Files
Socrates/apps/web/lib/sync/applyOps.ts
dtoro b55425cc68 Pivot to text-first column-stack workspace + merge-with-review across AI artifacts
Workspace
- Pivot from "set of open panes" to a Finder-style miller column stack:
  TopBar / LeftSidebar / [section → entity → entity ...] / pinned text editor.
  openPanesStore is now an ordered Column[] with pushFrom / closeFrom /
  setStack; only one top-level section is rooted at a time.
- New entity column panes: Term, Block, Association, Constraint,
  Requirement, Finding. Click-through navigation truncates deeper
  columns automatically.
- LeftSidebar surfaces a pending-count chip per section (single-glance
  navigation cue) and spins its analyze ↻ via SVG Spinner whenever the
  LLM is working — including server-initiated runs caught by the runs
  poll, not just user-triggered ones.

Analyze pipeline + persistence
- Unified `concepts` pass (taxonomy + glossary in one LLM call) replaces
  the two-pass setup. Server still accepts ?section=taxonomy|glossary
  and normalizes them for back-compat.
- model / requirements / detection (assumptions, risks, inconsistencies)
  + cross-layer validation rules (X1–X4: stale term link, unlinked
  formalism, undefined linked term, prose-only term).
- Persistence: NarrativeDocument, ModelSnapshot, ChangelogEntry,
  TaxonomyTerm, RequirementEntry, Finding, AnalysisRun. Re-runs MERGE
  instead of replace: gentle update on existing items, suggested on new,
  deprecated on missing — same idiom for every artifact kind. User pins
  preserve "kept" decisions across re-analyses.
- Migrations: pivot_text_first, add_requirement_linked_term,
  term_review_state, review_state_for_reqs_and_findings,
  add_term_definition_pinned.

Concept ↔ ontology integration
- linkedTermId on Block / Association / Constraint / Requirement.
  PromoteToolbar lets the user formalize a concept inline: + Block /
  + Association / + Constraint / + Requirement, all routed through
  applyOps so undo/redo and SSE work for free.
- decideElement op for in-canvas keep/discard on review-pending model
  elements.

User-authored definitions
- TermColumn definition is click-to-edit. Save (Cmd-Enter / blur),
  Cancel (Esc), Reset to AI suggestion when pinned.
- definitionPinned flag on TaxonomyTerm: future Analyze runs leave the
  user's text alone. setTermDefinition repo function + POST
  /api/projects/[id]/terms/[termId]/definition endpoint.
- mergeTaxonomySuggestion + applyGlossaryDefinitions both pin-aware.

UX/UI
- StatusChip: single component for all state idioms (suggested,
  deprecated, accepted, dismissed, resolved, severity, validation code,
  confidence, warn). Replaces 5+ ad-hoc badge classes.
- PaneControls (PaneViewTabs + PaneFilterChip): separates view-mode
  toggles from filter chips so toggling Pending no longer flips you off
  the current view.
- PaneEmpty: unified empty-state with title + hint + action.
- PaneDrawer: collapsible groups for Pending / Discarded review; cards
  group as Kept (top) → Pending (bottom drawer) → Discarded (Findings
  only, hidden when empty). Restore action recovers dismissed/resolved
  findings.
- ConceptCard unifies Tree and A–Z views in Concepts; only Tree parents
  carry the chevron (no empty placeholder offset).
- Type + spacing tokens (--text-xs..xl, --space-1..6, --lh-tight/ui/
  prose, --radius-*) replace every ad-hoc value.
- Buttons standardized to body sans 500 (was a mishmash of mono / display).
- Card shells unified across Concepts / Requirements / Findings.

Cleanup
- Removed: LeftRail, FindingsPanel, IssuesPanel, SocratesDock,
  ProposalCard, SlashMenu, SlashExtension, slashSuggestion,
  CanvasHeader, TaxonomyPane, GlossaryPane, TermDetail (popover; now
  TermColumn).
- Section ids in openPanesStore: dropped taxonomy/glossary, added
  concepts. localStorage migration runs on hydrate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 00:12:06 +02:00

289 lines
11 KiB
TypeScript

