Files
Socrates/apps/web/components/socrates/ProposalCard.tsx
dtoro 4b8e3f04ee MVP M7: Socrates can propose model changes — review impact + Accept/Reject
The dock now has a "propose" button that asks Socrates to suggest one
high-value structural change. He returns a structured payload (reasoning
+ ops + impactSummary) which renders as a ProposalCard inline in the
thread. Accept routes the ops through the same useApply() pipeline as
user-originated edits (optimistic local + persisted POST + server
reconciliation).

apps/web/lib/llm/prompts/socrates/propose.md
- Promoted verbatim from phase-0/src/prompts/.

apps/web/lib/llm/proposeChange.ts
- Server-side proposeChange() — calls the LLM with character + propose
  prompts + trimmed model + active issues. JSON Schema uses oneOf per
  op kind (Phase 0 lesson: small models need this to produce real op
  shapes instead of cramming everything into the kind name).
- normalizeOps() converts the LLM-emitted op shapes into canonical
  ModelOp[] (fills in property ids/multiplicity defaults, expands
  satisfiedBy[] into RequirementRelation[], splits PropertyType union
  per kind).

apps/web/lib/sysml/impact.ts
- Pure pre-apply impact analysis. Runs the ops through the same
  applyOps() reducer locally, then diffs:
    - structural: added / removed / changed elements (per kind)
    - validation: issues created vs resolved (by canonical issue key)
    - dep-graph blast radius (closure of touched element ids on the
      post-apply graph)
  Headline stats summarized as deltas (+1 block, −1 assoc, etc.) for
  the proposal card.

apps/web/app/api/projects/[projectId]/socrates/propose
- POST: returns { reasoning, ops, impactSummary, meta }. Pure read of
  the model — does not apply anything; client must POST /apply with the
  same ops to commit.

apps/web/components/socrates/ProposalCard.tsx
- In-dock card: PROPOSAL tag + delta stats / reasoning / collapsible
  ops list / Impact section (added/removed/changed) / Validation diff
  (resolves ✓ / creates ⚠) / Accept + Reject. Disabled when impact
  analysis flagged the apply as illegal.

apps/web/components/socrates/SocratesDock.tsx
- New "propose" button between the input field and send. Renders
  ProposalCard for assistant turns of role "proposal". Accept calls
  useApply(); on success the card collapses to a "✓ Applied" system
  bubble. On apply failure the dock shows the structured error
  messages.
- New "system" bubble role for apply confirmations + dismissals.

apps/web/components/diagram-canvas/DiagramCanvas.tsx
- Bug fix: new blocks/constraints arriving via the model→RF sync (e.g.
  from accepted proposals) are now positioned to the right of the
  existing layout instead of stacking at (0, 0) offscreen.

apps/web/lib/sync/ModelStore.tsx
- Bug fix / observability: background-POST failures and version
  mismatches now log to the console with structured context instead of
  being silently swallowed. The server's authoritative state still
  replaces the optimistic local state on response, but the user can now
  see why their accept appeared to do nothing (typically: page tab
  was at version N but server had advanced to N+1).
2026-04-30 00:27:29 +02:00