// The single chokepoint for SysMLModel mutations.
//
// Pure: (model, ops) → { model, idMapping, errors }. No DB / network here.
// M5 in-memory: tempIds are used as canonical ids when free, otherwise
// rewritten with a `_n` suffix. The DB layer (later) will replace this with
// server-issued ids.
//
// applyOps is atomic per-batch: if any op fails validation, the entire
// batch is rejected and the original model is returned unchanged. This is
// the contract docs/sync.md §4 specifies.
import type { SysMLModel, Block, Association, Constraint, Requirement } from "../sysml/model";
import type { ModelOp } from "./ops";
export interface ApplyResult {
model: SysMLModel;
/** Map of any tempId → assigned canonical id. */
idMapping: Record<string, string>;
errors: ApplyError[];
/** True iff the batch landed without errors. */
applied: boolean;
}
export interface ApplyError {
opIndex: number;
code: "DUPLICATE_ID" | "MISSING_ELEMENT" | "INVALID_PATCH";
message: string;
}
export function applyOps(model: SysMLModel, ops: ModelOp[]): ApplyResult {
const idMapping: Record<string, string> = {};
const errors: ApplyError[] = [];
// Fail-fast working copy. We mutate this; if errors accumulate we throw it
// away and return the original.
let next = cloneModel(model);
for (let i = 0; i < ops.length; i++) {
const op = ops[i]!;
try {
next = applyOne(next, op, idMapping);
} catch (err) {
errors.push({ opIndex: i, code: classifyError(err), message: (err as Error).message });
}
}
if (errors.length > 0) {
return { model, idMapping: {}, errors, applied: false };
}
return { model: next, idMapping, errors: [], applied: true };
}
// ─── Per-op application ──────────────────────────────────────────────────
function applyOne(model: SysMLModel, op: ModelOp, idMapping: Record<string, string>): SysMLModel {
switch (op.kind) {
case "add-block": {
const id = resolveAddId(op.block.id, op.tempId, idMapping, model.blocks.map(b => b.id));
const block: Block = { ...op.block, id };
return { ...model, blocks: [...model.blocks, block] };
}
case "update-block": {
const realId = idMapping[op.blockId] ?? op.blockId;
assertExists(model.blocks, realId, "block");
return {
...model,
blocks: model.blocks.map(b => (b.id === realId ? { ...b, ...op.patch } : b)),
};
}
case "remove-block": {
const realId = idMapping[op.blockId] ?? op.blockId;
assertExists(model.blocks, realId, "block");
// Cascade: drop incident associations + requirement satisfiers + constraint applies-to
return {
...model,
blocks: model.blocks.filter(b => b.id !== realId),
associations: model.associations.filter(a => a.fromBlockId !== realId && a.toBlockId !== realId),
constraints: model.constraints.map(c => ({ ...c, appliesTo: c.appliesTo.filter(id => id !== realId) })),
requirements: model.requirements.map(r => ({
...r,
relations: r.relations.filter(rel => rel.kind !== "satisfy" || rel.blockId !== realId),
})),
};
}
case "add-property": {
const blockId = idMapping[op.blockId] ?? op.blockId;
const block = model.blocks.find(b => b.id === blockId);
if (!block) throw missing("block", blockId);
const propId = resolveAddId(op.property.id, op.tempId, idMapping, block.properties.map(p => p.id));
return {
...model,
blocks: model.blocks.map(b =>
b.id === blockId ? { ...b, properties: [...b.properties, { ...op.property, id: propId }] } : b
),
};
}
case "update-property": {
const blockId = idMapping[op.blockId] ?? op.blockId;
return {
...model,
blocks: model.blocks.map(b =>
b.id === blockId
? { ...b, properties: b.properties.map(p => (p.id === op.propertyId ? { ...p, ...op.patch } : p)) }
: b
),
};
}
case "remove-property": {
const blockId = idMapping[op.blockId] ?? op.blockId;
return {
...model,
blocks: model.blocks.map(b =>
b.id === blockId ? { ...b, properties: b.properties.filter(p => p.id !== op.propertyId) } : b
),
};
}
case "add-association": {
const id = resolveAddId(op.association.id, op.tempId, idMapping, model.associations.map(a => a.id));
const association: Association = {
...op.association,
id,
fromBlockId: idMapping[op.association.fromBlockId] ?? op.association.fromBlockId,
toBlockId: idMapping[op.association.toBlockId] ?? op.association.toBlockId,
};
return { ...model, associations: [...model.associations, association] };
}
case "update-association": {
const realId = idMapping[op.associationId] ?? op.associationId;
assertExists(model.associations, realId, "association");
return {
...model,
associations: model.associations.map(a => (a.id === realId ? { ...a, ...op.patch } : a)),
};
}
case "remove-association": {
const realId = idMapping[op.associationId] ?? op.associationId;
assertExists(model.associations, realId, "association");
return { ...model, associations: model.associations.filter(a => a.id !== realId) };
}
case "add-constraint": {
const id = resolveAddId(op.constraint.id, op.tempId, idMapping, model.constraints.map(c => c.id));
const constraint: Constraint = {
...op.constraint,
id,
appliesTo: op.constraint.appliesTo.map(b => idMapping[b] ?? b),
};
return { ...model, constraints: [...model.constraints, constraint] };
}
case "update-constraint": {
const realId = idMapping[op.constraintId] ?? op.constraintId;
assertExists(model.constraints, realId, "constraint");
return {
...model,
constraints: model.constraints.map(c => (c.id === realId ? { ...c, ...op.patch } : c)),
};
}
case "remove-constraint": {
const realId = idMapping[op.constraintId] ?? op.constraintId;
assertExists(model.constraints, realId, "constraint");
return { ...model, constraints: model.constraints.filter(c => c.id !== realId) };
}
case "add-requirement": {
const id = resolveAddId(op.requirement.id, op.tempId, idMapping, model.requirements.map(r => r.id));
const requirement: Requirement = { ...op.requirement, id };
return { ...model, requirements: [...model.requirements, requirement] };
}
case "update-requirement": {
const realId = idMapping[op.requirementId] ?? op.requirementId;
assertExists(model.requirements, realId, "requirement");
return {
...model,
requirements: model.requirements.map(r => (r.id === realId ? { ...r, ...op.patch } : r)),
};
}
case "remove-requirement": {
const realId = idMapping[op.requirementId] ?? op.requirementId;
assertExists(model.requirements, realId, "requirement");
return { ...model, requirements: model.requirements.filter(r => r.id !== realId) };
}
case "add-relation": {
const realId = idMapping[op.requirementId] ?? op.requirementId;
assertExists(model.requirements, realId, "requirement");
return {
...model,
requirements: model.requirements.map(r =>
r.id === realId ? { ...r, relations: [...r.relations, op.relation] } : r
),
};
}
case "remove-relation": {
const realId = idMapping[op.requirementId] ?? op.requirementId;
assertExists(model.requirements, realId, "requirement");
return {
...model,
requirements: model.requirements.map(r =>
r.id === realId
? { ...r, relations: r.relations.filter((_, idx) => idx !== op.relationIndex) }
: r
),
};
}
case "decide-element": {
const realId = idMapping[op.element.id] ?? op.element.id;
const flip = <T extends { id: string; reviewStatus?: import("../sysml/model").ReviewStatus; reviewPinned?: boolean }>(arr: T[]): T[] =>
arr.map(e =>
e.id === realId
? {
...e,
reviewStatus: "accepted" as const,
reviewPinned: e.reviewStatus === "deprecated" ? true : !!e.reviewPinned,
}
: e
);
switch (op.element.kind) {
case "block":
assertExists(model.blocks, realId, "block");
return { ...model, blocks: flip(model.blocks) };
case "association":
assertExists(model.associations, realId, "association");
return { ...model, associations: flip(model.associations) };
case "constraint":
assertExists(model.constraints, realId, "constraint");
return { ...model, constraints: flip(model.constraints) };
case "requirement":
assertExists(model.requirements, realId, "requirement");
return { ...model, requirements: flip(model.requirements) };
}
}
}
}
// ─── Helpers ─────────────────────────────────────────────────────────────
function cloneModel(model: SysMLModel): SysMLModel {
// Shallow-clone collections; nested objects are immutable per our op contract.
return {
systemOfInterestId: model.systemOfInterestId,
blocks: model.blocks.map(b => ({ ...b, properties: [...b.properties], stereotypes: [...b.stereotypes] })),
associations: model.associations.map(a => ({ ...a })),
constraints: model.constraints.map(c => ({ ...c, appliesTo: [...c.appliesTo] })),
requirements: model.requirements.map(r => ({ ...r, relations: [...r.relations] })),
};
}
/**
* Decide what id to use for a newly-added element.
* - If the requested id is unused, it sticks. (Most common path.)
* - Otherwise, append `_2`, `_3`, … until free, and record the mapping from
* the requested id to the assigned id so subsequent ops in the same batch
* can reference the new element by its tempId.
*/
function resolveAddId(
desiredId: string,
tempId: string | undefined,
idMapping: Record<string, string>,
existing: string[]
): string {
const taken = new Set(existing);
if (!taken.has(desiredId)) {
if (tempId) idMapping[tempId] = desiredId;
return desiredId;
}
let suffix = 2;
while (taken.has(`${desiredId}_${suffix}`)) suffix++;
const final = `${desiredId}_${suffix}`;
if (tempId) idMapping[tempId] = final;
idMapping[desiredId] = final;
return final;
}
function assertExists<T extends { id: string }>(items: T[], id: string, what: string): void {
if (!items.find(i => i.id === id)) throw missing(what, id);
}
function missing(what: string, id: string): Error {
return new Error(`${what} "${id}" not found`);
}
function classifyError(err: unknown): ApplyError["code"] {
const msg = (err as Error).message ?? "";
if (msg.includes("not found")) return "MISSING_ELEMENT";
if (msg.includes("duplicate")) return "DUPLICATE_ID";
return "INVALID_PATCH";
}