209 lines
7.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// In-dock card showing a Socrates-proposed change.
//
// Displays: reasoning, op summary, impact summary (added/removed/changed +
// validation diff), and Accept / Reject controls. Accept calls into the
// ModelStore which routes through the same applyOps + persistence pipeline
// as user-originated edits.
"use client";
import { useState } from "react";
import type { ImpactSummary } from "../../lib/sysml/impact";
import type { ModelOp } from "../../lib/sync/ops";
export interface ProposalPayload {
reasoning: string;
ops: ModelOp[];
impactSummary: ImpactSummary;
meta?: { provider?: string; model?: string };
}
interface ProposalCardProps {
proposal: ProposalPayload;
onAccept: () => Promise<void> | void;
onReject: () => void;
pending?: boolean;
}
export function ProposalCard({ proposal, onAccept, onReject, pending }: ProposalCardProps) {
const [busy, setBusy] = useState(false);
const { reasoning, ops, impactSummary } = proposal;
async function accept() {
if (busy) return;
setBusy(true);
try {
await onAccept();
} finally {
setBusy(false);
}
}
return (
<div className={`proposal-card ${pending ? "proposal-card-pending" : ""}`}>
<div className="proposal-card-head">
<span className="proposal-card-tag">PROPOSAL</span>
<span className="proposal-card-stats">
{summarizeStats(impactSummary)}
</span>
</div>
<div className="proposal-card-reasoning">{reasoning}</div>
{ops.length > 0 && (
<details className="proposal-card-ops" open>
<summary>Ops · {ops.length}</summary>
<ul>
{ops.map((op, i) => (
<li key={i}>{summarizeOp(op)}</li>
))}
</ul>
</details>
)}
{(impactSummary.added.length > 0 || impactSummary.removed.length > 0 || impactSummary.changed.length > 0) && (
<div className="proposal-card-section">
<div className="proposal-card-section-label">Impact</div>
<div className="proposal-card-impact-grid">
{impactSummary.added.length > 0 && (
<div className="proposal-card-impact-row">
<span className="proposal-card-impact-key">+ added</span>
<span className="proposal-card-impact-val">
{impactSummary.added.map(e => `${e.label} (${e.kind})`).join(", ")}
</span>
</div>
)}
{impactSummary.removed.length > 0 && (
<div className="proposal-card-impact-row">
<span className="proposal-card-impact-key"> removed</span>
<span className="proposal-card-impact-val">
{impactSummary.removed.map(e => `${e.label} (${e.kind})`).join(", ")}
</span>
</div>
)}
{impactSummary.changed.length > 0 && (
<div className="proposal-card-impact-row">
<span className="proposal-card-impact-key">~ changed</span>
<span className="proposal-card-impact-val">
{impactSummary.changed.map(e => `${e.label} (${e.kind})`).join(", ")}
</span>
</div>
)}
</div>
</div>
)}
{(impactSummary.issuesCreated.length > 0 || impactSummary.issuesResolved.length > 0) && (
<div className="proposal-card-section">
<div className="proposal-card-section-label">Validation</div>
{impactSummary.issuesResolved.length > 0 && (
<ul className="proposal-card-issue-list proposal-card-issues-resolved">
{impactSummary.issuesResolved.slice(0, 4).map((i, idx) => (
<li key={idx}> resolves {i.code}: {i.message}</li>
))}
</ul>
)}
{impactSummary.issuesCreated.length > 0 && (
<ul className="proposal-card-issue-list proposal-card-issues-created">
{impactSummary.issuesCreated.slice(0, 4).map((i, idx) => (
<li key={idx}> creates {i.code}: {i.message}</li>
))}
</ul>
)}
</div>
)}
{!impactSummary.ok && (
<div className="proposal-card-section proposal-card-error">
<div className="proposal-card-section-label">Cannot apply</div>
<ul className="proposal-card-issue-list">
{impactSummary.errors.map((e, i) => (
<li key={i}>{e.code}: {e.message}</li>
))}
</ul>
</div>
)}
<div className="proposal-card-actions">
<button
type="button"
className="proposal-card-btn proposal-card-btn-primary"
onClick={accept}
disabled={busy || pending || !impactSummary.ok || ops.length === 0}
>
{busy ? "Applying…" : "Accept"}
</button>
<button
type="button"
className="proposal-card-btn"
onClick={onReject}
disabled={busy || pending}
>
Reject
</button>
</div>
{proposal.meta?.model && (
<div className="proposal-card-meta">
via {proposal.meta.provider} · {proposal.meta.model}
</div>
)}
</div>
);
}
function summarizeStats(impact: ImpactSummary): string {
if (!impact.ok) return "would not apply";
const parts: string[] = [];
const { stats } = impact;
if (stats.blocksDelta) parts.push(`${signed(stats.blocksDelta)} block${Math.abs(stats.blocksDelta) === 1 ? "" : "s"}`);
if (stats.associationsDelta) parts.push(`${signed(stats.associationsDelta)} assoc`);
if (stats.constraintsDelta) parts.push(`${signed(stats.constraintsDelta)} constraint${Math.abs(stats.constraintsDelta) === 1 ? "" : "s"}`);
if (stats.requirementsDelta) parts.push(`${signed(stats.requirementsDelta)} req${Math.abs(stats.requirementsDelta) === 1 ? "" : "s"}`);
if (stats.issuesDelta) parts.push(`${signed(stats.issuesDelta)} issue${Math.abs(stats.issuesDelta) === 1 ? "" : "s"}`);
if (parts.length === 0) parts.push("structural rearrangement");
return parts.join(" · ");
}
function signed(n: number): string {
return n > 0 ? `+${n}` : `${n}`;
}
function summarizeOp(op: ModelOp): string {
switch (op.kind) {
case "add-block":
return `+ block "${op.block.label}" (${op.block.kind})`;
case "remove-block":
return ` block ${op.blockId}`;
case "update-block":
return `~ block ${op.blockId}`;
case "add-association":
return `+ assoc ${op.association.fromBlockId}${op.association.toBlockId} (${op.association.kind})`;
case "remove-association":
return ` assoc ${op.associationId}`;
case "update-association":
return `~ assoc ${op.associationId}`;
case "add-constraint":
return `+ constraint "${op.constraint.label}"`;
case "remove-constraint":
return ` constraint ${op.constraintId}`;
case "update-constraint":
return `~ constraint ${op.constraintId}`;
case "add-requirement":
return `+ req ${op.requirement.tag}`;
case "remove-requirement":
return ` req ${op.requirementId}`;
case "update-requirement":
return `~ req ${op.requirementId}`;
case "add-property":
return `+ property ${op.blockId}.${op.property.name}`;
case "update-property":
return `~ property ${op.blockId}.${op.propertyId}`;
case "remove-property":
return ` property ${op.blockId}.${op.propertyId}`;
case "add-relation":
return `+ relation ${op.requirementId}.${op.relation.kind}`;
case "remove-relation":
return ` relation ${op.requirementId}[${op.relationIndex}]`;
}
}