diff --git a/.agents/adr/implemented/architecture/2026-11-10-canvas-composition-and-pattern-packages.md b/.agents/adr/implemented/architecture/2026-11-10-canvas-composition-and-pattern-packages.md new file mode 100644 index 000000000..4d90fb99d --- /dev/null +++ b/.agents/adr/implemented/architecture/2026-11-10-canvas-composition-and-pattern-packages.md @@ -0,0 +1,171 @@ +# ADR: Canvas Composition and Pattern Packages — Strategy Orchestration Cutover + +Status: implemented — the cutover landed across v1.239–v1.248: P3 composition and approval (v1.239), Apply/Execute (v1.241), the P4 dual-read loader (v1.242–v1.243), P5 IR-primary authoring (v1.243), P6 conditions 2–7 (v1.243–v1.247), and P6 condition 1 in v1.248, where embedded and sample strategies construct their `WorkflowDocument` from the embedded `preset.yaml` plus compiled-in assets, `resolve_applied_document` returns that document with `apply_id = "embedded:"` and the canonical content hash, admission freezes the identity, recovery re-compares it, and every remaining embedded execution path refuses rather than building a manifest graph. `preset.yaml` stays the authoring and persistence format; `ir-twins/*.json` is a CI equivalence artifact and no production path reads it. +Date: 2026-11-10 +Scope: The strategy-orchestration cutover, complete. Every shipped surface is described by the composition spec rather than here: the Canvas composition surface, the compose operations, the pattern packages, the candidate lifecycle up to Approve, Apply/Execute, the P4 dual-read loader, P5 IR-primary authoring, the IR-primary Canvas intake with `preset generate`, and the embedded-strategy IR execution source. `preset.yaml` import/export is retained as the compatibility format. +Source: split from the archived Canvas + Workflow IR redesign and Dynamic Workflow Generation and Orchestration Simulation records + +## Problem + +P0/P1 shipped the [Workflow IR document model](../../implemented/architecture/2026-11-10-workflow-ir-document-model.md), +P2 shipped the [strategy simulation fence](../../implemented/architecture/2026-11-10-strategy-simulation-fence.md), +P3 shipped composition and approval in v1.239, and P3.5 shipped Apply/Execute in v1.241. Canvas +composes, packages are published with pinned identity, a candidate can be simulated and approved, +and an approved snapshot becomes the identity production intake reads. + +Two stakes drove this record. Both were closed with a limit rather than cleanly, and both limits are +closed too: approved identity is no longer persisted-but-never-applied, and the candidate lifecycle no +longer stops at Approve. The applied identity survives admission and recovery (I-000443), and an +unbuildable document no longer applies — `validate_ir_buildability` runs in +`crates/nexus-core/src/apply.rs` before the apply row is written, so the refusal intake would raise +(I-000448) lands as `DocumentUnbuildable` at Apply instead. + +1. **Production intake was YAML-first.** A controlled dual-read transition had to exist before + IR-primary execution could replace the YAML-only mapper. It could begin on imported preset bundles + — the intake of the time — but the applied path already existed, so dual-read was a loader decision + rather than a missing stage. +2. **New strategy authoring, compatibility export, and retirement of the hand-authored YAML main path** + needed explicit exit criteria so the two grammars would not evolve independently. + +## Decision + +### 1–4. Shipped surface — read the spec, not this record + +The composition surface, the nest/compose operations, the pattern-package contract and the candidate +lifecycle up to Approve shipped in v1.239 (#515). Apply/Execute followed in v1.241 (#520) as its own +stage, which P6's fourth acceptance item ("compose and generate candidates pass validate, simulate, +approve, and apply") and §6's rollback-by-new-Apply both assume. + +That stage preceded P4 in practice, as predicted: dual-read began by loading imported preset bundles to +prove the IR→Graph mapping, and an *applied* IR identity then existed to load. What P3.5 did not settle +was durability — the applied identity answered admission and recovery from the YAML descriptor, so a +restart reverted to the preset graph (I-000443) — which made that question P4's opening problem rather +than its follow-up. It is closed: see §5. + +The shipped contract — manifest fields, the content-hash pin, the four operations and their CAS, the +approval freeze, the flag and its per-audience default — lives in +[the composition spec](../../../../docs/specs/orchestration/strategy-composition.md). Two facts from the +implementation are decisions rather than contract details: + +- **The pin is the canonical content hash of the fragment.** The manifest version is a label; a package + edited under an unchanged version must fail closed, which is why approve records and verifies hashes. +- **A compose operation is refused, not repaired, when the parent level cannot carry what it would + receive.** `unnest` refuses rather than dropping a body's role/asset/signal declarations or the removed + slot's own control references. + +### 5. P4–P6 ladder, as shipped + +P0/P1/P2 are governed by their implemented records. P3 and P3.5 are governed by the composition spec. + +P3.5's exit criteria were met as stated — an approved candidate is applied and an existing schedule runs +from that applied identity, and a rollback installs the previous snapshot through a new Apply. The +qualification P3.5 carried — authoritative within one process lifetime only — is closed: admission +resolves a strategy's current apply before it validates bindings, and recovery re-enters that same +resolution, so a daemon restart during an in-flight applied run rebuilds the applied graph. At admission +the role set bound to providers comes from the document that runs, and recovery reads the frozen +descriptor's `agent_bindings` rather than resolving them again (I-000443). That reuse cannot cross +documents: recovery compares the identity admission froze with the strategy's current apply and refuses +with `reconstruction_unavailable` before it builds anything, so a re-apply during an in-flight run is a +refused restart rather than bindings from one document and a graph from another. + +The composition spec owns the resulting precedence: a user bundle with a current apply runs from the +applied document, every other strategy keeps its descriptor, and — since v1.248 — an embedded preset +resolves its document from the embedded bundle and freezes `embedded:` with the canonical +content hash, so no embedded execution path reads a manifest graph. + +P4's buildability half (I-000448) landed in `da84c588f`: `crates/nexus-core/src/apply.rs` refuses an +unbuildable document through the same `validate_ir_buildability` the intake runs +(`validate_ir_buildability` in `crates/nexus-orchestration/src/preset_runtime.rs`), before the +`INSERT INTO strategy_applies` (`apply_strategy` in `crates/nexus-core/src/apply.rs`). The limits that +remain on the applied path (I-000449, I-000462–I-000465) are recorded there rather than here. + +P4's third exit criterion — the IR→Graph mapping compared against the IR→Task table in +orchestration-engine §8.2.1 — is satisfied. The evidence is the amended table itself: §8.2.1 carries nine +amendments (`8e6f22225` plus the QC correction round) and no longer states anything the projection does +not do. Reading §8.2.1 against `build_wired_outer_graph_from_ir` +(`build_wired_outer_graph_from_ir` in `crates/nexus-orchestration/src/preset_runtime.rs`) yields 34 +constructs — 25 already matching, 8 whose table row was the stale side, 1 the table omitted, 0 where the +code diverged. Node-type coverage is closed in both directions; the one real omission found — the +inner-graph synthetic `end` task — is now in the table; edge semantics were corrected in four places; +and no third mapping exists. The criterion is tracked by I-000508. The old §8.2.1 prose promised an +`ir_unmappable` refusal for `nests[]` that no guard enforces; the amended table states the truth (the +projection does not read `nests[]`) and the hardening is an issue, not a gap in this decision. + +| Phase | Change | Exit criteria | +| --- | --- | --- | +| **P4 Dual-read loader** | Engine loads applied IR or a preset bundle, and applied IR survives admission and recovery | Met: existing YAML-preset schedules ran unchanged; the applied identity is authoritative across a daemon restart; the IR→Graph mapping matches the IR→Task table | +| **P5 IR-primary authoring** | Documentation and samples are authored as IR; YAML export remains compatibility output | Met: repository strategies land as IR | +| **P6 Retire hand-authored YAML main path** | Hand-edit and YAML patch cease to be the default authoring/intake path; import/export remains | Met: the retirement gate below passes, the legacy mapper is off, and the import tool remains | + +### 6. Dual-read, coexistence, and rollback + +| Stage | Intake/write behavior | +| --- | --- | +| Dual-read | Loader accepts applied IR or preset bundle; both use the shared semantic core | +| IR-primary write | Generate/Compose and new edits write IR with revision CAS; YAML export is derived | +| IR-primary execute | Production admission prefers applied IR identity, including embedded bundles | +| Retire hand-authored main path | The YAML mapper is off for the primary path; partner/integrator import/export remains | + +YAML and IR never become independently evolving grammars: `nexus-preset` is the import/compat loader, +retains `PresetSourceIdentity` hash semantics, and shares semantic validation with IR. + +Rollback of a bad Apply installs the previous approved snapshot through a new Apply; it never rewrites a +hash silently. Execute continues refusing missing or changed source bytes. Both shipped in v1.241: +rollback is an append naming a superseded approval, and intake refuses bytes that no longer hash to the +recorded identity (`applied_document_changed`) or cannot be read at all +(`applied_document_unverifiable`). Pattern and asset hashes recorded at Approve participate in source +freeze. + +### 7. Retirement scope + +Retired as the primary paths: + +- Hand-authored `preset.yaml` as the primary authoring path. +- TypeScript `parsePresetYaml` + `buildStrategyGraph` as the sole Canvas source. +- `strategy.patch_*` YAML mutators as the sole write path. +- YAML→Graph as the sole production intake. +- Copy-sample-directory reuse and explainability-only Canvas framing. + +The retained pieces are graph-flow, `OrchestrationEngine`, SessionStorage, `WaitingForInput` / `wait_id`, +the capability registry, source identity freeze, integrator versus creator-host execution surfaces, and +documented `preset.yaml` import/export. Outline, Timeline, World KB Canvas, Actor/Viewpoint preset IR, +Work-tree artifacts, and a first-party player app are not replaced. + +## Alternatives considered + +- **Keep Canvas explainability-only and extend YAML patches indefinitely.** Rejected: the human remains a YAML surgeon and cannot compose patterns or drafts as first-class IR units. +- **Make Canvas the only authoring entry or require drag-from-scratch.** Rejected: CLI, Agent, programmatic Compose, and Generate remain valid paths to the same candidate. +- **Make Canvas a read-only Agent-output viewer.** Rejected: it discards the composition duty. +- **Copy sample directories as the reuse mechanism.** Rejected: independently versioned packages with exact content pins provide reusable identity and fail-closed updates. +- **Allow hot update under an unchanged approved version.** Rejected: source identity would change silently; a new Approve/Apply is required. +- **Delete `preset.yaml` import/export at P6.** Rejected: partner/integrator bundles remain a public compatibility format; only the hand-authored main path retires. +- **Maintain YAML and IR as independent grammars.** Rejected: YAML becomes import/projection through the shared semantic core. +- **Big-bang intake replacement.** Rejected: P3.5–P6 preserve existing schedules, emergency YAML re-enable, mixed workspaces, and previous-snapshot rollback. +- **Replace graph-flow, add a first-party player, or absorb Work Artifact IR.** Rejected as separate or explicitly excluded responsibilities. + +## Consequences + +The retirement gate that P6 had to satisfy, all of it met on a reference workspace by v1.248: + +1. Samples and embedded creator strategies run from applied IR with YAML intake off. +2. The primary Strategy Canvas route calls `parsePresetYaml` only inside the legacy import wizard. +3. No CI job requires hand-maintained `preset.yaml` for new strategies; generated export may remain. +4. Compose and Generate candidates pass validate, simulate, approve, and apply. +5. Recovery refuses mismatches in IR content hash and recorded pattern/asset pins. +6. The `yaml-only` kill-switch was removed at its own boundary rather than left as a documented flag. +7. Existing partner/integrator bundles have a deprecation note and import path that converts them into candidates passing validation and simulation. + +The public bundle format was never cut without that compatibility path. + +### Standing constraints + +1. **Encoding and identity:** the implemented document-model record owns the schema/identity baseline; this decision creates no second encoding authority. +2. **Gate placement:** enqueue-time gates remain schedule-owned even when IR has metadata carriers; `cli_args` remains in `meta.cli_args`. +3. **Nest policy:** the depth limit and the choice between `expand_in_candidate` and `defer_until_apply` are exercised without permitting cycles or hidden effects. +4. **Generator home:** builtin capability, Develop-hub tool, and CLI-first operation share one candidate state and do not bypass the fence. +5. **Simulation fidelity:** P2 answers static reachability only; the Canvas preserves its disclosures rather than presenting it as output preview. +6. **Approval trust:** creator versus developer policy for third-party patterns must not create a weaker publish or Approve channel. +7. **Compatibility artifacts:** YAML exports are generated output, never a second authoring SSOT. +8. **Partial regeneration:** local Agent regeneration of nested regions merges by nest id into one candidate rather than creating shadow graphs. +9. **External effects:** simulation never promises exactly-once effects or commits write/external capabilities. +10. **Cutover availability:** YAML-only schedules and partner bundles survive through dual-read, the kill-switch window, and import/export rather than a breaking default change. diff --git a/.agents/adr/proposed/architecture/2026-11-10-canvas-composition-and-pattern-packages.md b/.agents/adr/proposed/architecture/2026-11-10-canvas-composition-and-pattern-packages.md deleted file mode 100644 index 4808ddfd4..000000000 --- a/.agents/adr/proposed/architecture/2026-11-10-canvas-composition-and-pattern-packages.md +++ /dev/null @@ -1,184 +0,0 @@ -# ADR: Canvas Composition and Pattern Packages — Strategy Orchestration Cutover - -Status: proposed — P6 is six of seven conditions in. P3 shipped in v1.239 (#515) and Apply/Execute in v1.241 (#520); P4 and P5 in v1.242–v1.243; P6 conditions 3, 5 and 7 in v1.243 (a committed `preset export` generator, the pin re-comparison at Apply and recovery, and a partner-bundle deprecation note with an import path); condition 6 in v1.243 and its `yaml-only` kill-switch removed at its own v1.244.0 boundary in v1.247; conditions 2 and 4 in v1.247 — the primary Canvas reads applied IR only (`parsePresetYaml` has no caller on that path) and `CoreService::generate_strategy_candidate` ships behind `nexus42 preset generate`, an agent tool and `POST /v1/daemon/strategies/{id}/generate` with a bounded lint-correct loop. **Condition 1 is not met**: samples and embedded creator strategies still execute the embedded `preset.yaml` (`nexus-preset/src/lib.rs` `load_embedded_preset`), and `applied_documents.rs` answers `None` for every non-user bundle, so no embedded strategy runs from applied IR. The twenty `ir-twins` that condition 1 was previously credited for prove twin/YAML conformance, not an execution source — that reading was wrong and this line now states what a symbol can show. -Date: 2026-11-10 -Scope: The strategy-orchestration cutover, complete except condition 1. Every shipped surface is described by the composition spec rather than here: the Canvas composition surface, the compose operations, the pattern packages and the candidate lifecycle **up to Approve** (v1.239), **Apply/Execute** (v1.241), the P4 dual-read loader (v1.242–v1.243) and P5 IR-primary authoring (v1.243), the IR-primary Canvas intake of v1.247 with `preset generate`, with `preset.yaml` import/export retained. What remains open is the embedded-strategy execution source: `load_embedded_preset` still reads `preset.yaml`, so condition 1 needs the embedded path switched before this record can move to `implemented/`. `parsePresetYaml` stays exported for an import surface that does not exist yet; its absence is tracked separately rather than claimed here. -Source: split from the archived Canvas + Workflow IR redesign and Dynamic Workflow Generation and Orchestration Simulation records - -## Problem - -P0/P1 shipped the [Workflow IR document model](../../implemented/architecture/2026-11-10-workflow-ir-document-model.md), -P2 shipped the [strategy simulation fence](../../implemented/architecture/2026-11-10-strategy-simulation-fence.md), -P3 shipped composition and approval in v1.239, and P3.5 shipped Apply/Execute in v1.241. Canvas -composes, packages are published with pinned identity, a candidate can be simulated and approved, -and an approved snapshot now becomes the identity production intake reads. What the cutover still -lacked when this section was written — P4 and P5 have since shipped, and P6's conditions 2 and 4 are -the remainder: - -Two stakes that drove this record are closed and are kept only because they explain why the -remaining stages are shaped as they are: approved identity is no longer persisted-but-never-applied, -and the candidate lifecycle no longer stops at Approve. Each was closed with a limit rather than -cleanly, and both limits are closed too: the applied identity survives admission and recovery -(I-000443), and an unbuildable document no longer applies — `validate_ir_buildability` runs in -`crates/nexus-core/src/apply.rs` before the apply row is written, so the refusal intake would raise -(I-000448) lands as `DocumentUnbuildable` at Apply instead. - -1. **Production intake was still YAML-first.** A controlled dual-read transition had to exist before - IR-primary execution could replace the YAML-only mapper. It could begin on imported preset bundles - — the intake of the time — but the applied path already existed, so dual-read was a loader decision - rather than a missing stage. -2. **New strategy authoring, compatibility export, and retirement of the hand-authored YAML main path** - needed explicit exit criteria so the two grammars would not evolve independently. - -## Proposal - -### 1–4. Shipped surface — read the spec, not this record - -The composition surface, the nest/compose operations, the pattern-package contract and the candidate -lifecycle **up to Approve** shipped in v1.239 (#515). **Apply/Execute followed in v1.241 (#520)** as -its own stage, which is what P6's fourth acceptance item ("compose and generate candidates pass -validate, simulate, approve, and apply") and §6's rollback-by-new-Apply both assume. - -That stage precedes P4 in practice, as predicted here: dual-read can begin by loading imported preset -bundles (today's intake) to prove the IR→Graph mapping, and an *applied* IR identity now exists to -load. What P3.5 did not settle was durability — the applied identity answered admission and recovery -from the YAML descriptor, so a restart reverted to the preset graph (I-000443) — which made that -question P4's opening problem rather than its follow-up. It is closed: see §5. - -The shipped contract — manifest fields, the content-hash pin, the four operations and their CAS, the -approval freeze, the flag and its per-audience default — lives in -[the composition spec](../../../../docs/specs/orchestration/strategy-composition.md). This record keeps -only the reasoning for what is still unshipped. - -Two facts from the shipped implementation worth carrying here, because they are decisions rather than -contract details: - -- **The pin is the canonical content hash of the fragment.** The manifest version is a label; a package - edited under an unchanged version must fail closed, which is why approve records and verifies hashes. -- **A compose operation is refused, not repaired, when the parent level cannot carry what it would - receive.** `unnest` refuses rather than dropping a body's role/asset/signal declarations or the removed - slot's own control references. - -### 5. P4–P6 ladder - -P0/P1/P2 shipped and are governed by their implemented records. P3 shipped in v1.239 and P3.5 in -v1.241, both governed by the composition spec. What remains: - -P3.5's own exit criteria were met as stated — an approved candidate is applied and an existing -schedule runs from that applied identity, and a rollback installs the previous snapshot through a -new Apply. The qualification P3.5 carried — authoritative within one process lifetime only — is -closed: admission resolves a strategy's current apply before it validates bindings, and recovery -re-enters that same resolution, so a daemon restart during an in-flight applied run rebuilds the -applied graph. At admission the role set bound to providers comes from the document that runs, and -recovery still reads the frozen descriptor's `agent_bindings` rather than resolving them again -(I-000443). That reuse can no longer cross documents: recovery compares the identity admission froze -with the strategy's current apply and refuses with a typed error, `reconstruction_unavailable`, before -it builds anything, so a re-apply during an in-flight run is a refused restart rather than bindings -from one document and a graph from another. -The composition spec owns the resulting precedence: a user bundle with a current apply runs -from the applied document, embedded and system presets have no apply branch, and every other -strategy keeps the YAML descriptor. P4's other half — the buildability predicate apply and intake -must share (I-000448) — landed after this record was written, in `da84c588f`: `crates/nexus-core/src/apply.rs` -refuses an unbuildable document through the same `validate_ir_buildability` the intake runs -(`validate_ir_buildability` in `crates/nexus-orchestration/src/preset_runtime.rs`), and it does so before the `INSERT INTO -strategy_applies` (`apply_strategy` in `crates/nexus-core/src/apply.rs`). The limits that remain on the applied path (I-000449, -I-000462–I-000465) are recorded there rather than here. P4's **third** exit criterion — the IR→Graph -mapping compared against the IR→Task table in orchestration-engine §8.2.1 — is satisfied. That criterion's evidence is the amended table itself, not a working note: §8.2.1 now -carries nine amendments (`8e6f22225` plus the QC correction round) and no longer states anything the -projection does not do. Reading §8.2.1 against `build_wired_outer_graph_from_ir` -(`build_wired_outer_graph_from_ir` in `crates/nexus-orchestration/src/preset_runtime.rs`) yields 34 constructs — 25 already matching, -8 whose table row was the stale side, 1 the table omitted, **0 where the code diverged** — which is -the comparison this criterion asked for, reproducible from the two tracked artifacts by anyone. -What it established, beyond that it ran: -node-type coverage is closed in both directions, the one real omission found — the inner-graph -synthetic `end` task (`build_inner_graphs` in `preset_runtime.rs`) — now being in the table; edge semantics were -corrected in four places (conditional routing is in-task `resolve_expression_target` → `GoTo` with -no builder edge, pinned by `parity_edges_conditional_and_default_route_by_expression` in `preset_runtime.rs`; `default` is the family fallback, not an edge; -`edges[kind=depends_on]` is a phantom with no producer and no reader; and the judge's no-go routes -rather than waits on every routed `next` form, pinned by `parity_exit_when_llm_judge_go_continues_and_nogo_waits` in `preset_runtime.rs`); and no -third mapping exists — -the five `NextTarget` forms all trace to table rows, and refusal names are generated from the -table's own row names (`IrOuterGraphError` in `preset_runtime.rs`). The zero `code-divergent` count is a result, not an -absence of effort: every rule-1 and rule-2 row diverged with the table as the stale side — what a -spec-only plan should expect — and the refusal and carrier rows matched symbol-for-symbol. The -criterion is tracked by I-000508. One hole the comparison surfaced stays open: the old §8.2.1 prose -promised an `ir_unmappable` refusal for `nests[]` that no guard enforces — the amended table now -states the truth (the projection does not read `nests[]`), the behaviour is unchanged, and the -hardening is filed as an issue rather than closed here. - -| Phase | Change | Exit criteria | -| --- | --- | --- | -| **P4 Dual-read loader** | Engine loads applied IR or a preset bundle, and applied IR survives admission and recovery | Existing YAML-preset schedules remain unbroken; an applied identity is authoritative across a daemon restart, not only within one process; IR→Graph mapping matches the IR→Task table in orchestration-engine §8.2.1 | -| **P5 IR-primary authoring** | Documentation and samples are authored as IR; YAML export remains compatibility output | New repository strategies land as IR | -| **P6 Retire hand-authored YAML main path** | Hand-edit and YAML patch cease to be the default authoring/intake path; import/export remains | Retirement acceptance below passes; the legacy YAML mapper defaults off in new installs and the import tool remains | - -P4 requires review of the P0/P1 IR→Task mapping table against existing YAML→Task semantics. P6 requires -the full retirement evidence and documented kill-switch below. - -### 6. Dual-read, coexistence, and rollback - -| Stage | Intake/write behavior | -| --- | --- | -| Dual-read | Loader accepts applied IR or preset bundle; both use the shared semantic core; Canvas may retain a YAML projection for legacy bundles | -| IR-primary write | Generate/Compose and new edits write IR with revision CAS; YAML export is derived | -| IR-primary execute | Production admission prefers applied IR identity; YAML-only bundles import on load; remaining YAML-only usage is observable | -| Retire hand-authored main path | YAML mapper defaults off for that path; partner/integrator import/export remains | - -The dual-read window allows emergency re-enable of YAML intake by configuration. YAML-only bundles and mixed workspaces remain supported until P6. YAML and IR never become independently evolving grammars: `nexus-preset` becomes the import/compat loader, retains `PresetSourceIdentity` hash semantics, and shares semantic validation with IR. - -Rollback of a bad Apply installs the previous approved snapshot through a new Apply; it never rewrites a hash silently. Execute continues refusing missing or changed source bytes. **Both shipped in v1.241:** rollback is an append naming a superseded approval, and intake refuses bytes that no longer hash to the recorded identity (`applied_document_changed`) or cannot be read at all (`applied_document_unverifiable`). Pattern and asset hashes recorded at Approve participate in source freeze. - -### 7. Retirement scope - -P3.5–P6 add, and P4–P6 replace: - -- Hand-authored `preset.yaml` as the primary authoring path. -- TypeScript `parsePresetYaml` + `buildStrategyGraph` as the sole Canvas source. -- `strategy.patch_*` YAML mutators as the sole write path. -- YAML→Graph as the sole production intake. -- Copy-sample-directory reuse and explainability-only Canvas framing. - -The retained pieces are graph-flow, `OrchestrationEngine`, SessionStorage, `WaitingForInput` / `wait_id`, capability registry, source identity freeze, integrator versus creator-host execution surfaces, and documented `preset.yaml` import/export. Outline, Timeline, World KB Canvas, Actor/Viewpoint preset IR, Work-tree artifacts, and a first-party player app are not replaced. - -The Canvas transition removes YAML-only projection from the hot path only after dual-read ends. Developer explainability is expected to become a read-only view of the applied document rather than YAML-first editing; no such surface ships today, and naming it here is a direction, not a claim about the codebase. - -## Alternatives considered - -- **Keep Canvas explainability-only and extend YAML patches indefinitely.** Rejected: the human remains a YAML surgeon and cannot compose patterns or drafts as first-class IR units. -- **Make Canvas the only authoring entry or require drag-from-scratch.** Rejected: CLI, Agent, programmatic Compose, and Generate remain valid paths to the same candidate. -- **Make Canvas a read-only Agent-output viewer.** Rejected: it discards the composition duty. -- **Copy sample directories as the reuse mechanism.** Rejected: independently versioned packages with exact content pins provide reusable identity and fail-closed updates. -- **Allow hot update under an unchanged approved version.** Rejected: source identity would change silently; a new Approve/Apply is required. -- **Delete `preset.yaml` import/export at P6.** Rejected: partner/integrator bundles remain a public compatibility format; only the hand-authored main path retires. -- **Maintain YAML and IR as independent grammars.** Rejected: YAML becomes import/projection through the shared semantic core. -- **Big-bang intake replacement.** Rejected: P3.5–P6 preserve existing schedules, emergency YAML re-enable, mixed workspaces, and previous-snapshot rollback. -- **Replace graph-flow, add a first-party player, or absorb Work Artifact IR.** Rejected as separate or explicitly excluded responsibilities. - -## Acceptance criteria - -P3, shipped in v1.239, required a staged creator compose→simulate→approve flow using two patterns. P4 exit requires existing YAML-preset schedules to run unchanged while applied IR loads through the reviewed IR→Task mapping. P5 exit requires new samples and strategies to land as IR with YAML only as compatibility export. - -P6 retirement requires all of the following on a reference workspace: - -1. Samples and embedded creator strategies run from applied IR with YAML intake off. -2. The primary Strategy Canvas route calls `parsePresetYaml` only inside the legacy import wizard. -3. No CI job requires hand-maintained `preset.yaml` for new strategies; generated export may remain. -4. Compose and Generate candidates pass validate, simulate, approve, and apply. -5. Recovery refuses mismatches in IR content hash and recorded pattern/asset pins. -6. A documented kill-switch re-enables YAML intake for one minor release after default-off; import/export remains afterward. -7. Existing partner/integrator bundles have a deprecation note and import path that converts them into candidates passing validation and simulation. - -P6 never cuts the public bundle format without that compatibility path. - -## Risks - -1. **Encoding and identity:** JSON, CBOR, or YAML-IR trade human diff friendliness against canonical hash stability. The implemented document-model record owns the schema/identity baseline; this proposal must not create another encoding authority. -2. **Gate placement:** enqueue-time gates remain schedule-owned even when IR has metadata carriers; `cli_args` remains in `meta.cli_args`. -3. **Nest policy:** the hard depth limit and the default between `expand_in_candidate` and `defer_until_apply` still need to be exercised without permitting cycles or hidden effects. -4. **Generator home:** builtin capability, Develop-hub tool, or CLI-first operation must not fork candidate state or bypass the fence. -5. **Simulation fidelity:** P2 answers static reachability only; Canvas must preserve its disclosures rather than presenting it as output preview. The current contract is linked to the implemented simulation record. -6. **Approval trust:** creator versus developer policy for third-party patterns, including trust labels or signatures, must not create a weaker publish or Approve channel. -7. **Compatibility artifacts:** whether dual-read YAML exports are Git-tracked generated output or local install artifacts must be explicit without making them a second authoring SSOT. -8. **Partial regeneration:** local Agent regeneration of nested regions must merge by nest id into one candidate rather than create shadow graphs. -9. **External effects:** simulation must never promise exactly-once effects or commit write/external capabilities. -10. **Cutover availability:** YAML-only schedules and partner bundles must survive P4/P6 through dual-read, kill-switch, and import/export rather than a breaking default change. diff --git a/.agents/adr/proposed/architecture/2026-11-10-lightweight-core-modular-packaging.md b/.agents/adr/proposed/architecture/2026-11-10-lightweight-core-modular-packaging.md index d1f94c32c..cbf66f29e 100644 --- a/.agents/adr/proposed/architecture/2026-11-10-lightweight-core-modular-packaging.md +++ b/.agents/adr/proposed/architecture/2026-11-10-lightweight-core-modular-packaging.md @@ -39,7 +39,7 @@ Observed on `main` @ `3263aa71f` (local analysis, Asia/Shanghai 2026-11-10): - Root `AGENTS.md` Development Policy treats running CI-scope `cargo clippy --all` / `cargo test --all` on every small edit as an anti-pattern (scoped `-p ` is the daily default); `pnpm run dev:backend:refresh` and the `build:cli` / `build:cli:release` scripts are the routine Cargo/codegen DX paths — full rebuild cost is already treated as a constraint. - `modules/nexus-module-sdk` is STANDALONE with `publish = true` — the right packaging precedent; most workspace crates still share `0.1.0`. -Landed so far — the layering half has partly landed. `crates/nexus-connect` owns the 8,400-line peer Connect stack that used to sit inside `nexus-core`, with the direction `nexus-core -> nexus-connect`; it is the first extraction the prototype could justify on measurement. The second and third extractions landed in v1.245 (#528): `crates/nexus-execution` owns 20,305 lines of the run driver behind an admission port (`nexus_core::owner` keeps the 14,797 lines that hold `Arc` and the inherent impls a foreign crate cannot write), and `crates/nexus-memory-provider` owns all 16,273 lines with `ProviderError` as its public error and `impl From for CoreError` in core. The packaging half's first verifiable step is the bracket in the header line: those five crates version in the contract bracket of `tooling/release/version-brackets.json`, which versions independently of the product, `assert-lockstep-version.mjs` enforces the two brackets, and `check-contract-packageability.mjs` proves them packageable offline in `rust-checks`. Still unstarted: an actual registry publish and the remaining extraction candidates — `nexus-orchestration::capability` (23,554 lines) and `nexus-orchestration::storage` (3,879). Per-crate changelogs exist for the five contract-bracket packages (`crates/nexus-contracts`, `crates/nexus-workflow-ir`, `modules/nexus-module-sdk`, `modules/nexus-module-manifest`, `modules/nexus-module-test`); the rest of the workspace has none. +Landed so far — the layering half has partly landed. `crates/nexus-connect` owns the 8,400-line peer Connect stack that used to sit inside `nexus-core`, with the direction `nexus-core -> nexus-connect`; it is the first extraction the prototype could justify on measurement. The second and third extractions landed in v1.245 (#528): `crates/nexus-execution` owns 20,305 lines of the run driver behind an admission port (`nexus_core::owner` keeps the 14,797 lines that hold `Arc` and the inherent impls a foreign crate cannot write), and `crates/nexus-memory-provider` owns all 16,273 lines with `ProviderError` as its public error and `impl From for CoreError` in core. The fourth extraction landed in v1.248: `crates/nexus-session-storage` owns `SessionId`, `SessionStatus`, `SessionSummary`, `StorageError`, `run_state` and `storage` (4,478 lines moved), with `nexus-orchestration::engine` re-exporting the three session types so consumers compiled unchanged, and no edge back from the new crate to orchestration. The packaging half's first verifiable step is the bracket in the header line: those five crates version in the contract bracket of `tooling/release/version-brackets.json`, which versions independently of the product, `assert-lockstep-version.mjs` enforces the two brackets, and `check-contract-packageability.mjs` proves them packageable offline in `rust-checks`. Still unstarted: an actual registry publish and the remaining extraction candidates — `nexus-orchestration::capability` (23,554 lines) and `nexus-orchestration::storage` (3,879). Per-crate changelogs exist for the five contract-bracket packages (`crates/nexus-contracts`, `crates/nexus-workflow-ir`, `modules/nexus-module-sdk`, `modules/nexus-module-manifest`, `modules/nexus-module-test`); the rest of the workspace has none. --- diff --git a/.agents/knowledge/conventions/parallel-worktrees-cargo-target-isolation.md b/.agents/knowledge/conventions/parallel-worktrees-cargo-target-isolation.md new file mode 100644 index 000000000..decf17825 --- /dev/null +++ b/.agents/knowledge/conventions/parallel-worktrees-cargo-target-isolation.md @@ -0,0 +1,47 @@ +# Parallel worktrees need separate Cargo target directories + +## Symptom + +A `cargo check -p ` inside one git worktree failed with a type error naming a symbol that exists only in +a different worktree: + +``` +the trait bound `PathBuf: AssetSource` is not satisfied + --> crates/nexus-core/src/strategy_candidates.rs:66 +``` + +Both worktrees were cut from the same commit; the failing worktree's `crates/nexus-preset/src/workflow_ir.rs` +matched `main` byte for byte and contained no such trait. The error came from a compiled artifact left by the +other worktree. + +## Cause + +Every worktree shared one `CARGO_TARGET_DIR`. Two checkouts hold the same package (`nexus-preset v0.1.0`) at +different paths, and the shared target directory's fingerprints can be satisfied by the other checkout's output, +so a build compiles against the wrong `nexus-preset`. + +`touch` on the file that "should not have the symbol" forced a rebuild and the check passed in seconds — the +signature of a stale artifact, not a source defect. + +## Rule + +One target directory per worktree: + +```bash +CARGO_TARGET_DIR="$HOME/.cache/nexus-target/" cargo test -p +``` + +Alternatively, serialize builds: never run two worktrees' cargo concurrently against one shared directory. + +## Diagnosis order + +When a cross-worktree type error names a symbol that does not exist in the current worktree: + +1. `md5`/`git diff` the named file against `main` — confirm the symbol is absent. +2. `touch` the file and re-run — a pass confirms the cache. +3. Only then treat it as a source defect. + +## Cost of not following it + +A whole round was spent reporting the error as "pre-existing" and re-verifying it on `main`, where it did not +reproduce at all. The false report then had to be checked and discarded by the coordinator. diff --git a/.agents/knowledge/conventions/round-trip-gate-compares-source-values.md b/.agents/knowledge/conventions/round-trip-gate-compares-source-values.md new file mode 100644 index 000000000..068a9757d --- /dev/null +++ b/.agents/knowledge/conventions/round-trip-gate-compares-source-values.md @@ -0,0 +1,45 @@ +# A round-trip gate must compare the source representation, not the typed form + +## Symptom + +`preset export` and `preset import` looked symmetric, the types were `Option`, and a typed comparison passed — +yet nine of twenty embedded presets lost data on a round trip. The probe also showed the inverse: an omitted +`body:` came back as `body: ""`. + +## Cause + +The typed manifest folds two different source shapes into one Rust value: + +- `ContextUpdateOp::Append { body: Option }` — absent and `null` both become `None`; `Some("")` is the + only empty form. +- Re-parsing an *exported* YAML into the typed manifest turns a missing `body:` into `None` again, so + `typed_exported == typed_source` even when the export invented `body: ""` or dropped a key. + +A gate that compares typed manifests therefore cannot see key-level loss. It compares a lossy projection with +itself. + +## Rule + +Compare the **source representation** (parsed YAML/JSON values, key sets included), keyed by the paths the +contract names: + +```rust +let source: serde_yaml::Value = serde_yaml::from_str(&source_yaml)?; +let exported: serde_yaml::Value = serde_yaml::from_str(&serde_yaml::to_string(&exported_manifest)?)?; +assert_eq!(named_fields(&source), named_fields(&exported)); +``` + +`serde_yaml::Mapping` equality is order-insensitive, so only key sets and values matter. + +## Corollary: pin the shapes the corpus does not contain + +The embedded corpus carried no payload at all, so a gate over the corpus alone could not catch either direction. +The gate needs an inline fixture enumerating the states — absent, explicit null, empty string, non-empty — and +each state needs a named assertion besides the whole-block equality. Without that, a fixture edit can silently +drop a state and the gate stays green. + +## Corollary: `Option` is one bit, `Option>` is two + +An explicit `null` and an absent key are different source values. `Option` collapses them; preserving the +distinction needs `Option>` with a `deserialize_with` that maps `null` to `Some(None)` and an omitted +key to `None`, plus `skip_serializing_if = "Option::is_none"` on the outer option. diff --git a/Cargo.lock b/Cargo.lock index 13ae2f630..ed5faf11f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3762,6 +3762,7 @@ dependencies = [ "nexus-pattern", "nexus-preset", "nexus-provider-ports", + "nexus-session-storage", "nexus-spoke-adapter", "nexus-storage-guard", "nexus-wasm-host", @@ -3876,6 +3877,7 @@ dependencies = [ "nexus-local-db", "nexus-orchestration", "nexus-preset", + "nexus-session-storage", "nix 0.31.3", "parking_lot 0.13.0", "serde", @@ -4060,6 +4062,7 @@ dependencies = [ "nexus-local-db", "nexus-narrative", "nexus-preset", + "nexus-session-storage", "nexus-spoke-adapter", "nexus-wasm-host", "nexus-workflow-ir", @@ -4127,6 +4130,25 @@ dependencies = [ "nexus-contracts", ] +[[package]] +name = "nexus-session-storage" +version = "0.1.0" +dependencies = [ + "async-trait", + "chrono", + "graph-flow", + "nexus-home-layout", + "nexus-local-db", + "nexus-preset", + "serde", + "serde_json", + "sqlx", + "tempfile", + "thiserror 2.0.21", + "tokio", + "uuid", +] + [[package]] name = "nexus-spoke-adapter" version = "0.1.0" @@ -4221,6 +4243,7 @@ dependencies = [ "nexus-narrative", "nexus-orchestration", "nexus-preset", + "nexus-session-storage", "nexus-spoke-adapter", "nexus-wasm-host", "nexus-workflow-ir", diff --git a/Cargo.toml b/Cargo.toml index 8ce62d0ab..2e75bdcfa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ members = [ "crates/nexus-pattern", "crates/nexus-preset", "crates/nexus-provider-conformance", + "crates/nexus-session-storage", "crates/nexus-spoke-adapter", "crates/nexus-wasm-host", "crates/nexus-workflow-ir", diff --git a/apps/nexus42/Cargo.toml b/apps/nexus42/Cargo.toml index 82fd4cceb..f4124edda 100644 --- a/apps/nexus42/Cargo.toml +++ b/apps/nexus42/Cargo.toml @@ -94,6 +94,7 @@ nexus-preset = { path = "../../crates/nexus-preset" } # (`nexus_workflow_ir::validate`) alongside the preset facade. nexus-workflow-ir = { path = "../../crates/nexus-workflow-ir" } nexus-orchestration = { path = "../../crates/nexus-orchestration", optional = true } +nexus-session-storage = { path = "../../crates/nexus-session-storage", optional = true } nexus-moment-context-assembly = { path = "../../crates/nexus-moment-context-assembly", optional = true, features = ["cloud-stage"] } nexus-creator-memory = { path = "../../crates/nexus-creator-memory", optional = true } nexus-creator = { path = "../../crates/nexus-creator", optional = true } @@ -252,6 +253,7 @@ cli = [ # nothing (v1.235 work-artifact IR, ADR #485 §7.8). "nexus-core/execution", "dep:nexus-orchestration", + "dep:nexus-session-storage", "dep:nexus-moment-context-assembly", "dep:nexus-creator-memory", "dep:nexus-creator", diff --git a/apps/nexus42/src/commands/ops.rs b/apps/nexus42/src/commands/ops.rs index 96e8d4c05..e01a09944 100644 --- a/apps/nexus42/src/commands/ops.rs +++ b/apps/nexus42/src/commands/ops.rs @@ -52,7 +52,7 @@ use crate::config::CliConfig; use crate::errors::{CliError, Result}; use clap::Subcommand; use nexus_orchestration::resume_rules::{self, RecoveryClass, ResumeClass}; -use nexus_orchestration::storage::{CheckpointRow, CheckpointSummary, SqliteSessionStorage}; +use nexus_session_storage::storage::{CheckpointRow, CheckpointSummary, SqliteSessionStorage}; use serde::Serialize; use serde_json::Value; use std::fmt::Write as _; @@ -315,14 +315,14 @@ async fn inspect_inner(session_id: Option, config: &CliConfig) -> Result /// but does not deserialize as [`RunStateV1`] (e.g. `{"cancel_requested": /// "false"}`) returns `None` just like corrupt bytes, so list and detail /// agree. -fn parse_run_state(bytes: Option<&[u8]>) -> Option { +fn parse_run_state(bytes: Option<&[u8]>) -> Option { let bytes = bytes?; serde_json::from_slice(bytes).ok() } fn descriptor_is_valid(bytes: Option<&[u8]>) -> bool { bytes.is_some_and(|bytes| { - serde_json::from_slice::(bytes).is_ok() + serde_json::from_slice::(bytes).is_ok() }) } @@ -339,7 +339,7 @@ fn descriptor_is_valid(bytes: Option<&[u8]>) -> bool { fn recovery_class_for( execution_version: i64, status: &str, - state: Option<&nexus_orchestration::run_state::RunStateV1>, + state: Option<&nexus_session_storage::run_state::RunStateV1>, descriptor_valid: bool, gate_park_live: bool, ) -> RecoveryClass { @@ -703,7 +703,7 @@ fn frozen_source_reconstructable(bytes: Option<&[u8]>) -> bool { return false; }; let Ok(descriptor) = - serde_json::from_slice::(bytes) + serde_json::from_slice::(bytes) else { return false; }; diff --git a/apps/nexus42/src/commands/preset/mod.rs b/apps/nexus42/src/commands/preset/mod.rs index 43fa6f29b..4c12484b2 100644 --- a/apps/nexus42/src/commands/preset/mod.rs +++ b/apps/nexus42/src/commands/preset/mod.rs @@ -556,7 +556,9 @@ fn export_ir_twin(path: &str, out: &str) -> Result<()> { .map_err(|error| CliError::Other(format!("read {}: {error}", manifest_path.display())))?; let manifest: nexus_preset::manifest::PresetManifest = serde_yaml::from_str(&yaml) .map_err(|error| CliError::Other(format!("parse {}: {error}", manifest_path.display())))?; - let imported = nexus_preset::import_preset_bundle(&manifest, bundle) + let source = nexus_preset::FsAssetSource::new(bundle) + .map_err(|error| CliError::Other(format!("open {}: {error}", bundle.display())))?; + let imported = nexus_preset::import_preset_bundle(&manifest, &source) .map_err(|error| CliError::Other(format!("import {}: {error}", bundle.display())))?; let json = nexus_preset::canonical_twin_json(&imported.document)?; std::fs::write(out, json)?; diff --git a/apps/nexus42/tests/ops_inspect_cli.rs b/apps/nexus42/tests/ops_inspect_cli.rs index 4706861a6..9cdbdf79b 100644 --- a/apps/nexus42/tests/ops_inspect_cli.rs +++ b/apps/nexus42/tests/ops_inspect_cli.rs @@ -14,8 +14,8 @@ //! Run with: `cargo test -p nexus42 --test ops_inspect_cli` use assert_cmd::Command; -use nexus_orchestration::run_state::RunDescriptorV1; use nexus_preset::source_identity::PresetSourceIdentity; +use nexus_session_storage::run_state::RunDescriptorV1; use serde_json::{json, Value}; use std::collections::HashMap; use std::future::Future; diff --git a/apps/web/src/components/canvas/__tests__/strategy-canvas-compose.test.tsx b/apps/web/src/components/canvas/__tests__/strategy-canvas-compose.test.tsx index a88b560ae..dafd6eda2 100644 --- a/apps/web/src/components/canvas/__tests__/strategy-canvas-compose.test.tsx +++ b/apps/web/src/components/canvas/__tests__/strategy-canvas-compose.test.tsx @@ -41,30 +41,11 @@ vi.mock('@/components/canvas/strategy-canvas/hooks/use-strategy-canvas', () => ( revision: 1, activeSession: null, creatorId: 'c1', - baseRevision: 1, activeScheduleId: undefined, - draftEdges: [], - onConnect: () => {}, - onReconnect: () => {}, form: { label: '', description: '', nextTarget: '', promptBody: '' }, setForm: () => {}, - saveStatuses: {}, - setSaveStatuses: () => {}, + activeSection: 'state', setActiveSection: () => {}, - conflict: null, - setConflict: () => {}, - saveTriggers: {}, - workingRevisionRef: { current: 1 }, - handleConflict: () => {}, - handleReapply: () => {}, - selectedDraftEdge: null, - draftSourceState: null, - commitDraft: () => {}, - isCommittingDraft: false, - cancelDraft: () => {}, - commitKeyboardCreate: () => {}, - isCommittingKeyboardCreate: false, - isReconnecting: false, }), })); @@ -73,14 +54,12 @@ vi.mock('@/components/canvas/strategy-canvas/inspectors/state-inspector', () => })); vi.mock('@/components/canvas/strategy-canvas/inspectors/edge-inspector', () => ({ EdgeInspector: () => null, - DraftEdgeInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspectors/prompt-inspector', () => ({ PromptInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspector-panel', () => ({ InspectorPanel: () => null, - StrategyConflictModal: () => null, })); vi.mock('@/components/canvas/strategy-canvas/state-machine', () => ({ ValidationPanel: () => null, diff --git a/apps/web/src/components/canvas/__tests__/strategy-canvas-no-create-affordance.test.tsx b/apps/web/src/components/canvas/__tests__/strategy-canvas-no-create-affordance.test.tsx new file mode 100644 index 000000000..af5516fc3 --- /dev/null +++ b/apps/web/src/components/canvas/__tests__/strategy-canvas-no-create-affordance.test.tsx @@ -0,0 +1,209 @@ +/** + * Strategy canvas — no create affordance on either document shape + * (canvas-legacy-affordances Task 4). + * + * Both shapes the canvas can render are read-only: the applied document and the + * Compose working document. Neither may offer edge creation, transition + * creation or an inspector save — the deleted YAML-authoring entry points must + * not come back through a graph gesture, the keyboard shortcut, the palette, + * the header, or the inspector sections the adapter renders for a selected node. + */ +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { http, HttpResponse } from 'msw'; +import type { NodeChange } from '@xyflow/react'; +import type { MutableRefObject } from 'react'; +import type { WorkflowDocument } from '@42ch/nexus-contracts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { StrategyCanvas } from '@/components/canvas/strategy-canvas'; +import { + createStrategyCanvasAdapter, + type StrategyCanvasAdapterContext, +} from '@/components/canvas/strategy-canvas/strategy-canvas-adapter'; +import { originalFormOf } from '@/components/canvas/strategy-canvas/state-machine'; +import { clearCommands, getCommands } from '@/lib/canvas/command-registry'; +import { parsedPresetFromIr } from '@/lib/canvas/ir-preset'; +import { COMPOSE_FLAG_STORAGE_KEY } from '@/lib/canvas/strategy-compose-flag'; +import { BrowserClient } from '@/lib/nexus'; +import { useHandlers } from '@/test/msw-server'; +import { servedIrDocument } from '@/test/simulation-fixture'; +import { renderInApp } from '@/test/test-providers'; + +const shellProps = vi.hoisted(() => ({ current: {} as Record })); + +vi.mock('@/components/canvas/canvas-shell', () => ({ + // Keep React Flow out of jsdom. The children are the inspector chrome a + // selected node renders; the props are what the shell would wire. + CanvasShell: (props: { children?: React.ReactNode } & Record) => { + shellProps.current = props; + return <>{props.children}; + }, + useNodeChangeHandler: () => () => {}, +})); + +// Not part of this proof, and it mounts its own queries. +vi.mock('@/components/canvas/idea-input', () => ({ + IdeaInput: () => null, +})); + +const STRATEGY_ID = 'novel-writing'; +const APPLIED_PATH = `/v1/daemon/strategies/${STRATEGY_ID}/applied`; +const CANDIDATE_PATH = `/v1/daemon/strategies/${STRATEGY_ID}/candidate`; +const APPROVALS_PATH = `/v1/daemon/strategies/${STRATEGY_ID}/approvals`; +const PATTERNS_PATH = '/v1/daemon/patterns'; +const SESSIONS_PATH = '/v1/daemon/orchestration/sessions'; +const SCHEDULES_PATH = '/v1/daemon/orchestration/schedules'; + +const SEED = servedIrDocument({ id: STRATEGY_ID }); +// The entering state carries a prompt template, so all three inspector sections +// (state, transition, prompt) are rendered and asserted. +const DOCUMENT: WorkflowDocument = { + ...SEED, + nodes: SEED.nodes.map((node) => + node.id === 'draft' + ? { ...node, context_update: { op: 'append' as const, template: 'prompts/draft.md' } } + : node, + ), +}; + +function orchestrationHandlers() { + return [ + http.get(SESSIONS_PATH, () => HttpResponse.json({ items: [] })), + http.get(SCHEDULES_PATH, () => HttpResponse.json({ items: [] })), + ]; +} + +function renderCanvas() { + return renderInApp(, { client: new BrowserClient() }); +} + +const composeHandlers = () => ({ + isComposing: false, + onToggleSlotExpanded: () => {}, + onBindSlot: () => Promise.resolve(), + onReplaceSubtree: () => Promise.resolve(), + onUnnest: () => Promise.resolve(), +}); + +/** The canvas itself: no graph gesture, header button or palette create route. */ +function expectCanvasOffersNoCreateRoute(container: HTMLElement) { + const canvas = within(container); + + // Edge creation: no drag-to-connect and no reconnect gesture is wired. + expect(shellProps.current.onConnect).toBeUndefined(); + expect(shellProps.current.onReconnect).toBeUndefined(); + + // The deleted keyboard create gesture opens nothing. + fireEvent.keyDown(window, { key: 'N', shiftKey: true }); + expect(canvas.queryByText('Create Transition')).not.toBeInTheDocument(); + + // Transition create: no header entry, and the palette registers only the + // graph↔list toggle (the create-transition command is gone, not hidden). + expect(canvas.queryByRole('button', { name: 'Create' })).not.toBeInTheDocument(); + expect(getCommands().map((command) => command.id)).toEqual(['strategy.toggle-view']); + + // Inspector save: selecting the entry state and opening its editor reveals + // no save control anywhere in the canvas. + act(() => { + (shellProps.current.onNodesChange as (changes: NodeChange[]) => void)([ + { id: 'draft', type: 'select', selected: true }, + ]); + }); + fireEvent.click(canvas.getByRole('button', { name: 'Edit' })); + expect(canvas.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(); +} + +/** The inspector sections the adapter renders for that shape's selected state. */ +function expectInspectorOffersNoSave(compose: boolean) { + const parsed = parsedPresetFromIr(DOCUMENT); + const selectedState = parsed.manifest.states.find((state) => state.id === 'draft'); + if (!selectedState) throw new Error('fixture lost its draft state'); + const ctxRef = { + current: { + form: originalFormOf(selectedState), + onChange: () => {}, + setActiveSection: () => {}, + selectedState, + promptTemplateRef: 'prompts/draft.md', + selectedNode: null, + parsed, + danglingTargets: [], + ...(compose ? { compose: composeHandlers() } : {}), + }, + } as MutableRefObject; + + const { container } = render(<>{createStrategyCanvasAdapter(ctxRef).renderInspector?.(null as never)}); + const inspector = within(container); + expect(inspector.getByLabelText('State inspector')).toBeInTheDocument(); + expect(inspector.getByLabelText('Transition inspector')).toBeInTheDocument(); + expect(inspector.getByLabelText('Prompt inspector')).toBeInTheDocument(); + + const fields = inspector.getAllByRole('textbox'); + expect(fields.length).toBeGreaterThan(0); + for (const field of fields) expect(field).toBeDisabled(); + expect(inspector.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(); +} + +beforeEach(() => { + clearCommands(); +}); + +afterEach(() => { + cleanup(); + clearCommands(); + window.localStorage.removeItem(COMPOSE_FLAG_STORAGE_KEY); +}); + +describe('StrategyCanvas — no create affordance', () => { + it('offers none on the applied document', async () => { + window.localStorage.removeItem(COMPOSE_FLAG_STORAGE_KEY); + useHandlers( + ...orchestrationHandlers(), + http.get(APPLIED_PATH, () => + HttpResponse.json({ + current_apply: { + apply_id: 'app_1', + approval_id: 'apr_42', + content_hash: 'hash-1', + applied_at: '2026-11-13T01:00:00Z', + supersedes_apply_id: null, + }, + newest_approval: null, + applied_document: DOCUMENT, + applied_document_refusal: null, + }), + ), + ); + + const { container } = renderCanvas(); + // The applied preset is what rendered (revision 0), not a compose candidate. + expect(await screen.findByText('rev 0')).toBeInTheDocument(); + + expectCanvasOffersNoCreateRoute(container); + expectInspectorOffersNoSave(false); + }); + + it('offers none on the Compose working document', async () => { + window.localStorage.setItem(COMPOSE_FLAG_STORAGE_KEY, 'on'); + const workingDocument = { ...DOCUMENT, revision: 4 }; + useHandlers( + ...orchestrationHandlers(), + http.get(APPLIED_PATH, () => + HttpResponse.json({ current_apply: null, newest_approval: null }), + ), + http.get(APPROVALS_PATH, () => HttpResponse.json({ items: [] })), + http.get(CANDIDATE_PATH, () => HttpResponse.json(workingDocument)), + http.get(PATTERNS_PATH, () => + HttpResponse.json({ items: [], pagination: { limit: 100, has_more: false } }), + ), + ); + + const { container } = renderCanvas(); + // The candidate is what rendered (revision 4), on the Compose surface. + expect(await screen.findByTestId('strategy-staging')).toBeInTheDocument(); + expect(await screen.findByText('rev 4')).toBeInTheDocument(); + + expectCanvasOffersNoCreateRoute(container); + expectInspectorOffersNoSave(true); + }); +}); diff --git a/apps/web/src/components/canvas/__tests__/strategy-canvas-simulate.test.tsx b/apps/web/src/components/canvas/__tests__/strategy-canvas-simulate.test.tsx index 1f3949d43..4d4db5690 100644 --- a/apps/web/src/components/canvas/__tests__/strategy-canvas-simulate.test.tsx +++ b/apps/web/src/components/canvas/__tests__/strategy-canvas-simulate.test.tsx @@ -56,30 +56,11 @@ vi.mock('@/components/canvas/strategy-canvas/hooks/use-strategy-canvas', () => ( revision: 1, activeSession: null, creatorId: 'c1', - baseRevision: 1, activeScheduleId: undefined, - draftEdges: [], - onConnect: () => {}, - onReconnect: () => {}, form: { label: '', description: '', nextTarget: '', promptBody: '' }, setForm: () => {}, - saveStatuses: {}, - setSaveStatuses: () => {}, + activeSection: 'state', setActiveSection: () => {}, - conflict: null, - setConflict: () => {}, - saveTriggers: {}, - workingRevisionRef: { current: 1 }, - handleConflict: () => {}, - handleReapply: () => {}, - selectedDraftEdge: null, - draftSourceState: null, - commitDraft: () => {}, - isCommittingDraft: false, - cancelDraft: () => {}, - commitKeyboardCreate: () => {}, - isCommittingKeyboardCreate: false, - isReconnecting: false, }), })); @@ -88,14 +69,12 @@ vi.mock('@/components/canvas/strategy-canvas/inspectors/state-inspector', () => })); vi.mock('@/components/canvas/strategy-canvas/inspectors/edge-inspector', () => ({ EdgeInspector: () => null, - DraftEdgeInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspectors/prompt-inspector', () => ({ PromptInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspector-panel', () => ({ InspectorPanel: () => null, - StrategyConflictModal: () => null, })); vi.mock('@/components/canvas/strategy-canvas/state-machine', () => ({ ValidationPanel: () => null, diff --git a/apps/web/src/components/canvas/canvas-surface-commands.test.tsx b/apps/web/src/components/canvas/canvas-surface-commands.test.tsx index 183a0c63d..69d24a27d 100644 --- a/apps/web/src/components/canvas/canvas-surface-commands.test.tsx +++ b/apps/web/src/components/canvas/canvas-surface-commands.test.tsx @@ -12,8 +12,8 @@ * canvas internals (React Flow, daemon queries, inspectors, alt-views, conflict * modals) are mocked so the test focuses on the command registration and the * graph↔list toggle button, which is where the T4 wiring lives. The header - * (which owns the toggle button) and the Strategy edge-create dialog (the - * create-transition target) are kept real so handler effects are observable. + * (which owns the toggle button) is kept real so handler effects are + * observable. */ import { act, cleanup, render } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -194,46 +194,26 @@ vi.mock('@/components/canvas/strategy-canvas/hooks/use-strategy-canvas', () => { creatorId: 'c1', baseRevision: 1, activeScheduleId: undefined, - draftEdges: [] as never[], - onConnect: () => {}, - onReconnect: () => {}, form: { label: '', description: '', nextTarget: '', promptBody: '' }, setForm: () => {}, - saveStatuses: {}, - setSaveStatuses: () => {}, setActiveSection: () => {}, - conflict: null, - setConflict: () => {}, - saveTriggers: {}, - workingRevisionRef: { current: 1 }, - handleConflict: () => {}, - handleReapply: () => {}, - selectedDraftEdge: null, - draftSourceState: null, - commitDraft: () => {}, - isCommittingDraft: false, - cancelDraft: () => {}, - commitKeyboardCreate: () => {}, - isCommittingKeyboardCreate: false, - isReconnecting: false, + activeSection: 'state', }; return { useStrategyCanvas: () => strategyState }; }); -// Strategy heavy children → no-ops (keep canvas-layout + edge-create-dialog real). +// Strategy heavy children → no-ops (keep canvas-layout real). vi.mock('@/components/canvas/strategy-canvas/inspectors/state-inspector', () => ({ StateInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspectors/edge-inspector', () => ({ EdgeInspector: () => null, - DraftEdgeInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspectors/prompt-inspector', () => ({ PromptInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspector-panel', () => ({ InspectorPanel: () => null, - StrategyConflictModal: () => null, })); vi.mock('@/components/canvas/strategy-canvas/state-machine', () => ({ ValidationPanel: () => null, @@ -386,21 +366,18 @@ afterEach(() => { }); // --------------------------------------------------------------------------- -// Strategy — toggle view + create transition (the only surface with a clean -// canvas-level creation entrypoint: the "Create Transition…" button + dialog). +// Strategy — toggle view. View switching is the only palette command this +// surface registers; structural creation is a Compose operation. // --------------------------------------------------------------------------- describe('StrategyCanvas — palette commands', () => { - it('registers a toggle-view and a create-transition command on mount', async () => { + it('registers the toggle-view command on mount', async () => { const { StrategyCanvas } = await import('@/components/canvas/strategy-canvas'); render(withProviders()); - expect(getCommands().map((c) => c.id).sort()).toEqual([ - 'strategy.create-transition', - 'strategy.toggle-view', - ]); + expect(getCommands().map((c) => c.id)).toEqual(['strategy.toggle-view']); }); - it('unregisters both on unmount', async () => { + it('unregisters on unmount', async () => { const { StrategyCanvas } = await import('@/components/canvas/strategy-canvas'); const { unmount } = render(withProviders()); unmount(); @@ -435,23 +412,6 @@ describe('StrategyCanvas — palette commands', () => { }); expect(toggle.getAttribute('aria-pressed')).toBe('false'); }); - - it('create-transition handler opens the edge-create dialog', async () => { - const { StrategyCanvas } = await import('@/components/canvas/strategy-canvas'); - const renderResult = render(withProviders()); - - // The Radix Dialog is not mounted while closed. (The header's "Create - // Transition…" button is always visible, so assert on role="dialog" - // rather than text — the dialog content renders into a portal only when - // open=true.) - expect(renderResult.queryByRole('dialog')).toBeNull(); - - act(() => { - findById('strategy.create-transition')?.handler(); - }); - - expect(renderResult.getByRole('dialog')).toBeInTheDocument(); - }); }); // --------------------------------------------------------------------------- diff --git a/apps/web/src/components/canvas/strategy-canvas.tsx b/apps/web/src/components/canvas/strategy-canvas.tsx index 4c2e80234..82b51fdb8 100644 --- a/apps/web/src/components/canvas/strategy-canvas.tsx +++ b/apps/web/src/components/canvas/strategy-canvas.tsx @@ -1,21 +1,19 @@ /** * Strategy canvas — public orchestrator facade. * - * B1: per-inspector saves (R-V171P0-QC1-004). * B2: split into focused sibling modules ≤200 lines (R-V171P0-QC1-006). * V1.114 P0 T2: migrated to the shared `CanvasSurfaceAdapter` abstraction via * `useCanvasSurface()` so graph projection, summary, inspector routing, and * alt-view are adapter-driven. * V1.115 P0 T2 (W001): the adapter's `projectGraph` now owns the real - * projection (`buildStrategyGraph(parsed)`). `useStrategyCanvas` is a thin - * query + state hook — it delegates projection to the adapter and owns only - * form/save/conflict/draft state. Draft edges are merged into the projection - * via `ctxRef.current.localEdges`; `danglingTargets` flows back via - * `ctxRef.current.danglingTargets`. + * projection (`buildStrategyGraphFromIr(document)`). `useStrategyCanvas` is a + * thin query + state hook — it delegates projection to the adapter and owns + * only the edit form and the active inspector section. `danglingTargets` + * flows back from projection via `ctxRef.current.danglingTargets`. */ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import type { Connection, Edge, Node } from '@xyflow/react'; +import type { Node } from '@xyflow/react'; import type { StrategyApprovals, WorkflowDocument } from '@42ch/nexus-contracts'; @@ -24,7 +22,7 @@ import { ErrorState, LoadingState, UnavailableState } from '@/components/ui/stat import { useRegisterCommand } from '@/lib/canvas/command-registry'; import { useSimulationTrajectory } from '@/lib/canvas/use-simulation-trajectory'; import { isOrchestrationEngineUnavailable } from '@/lib/nexus/errors'; -import type { StrategyEdgeData, StrategyNodeData } from '@/lib/canvas/strategy-graph'; +import type { StrategyNodeData } from '@/lib/canvas/strategy-graph'; import { useCanvasSurface, type CanvasSurfaceQueryResult } from '@/components/canvas/use-canvas-surface'; import { useStrategyCanvas } from '@/components/canvas/strategy-canvas/hooks/use-strategy-canvas'; @@ -45,16 +43,12 @@ import { ApproveDisclosure } from './strategy-canvas/approve-disclosure'; import { StrategyAppliedState } from './strategy-canvas/applied-state'; import { ComposeConflictDialog } from './strategy-canvas/compose-conflict-dialog'; import { PatternPickerDialog } from './strategy-canvas/pattern-picker-dialog'; -import { InspectorPanel, StrategyConflictModal } from './strategy-canvas/inspector-panel'; -import { EdgeCreateDialog } from './strategy-canvas/edge-create-dialog'; -import { DraftEdgeInspector } from './strategy-canvas/inspectors/edge-inspector'; +import { InspectorPanel } from './strategy-canvas/inspector-panel'; import { ValidationPanel, isSectionDirty, originalFormOf, templateRefOf, - type SaveStatus, - type Section, } from './strategy-canvas/state-machine'; import type { IdeaArtifact } from '@/components/canvas/idea-input'; @@ -97,15 +91,7 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra // apply/approve produced, so this view is read-only and editing goes through // Compose (P6 condition 2, D18). const appliedView = document === appliedDocument; - // No rendered document is authored in place — the applied view is the running - // strategy and a compose candidate is written through compose ops — so the - // preset-YAML structural author is never offered and never dispatched. - const yamlWritesDisabled = appliedView || composeEnabled; - const strategyState = useStrategyCanvas( - presetId, - { document, refetch: () => applied.refetch() }, - yamlWritesDisabled, - ); + const strategyState = useStrategyCanvas(presetId, document); const approval = useApproveStrategy(presetId); const application = useApplyStrategy(presetId); // T4: every approval, so Apply can be aimed at a superseded one (rollback). @@ -119,32 +105,20 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra const [artifacts, setArtifacts] = useState([]); const [isEditing, setIsEditing] = useState(false); - const [createDialogOpen, setCreateDialogOpen] = useState(false); const [patternPickerOpen, setPatternPickerOpen] = useState(false); const [approveOpen, setApproveOpen] = useState(false); // Which listed approval Apply is aimed at; null means the newest (T4). const [applyTargetId, setApplyTargetId] = useState(null); const ctxRef = useRef({ - presetId, form: strategyState.form, - saveTriggers: strategyState.saveTriggers, - saveStatuses: strategyState.saveStatuses, - workingRevisionRef: strategyState.workingRevisionRef, - handleConflict: strategyState.handleConflict, onChange: () => {}, - onSaveStatus: () => {}, setActiveSection: strategyState.setActiveSection, selectedState: undefined, promptTemplateRef: undefined, selectedNode: null, parsed: undefined, - onUseCurrent: () => {}, - onReapply: () => {}, - onDismiss: () => {}, danglingTargets: [], - localEdges: [], - appliedView, }); const adapter = useMemo(() => createStrategyCanvasAdapter(ctxRef), []); @@ -166,8 +140,7 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra refetch: refetchSurface, }; } - // The payload carries the document only: the adapter projects it from IR - // and merges draft edges via ctxRef.localEdges. + // The payload carries the document only: the adapter projects it from IR. return { data: { revision: document.revision, @@ -210,11 +183,10 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra // It moved here because it depends on selectedState (now resolved from // surface.selectedNode by the orchestrator, not from hook-owned node state). const original = useMemo(() => originalFormOf(selectedState), [selectedState]); - const revisionStatus: 'clean' | 'dirty' | 'conflict' = strategyState.conflict - ? 'conflict' - : isSectionDirty('state', strategyState.form, original) || - isSectionDirty('transition', strategyState.form, original) || - isSectionDirty('prompt', strategyState.form, original) + const revisionStatus: 'clean' | 'dirty' = + isSectionDirty('state', strategyState.form, original) || + isSectionDirty('transition', strategyState.form, original) || + isSectionDirty('prompt', strategyState.form, original) ? 'dirty' : 'clean'; @@ -225,10 +197,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra strategyState.setForm((prev) => ({ ...prev, [field]: value })); } - function onSaveStatus(section: Section, status: SaveStatus | undefined) { - strategyState.setSaveStatuses((prev) => ({ ...prev, [section]: status })); - } - // One Simulate action for the open strategy: a supplied candidate is walked // as-is; otherwise the installed preset's IR is re-read and walked only when // it no longer matches the trajectory in hand. On the compose path the @@ -310,38 +278,19 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra (surface.selectedNode?.data as StrategyNodeData | undefined)?.stateId ?? compose.workingDocument?.entry; - function handleUseCurrent() { - strategyState.setConflict(null); - setIsEditing(false); - void applied.refetch(); - } - // Update the mutable adapter context every render. The adapter object is // stable, so useCanvasSurface's projection memo survives state changes. - // V1.115 T2: localEdges feeds draft transition edges into the adapter's - // projectGraph so they appear on the canvas without a second projection - // path. danglingTargets is written BY the adapter during projection and - // read below for the ValidationPanel. + // danglingTargets is written BY the adapter during projection and read below + // for the ValidationPanel. ctxRef.current = { - presetId, form: strategyState.form, - saveTriggers: strategyState.saveTriggers, - saveStatuses: strategyState.saveStatuses, - workingRevisionRef: strategyState.workingRevisionRef, - handleConflict: strategyState.handleConflict, onChange: updateField, - onSaveStatus, setActiveSection: strategyState.setActiveSection, selectedState, promptTemplateRef, selectedNode: surface.selectedNode as unknown as Node | null, parsed: strategyState.parsed, - onUseCurrent: handleUseCurrent, - onReapply: strategyState.handleReapply, - onDismiss: () => strategyState.setConflict(null), danglingTargets: ctxRef.current.danglingTargets, - localEdges: strategyState.draftEdges as Edge[], - appliedView, patterns: compose.patternsQuery.data?.items, ...(composeEnabled ? { @@ -374,38 +323,14 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra ], handler: () => surface.setShowAlt(!showAltRef.current), }); - useRegisterCommand({ - id: 'strategy.create-transition', - labelKey: 'strategy.create-transition.label', - groupKey: 'group.strategy', - keywordKeys: [ - 'strategy.create-transition.keywords.add-edge', - 'strategy.create-transition.keywords.new-transition', - 'strategy.create-transition.keywords.state-machine', - 'strategy.create-transition.keywords.link-states', - ], - handler: () => setCreateDialogOpen(true), - // The YAML transition author writes the preset file, which is never the - // document on canvas — neither the applied view nor a compose candidate. - available: () => !yamlWritesDisabled, - }); useEffect(() => { if (!isEditing || !selectedState) { strategyState.setForm({ label: '', description: '', nextTarget: '', promptBody: '' }); - strategyState.setSaveStatuses({}); return; } strategyState.setForm(originalFormOf(selectedState)); - strategyState.setSaveStatuses({}); - }, [isEditing, selectedState?.id, strategyState.setForm, strategyState.setSaveStatuses]); - - const onConnect = useCallback( - (connection: Connection) => { - strategyState.onConnect(connection); - }, - [strategyState.onConnect], - ); + }, [isEditing, selectedState?.id, strategyState.setForm]); // D16(c): an apply is recorded but its document no longer verifies. This is // not an empty state — presenting it as "not yet applied" would invite an @@ -485,7 +410,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra activeSession={strategyState.activeSession} showAlt={surface.showAlt} setShowAlt={surface.setShowAlt} - onOpenCreateTransition={yamlWritesDisabled ? undefined : () => setCreateDialogOpen(true)} onSimulate={handleSimulate} staging={composeEnabled} onAddPattern={composeEnabled ? () => setPatternPickerOpen(true) : undefined} @@ -503,11 +427,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra edges={surface.edges} nodeTypes={surface.nodeTypes} onNodesChange={surface.onNodesChange} - // A displayed edge is never authored through the YAML authority: the - // applied view is read-only and connect/reconnect write the preset, - // not the candidate, so neither gesture is offered. - onConnect={yamlWritesDisabled ? undefined : onConnect} - onReconnect={yamlWritesDisabled ? undefined : strategyState.onReconnect} summaryText={surface.summaryText} ariaLabel={t('strategy.graphAriaLabel')} relayout={surface.relayout} @@ -523,21 +442,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra ? surface.inspector : null} - {strategyState.selectedDraftEdge ? ( - - ) : null} )} @@ -586,27 +490,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra onNest={compose.nestPattern} /> - strategyState.setConflict(null)} - /> - - { - strategyState.commitKeyboardCreate(args); - setCreateDialogOpen(false); - }} - /> - void; - /** - * FB-SE-004 — when provided, the header renders a **Create Transition…** - * button and binds the Shift+N keyboard shortcut that opens the keyboard - * edge-creation dialog. The shortcut is suppressed while focus is in a text - * field, select, or contenteditable so authors can type the letter N. - */ - onOpenCreateTransition?: () => void; /** * Simulate entry point: resolves the open strategy's IR (a supplied * candidate, or the installed preset read) and opens the disclosure that @@ -58,25 +49,6 @@ export function CanvasHeader({ }) { const { t } = useTranslation('canvas'); - // Shift+N opens the keyboard edge-creation dialog (FB-SE-004 §4.4). Suppressed - // inside text-entry controls so the letter is passed through to the field. - useEffect(() => { - if (!onOpenCreateTransition) return; - const open = onOpenCreateTransition; - function onKeyDown(e: KeyboardEvent) { - if (!e.shiftKey || e.key !== 'N') return; - const target = e.target as HTMLElement | null; - if (target) { - const tag = target.tagName; - if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable) return; - } - e.preventDefault(); - open(); - } - window.addEventListener('keydown', onKeyDown); - return () => window.removeEventListener('keydown', onKeyDown); - }, [onOpenCreateTransition]); - return ( <>
@@ -109,16 +81,6 @@ export function CanvasHeader({ {t('strategy.header.addPattern')} ) : null} - {onOpenCreateTransition ? ( - - ) : null} {onSimulate ? ( - -
- - - - ); -} diff --git a/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.test.tsx b/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.test.tsx index d20178595..370ca87e7 100644 --- a/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.test.tsx +++ b/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.test.tsx @@ -1,639 +1,62 @@ /** - * Regression coverage for R-V171P0-QC1-008 (B7): edit-save-refetch loop. - * - * `useStrategyCanvas` does not own the PATCH mutation itself, but it owns the - * conflict/reapply coordination: when an inspector save fails with a conflict, - * the canvas refetches the canonical preset before showing the reconcile modal, - * and reapply refetches again before re-issuing the save trigger. - * - * V1.115 P0 T2 (W001): the hook no longer manages base node/edge state (the - * adapter owns projection). Tests target the hook's remaining responsibilities: - * draft edge management (draftEdges), conflict/reapply coordination, and the - * three transition-write mutations. Projection equivalence is covered by the - * adapter-level tests in `strategy-graph.test.ts`. + * `useStrategyCanvas` presents the rendered IR document to the flat edit form + * and owns the active inspector section. */ import { describe, expect, it, vi } from 'vitest'; -import { renderHook, act, waitFor } from '@testing-library/react'; +import { renderHook } from '@testing-library/react'; import type { ReactNode } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; - -import { ClientProvider } from '@/lib/client-context'; -import { NexusClientError } from '@/lib/nexus'; -import type { NexusClient } from '@/lib/nexus'; -import { ToastProvider } from '@/lib/use-toast'; - -import { useStrategyCanvas, type StrategyDocumentSource } from './use-strategy-canvas'; - -const mocks = vi.hoisted(() => { - const refetch = vi.fn(() => Promise.resolve({ data: undefined })); - return { refetch }; -}); - -vi.mock('@/lib/canvas/use-strategy-data', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - useActiveSession: () => undefined as unknown as ReturnType, - usePresetSchedules: () => ({ data: [] }) as unknown as ReturnType, - useDerivedCreatorId: () => 'creator-1', - }; -}); - -/** The document source the Canvas hands the hook: two states at revision 1. */ -function documentSource(): StrategyDocumentSource { - return { - document: { - ir_version: 0, - id: 'preset-1', - version: 1, - revision: 1, - state: 'candidate', - meta: { - description: 'Preset under test', - kind: 'creator', - run_intents: ['work_init'], - requires_capabilities: [], - }, - entry: 's1', - terminal: [], - nodes: [ - { id: 's1', kind: 'outer_state', effect_class: 'pure', ui: { description: 'Original' } }, - { id: 's2', kind: 'outer_state', effect_class: 'pure', ui: { description: 'Second' } }, - ], - edges: [{ id: 's1->s2', from: 's1', to: 's2', kind: 'linear' }], - nests: [], - assets: [], - signals: [], - roles: [], - effect_summary: 'pure', - provenance: { source: 'compose' }, - }, - refetch: mocks.refetch, - }; -} +import type { WorkflowDocument } from '@42ch/nexus-contracts'; + +import { useStrategyCanvas } from './use-strategy-canvas'; + +vi.mock('@/lib/canvas/use-strategy-data', () => ({ + useActiveSession: () => undefined, + usePresetSchedules: () => ({ data: [] }), + useDerivedCreatorId: () => 'creator-1', +})); + +/** The document the Canvas hands the hook: two states at revision 1. */ +const DOCUMENT: WorkflowDocument = { + ir_version: 0, + id: 'preset-1', + version: 1, + revision: 1, + state: 'candidate', + meta: { + description: 'Preset under test', + kind: 'creator', + run_intents: ['work_init'], + requires_capabilities: [], + }, + entry: 's1', + terminal: [], + nodes: [ + { id: 's1', kind: 'outer_state', effect_class: 'pure', ui: { description: 'Original' } }, + { id: 's2', kind: 'outer_state', effect_class: 'pure', ui: { description: 'Second' } }, + ], + edges: [{ id: 's1->s2', from: 's1', to: 's2', kind: 'linear' }], + nests: [], + assets: [], + signals: [], + roles: [], + effect_summary: 'pure', + provenance: { source: 'compose' }, +}; function wrapper({ children }: { children: ReactNode }) { - const client = { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, }); - return ( - - - {children} - - - ); -} - -/** Build a wrapper with a specific client for draft-commit tests (FB-SE-002). */ -function makeCommitWrapper(client: NexusClient) { - return function commitWrapper({ children }: { children: ReactNode }) { - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, - }); - return ( - - - {children} - - - ); - }; + return {children}; } -describe('useStrategyCanvas edit-save-refetch (R-V171P0-QC1-008 B7)', () => { - it('refetches on conflict + reapply and replays the save trigger', async () => { - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - act(() => { - // Use the document's own revision so the auto-clear effect does not - // immediately dismiss the conflict before reapply is exercised. - result.current.handleConflict(1, 'state'); - }); - expect(mocks.refetch).toHaveBeenCalledTimes(1); - - await act(async () => { - result.current.handleReapply(); - }); - expect(mocks.refetch).toHaveBeenCalledTimes(2); - await waitFor(() => { - expect(result.current.saveTriggers.state).toBe(1); - }); - }); -}); - -describe('useStrategyCanvas onConnect draft edge (FB-SE-000)', () => { - it('creates a draft transition edge when connecting two different states', () => { - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - expect(result.current.draftEdges).toHaveLength(0); - expect(typeof result.current.onConnect).toBe('function'); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - - expect(result.current.draftEdges).toHaveLength(1); - const draft = result.current.draftEdges[0]; - expect(draft.source).toBe('s1'); - expect(draft.target).toBe('s2'); - expect(draft.label).toBe('Draft transition'); - expect(draft.selected).toBe(true); - expect((draft.data as { isDraft?: boolean }).isDraft).toBe(true); - }); - - it('does not create a draft edge for a self-loop', () => { - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's1', sourceHandle: null, targetHandle: null }); - }); - - expect(result.current.draftEdges).toHaveLength(0); - }); - - it('does not call the daemon on connect (local-only draft)', () => { - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - - // No save trigger fires from a connect — draft is local until inspector commit. - expect(result.current.saveTriggers.transition).toBe(0); - }); - - it('preserves the draft edge across re-renders (V1.115 T2: adapter owns base projection)', () => { - // V1.115 T2: the hook manages only drafts; base edges are projected by the - // adapter. A re-render (e.g. query refetch) does not touch draftEdges. - const { result, rerender } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - - expect(result.current.draftEdges).toHaveLength(1); - const draft = result.current.draftEdges[0]; - expect((draft.data as { isDraft?: boolean }).isDraft).toBe(true); - - rerender(); - - // The draft survives — the adapter merges it with projected edges. - expect(result.current.draftEdges).toHaveLength(1); - expect(result.current.draftEdges.some((e) => e.id === draft.id)).toBe(true); - }); -}); - -describe('useStrategyCanvas draft transition commit (FB-SE-002)', () => { - function makeClient(patchImpl: () => Promise): NexusClient { - return { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(patchImpl), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; - } - - it('commits a draft edge via strategy.patch_transition with op: "create"', async () => { - const patch = vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - expect(result.current.selectedDraftEdge).not.toBeNull(); - - await act(async () => { - result.current.commitDraft({ condition: 'word_count > 1000' }); - }); - - await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); - const request = patch.mock.calls[0][1] as Record; - expect(request).toMatchObject({ - strategy_id: 'preset-1', - source_state_id: 's1', - new_target: 's2', - op: 'create', - condition: 'word_count > 1000', - }); - - // Successful commit replaces the draft (refetch brings the canonical edge). - await waitFor(() => expect(result.current.selectedDraftEdge).toBeNull()); - }); - - it('omits op on the existing-edit path so it defaults to "update"', async () => { - // The hook-owned commit is create-only; this test documents that the draft - // commit always sends op: "create" while the legacy inspector edit path - // (usePatchStrategyTransition) continues to omit op. We assert create here; - // the legacy path is covered by inspector-save-trigger.test.tsx. - const patch = vi.fn().mockResolvedValue({ new_revision: 3 }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - - await act(async () => { - result.current.commitDraft({}); - }); - - await waitFor(() => expect(patch).toHaveBeenCalled()); - const request = patch.mock.calls[0][1] as Record; - expect(request.op).toBe('create'); - }); - - it('opens the conflict modal when the daemon returns strategy_conflict (409)', async () => { - // The document reports revision 1; the conflict's current_revision - // is set to match so the existing auto-clear effect (which dismisses a - // conflict once the refetched revision differs) does not race the - // assertion. This mirrors the established pattern in this file's - // edit-save-refetch suite. - const conflictError = new NexusClientError( - 409, - 'strategy_conflict', - 'Strategy revision is stale', - { current_revision: 1 }, - ); - const patch = vi.fn().mockRejectedValue(conflictError); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - expect(result.current.conflict).toBeNull(); - - await act(async () => { - result.current.commitDraft({}); - }); - - // 409 keeps the draft and routes to the existing conflict modal handler. - await waitFor(() => expect(result.current.conflict).not.toBeNull()); - expect(result.current.conflict).toMatchObject({ currentRevision: 1, section: 'transition' }); - // A retry command is stored so "Reapply my edit" replays the transition - // command, not the state-edit save trigger (QC1 W-001). - expect(typeof result.current.conflict?.retry).toBe('function'); - // Draft is preserved so the author can reconcile. - expect(result.current.selectedDraftEdge).not.toBeNull(); - }); - - it('cannot issue the YAML create for a draft authored with the flag off once compose takes authority (Y3)', async () => { - const patch = vi.fn().mockResolvedValue({ new_revision: 2 }); - const client = makeClient(patch); - const { result, rerender } = renderHook( - ({ structuralWritesDisabled }: { structuralWritesDisabled: boolean }) => - useStrategyCanvas('preset-1', documentSource(), structuralWritesDisabled), - { wrapper: makeCommitWrapper(client), initialProps: { structuralWritesDisabled: false } }, - ); - - // Flag off: the spatial gesture authors a local draft. - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - expect(result.current.selectedDraftEdge).not.toBeNull(); - - // Flag on: the candidate document is the one structural authority. - rerender({ structuralWritesDisabled: true }); - await act(async () => { - result.current.commitDraft({}); - }); - - // The author keeps the edge they can still see, and no structural patch was issued. - expect(patch).not.toHaveBeenCalled(); - expect(result.current.selectedDraftEdge).not.toBeNull(); - }); - - it('cancelDraft removes the draft edge without a daemon call', () => { - const patch = vi.fn(); - const client = makeClient(patch as () => Promise); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - expect(result.current.selectedDraftEdge).not.toBeNull(); - - act(() => { - result.current.cancelDraft(); - }); - - expect(result.current.selectedDraftEdge).toBeNull(); - expect(patch).not.toHaveBeenCalled(); - }); -}); - -describe('useStrategyCanvas keyboard create (FB-SE-004)', () => { - function makeClient(patchImpl: () => Promise): NexusClient { - return { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(patchImpl), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; - } - - it('commits via strategy.patch_transition with op: "create" and explicit source/target', async () => { - const patch = vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - await act(async () => { - result.current.commitKeyboardCreate({ - sourceStateId: 's1', - targetStateId: 's2', - transitionKind: 'branch', - condition: 'word_count > 1000', - }); - }); - - await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); - const request = patch.mock.calls[0][1] as Record; - expect(request).toMatchObject({ - strategy_id: 'preset-1', - source_state_id: 's1', - new_target: 's2', - op: 'create', - transition_kind: 'branch', - condition: 'word_count > 1000', - }); - }); - - it('routes a 409 conflict through the conflict modal handler', async () => { - const conflictError = new NexusClientError( - 409, - 'strategy_conflict', - 'Strategy revision is stale', - { current_revision: 1 }, - ); - const patch = vi.fn().mockRejectedValue(conflictError); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - expect(result.current.conflict).toBeNull(); - - await act(async () => { - result.current.commitKeyboardCreate({ - sourceStateId: 's1', - targetStateId: 's2', - }); - }); - - await waitFor(() => expect(result.current.conflict).not.toBeNull()); - expect(result.current.conflict).toMatchObject({ currentRevision: 1, section: 'transition' }); - }); - - it('reapplies the original transition command on reapply, not the state-edit save trigger (QC1 W-001)', async () => { - // First call rejects with 409; second call succeeds so we can observe - // the retry re-issuing the transition create. - const conflictError = new NexusClientError( - 409, - 'strategy_conflict', - 'Strategy revision is stale', - { current_revision: 1 }, - ); - const patch = vi - .fn() - .mockRejectedValueOnce(conflictError) - .mockResolvedValueOnce({ new_revision: 2 }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - const createArgs = { - sourceStateId: 's1', - targetStateId: 's2', - transitionKind: 'branch' as const, - condition: 'word_count > 1000', - }; - - await act(async () => { - result.current.commitKeyboardCreate(createArgs); - }); - - await waitFor(() => expect(result.current.conflict).not.toBeNull()); - expect(patch).toHaveBeenCalledTimes(1); - - // Reapply should replay the original transition command, not increment - // the section save trigger (which would drive a state-edit save). - await act(async () => { - result.current.handleReapply(); - }); - - await waitFor(() => expect(patch).toHaveBeenCalledTimes(2)); - - // The second patch call is the retried transition create — same args. - const retryRequest = patch.mock.calls[1][1] as Record; - expect(retryRequest).toMatchObject({ - strategy_id: 'preset-1', - source_state_id: 's1', - new_target: 's2', - op: 'create', - transition_kind: 'branch', - condition: 'word_count > 1000', - }); - - // The transition save trigger must NOT have been incremented (that would - // drive the legacy state-edit EdgeInspector save, not the transition create). - expect(result.current.saveTriggers.transition).toBe(0); - }); -}); - -describe('useStrategyCanvas edge reconnection (FB-SE-003)', () => { - // V1.115 T2: the hook no longer manages base edge state — the adapter - // projects from `parsed`. Reconnect tests verify the daemon call shape and - // conflict routing. The optimistic edge update / revert (previously managed - // in hook edge state) is now handled at the adapter/orchestrator level: - // the edge moves to the new target on query refetch (success) or stays at - // the old target (failure — no daemon state changed). - const existingEdge = { - id: 'e-s1-s2-next-0', - source: 's1', - target: 's2', - type: 'strategy-edge', - data: { transitionKind: 'next' }, - }; - - function makeReconnClient(patchImpl: () => Promise): NexusClient { - return { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(patchImpl), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; - } - - it('reconnects via a single patch_transition with old_target + new_target (op: update)', async () => { - const patch = vi.fn().mockResolvedValue({ new_revision: 2 }); - const client = makeReconnClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - expect(typeof result.current.onReconnect).toBe('function'); - - act(() => { - result.current.onReconnect(existingEdge, { - source: 's1', - target: 's3', - sourceHandle: null, - targetHandle: null, - }); - }); - - // Single reconnect payload — no delete+create, one logical transition. - await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); - const request = patch.mock.calls[0][1] as Record; - expect(request).toMatchObject({ - strategy_id: 'preset-1', - source_state_id: 's1', - old_target: 's2', - new_target: 's3', - op: 'update', - }); - }); - - it('includes the branch condition on reconnect so sibling rules sharing a target are not all rewritten (Greptile Issue 1)', async () => { - const branchEdge = { - id: 'e-s1-s2-branch-0', - source: 's1', - target: 's2', - type: 'strategy-edge', - data: { transitionKind: 'branch', condition: '_context.branch_a' }, - }; - - const patch = vi.fn().mockResolvedValue({ new_revision: 2 }); - const client = makeReconnClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onReconnect(branchEdge, { - source: 's1', - target: 's3', - sourceHandle: null, - targetHandle: null, - }); - }); - - await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); - const request = patch.mock.calls[0][1] as Record; - expect(request).toMatchObject({ - source_state_id: 's1', - old_target: 's2', - new_target: 's3', - condition: '_context.branch_a', - transition_kind: 'branch', - op: 'update', - }); - }); - - it('routes a 409 conflict through the conflict modal handler on reconnect failure', async () => { - const conflictError = new NexusClientError( - 409, - 'strategy_conflict', - 'Strategy revision is stale', - { current_revision: 1 }, - ); - const patch = vi.fn().mockRejectedValue(conflictError); - const client = makeReconnClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - expect(result.current.conflict).toBeNull(); - - await act(async () => { - result.current.onReconnect(existingEdge, { - source: 's1', - target: 's3', - sourceHandle: null, - targetHandle: null, - }); - }); - - await waitFor(() => expect(result.current.conflict).not.toBeNull()); - expect(result.current.conflict).toMatchObject({ currentRevision: 1, section: 'transition' }); - // A retry command is stored so "Reapply my edit" replays the reconnect, not a state-edit save. - expect(typeof result.current.conflict?.retry).toBe('function'); - }); - - it('does not reconnect onto the same source (self-loop guard)', () => { - const patch = vi.fn(); - const client = makeReconnClient(patch as () => Promise); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onReconnect(existingEdge, { - source: 's1', - target: 's1', - sourceHandle: null, - targetHandle: null, - }); - }); - - expect(patch).not.toHaveBeenCalled(); - }); -}); - -describe('useStrategyCanvas structural write authority', () => { - function makeClient(patch: () => Promise): NexusClient { - return { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(patch), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; - } - - it('refuses every structural channel while the candidate owns the document', async () => { - const patch = vi.fn().mockResolvedValue({ new_revision: 2 }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource(), true), { - wrapper: makeCommitWrapper(client), - }); - - await act(async () => { - // Spatial connect authors only a local draft; its commit is a YAML write. - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - await act(async () => { - result.current.commitDraft({}); - }); - await act(async () => { - result.current.commitKeyboardCreate({ sourceStateId: 's1', targetStateId: 's2' }); - result.current.onReconnect( - { id: 'edge-1', source: 's1', target: 's2', data: { transitionKind: 'next' } }, - { source: 's1', target: 's3', sourceHandle: null, targetHandle: null }, - ); - }); +describe('useStrategyCanvas', () => { + it('presents the rendered document to the editing surface', () => { + const { result } = renderHook(() => useStrategyCanvas('preset-1', DOCUMENT), { wrapper }); - expect(patch).not.toHaveBeenCalled(); + expect(result.current.revision).toBe(1); + expect(result.current.parsed?.manifest.states.map((state) => state.id)).toEqual(['s1', 's2']); + expect(result.current.activeSection).toBe('state'); }); }); diff --git a/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.ts b/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.ts index 4b5b3fe0f..3297210c4 100644 --- a/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.ts +++ b/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.ts @@ -2,68 +2,25 @@ * Orchestrator-level state hook for the Strategy canvas. * * The Canvas renders a workflow IR document (the applied one, or the candidate - * being composed) — never YAML. The hook owns: the shared edit form, - * per-section save triggers/statuses, revision tracking, conflict/reapply - * coordination, draft transition edges (local-only), and the three - * transition-write mutations (commit draft, keyboard create, reconnect). The - * editing surface still speaks the flat state shape, so `parsedPresetFromIr` - * presents the document's nodes to it without any YAML parse. + * being composed) — never YAML. The hook owns the shared edit form, the active + * inspector section, and the reads around the open preset. The editing surface + * still speaks the flat state shape, so `parsedPresetFromIr` presents the + * document's nodes to it without any YAML parse. */ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { useMutation, useQueryClient } from '@tanstack/react-query'; -import type { Connection, Edge } from '@xyflow/react'; +import { useMemo, useState } from 'react'; import type { WorkflowDocument } from '@42ch/nexus-contracts'; import { parsedPresetFromIr } from '@/lib/canvas/ir-preset'; import { - isStrategyConflictError, useActiveSession, useDerivedCreatorId, usePresetSchedules, } from '@/lib/canvas/use-strategy-data'; -import { useStrategyYamlAuthority } from '@/lib/canvas/strategy-yaml-authority'; -import { queryKeys } from '@/lib/nexus/query-keys'; -import { useToast } from '@/lib/use-toast'; -import { - createDraftTransitionEdge, - type EditForm, - type SaveStatus, - type Section, -} from '../state-machine'; +import type { EditForm, Section } from '../state-machine'; -/** - * Conflict state shared across the canvas write boundary. - * - * `retry` is present when the conflict originated from a transition - * create/reconnect command (not a state-edit save). In that case - * {@link useStrategyCanvas.handleReapply} replays the original transition - * command instead of incrementing the section save trigger, which would - * wrongly replay a state-edit save (QC1 W-001). - */ -export interface ConflictInfo { - currentRevision: number; - section: Section; - retry?: () => void; -} - -/** Where the rendered document comes from, and how to re-read it. */ -export interface StrategyDocumentSource { - /** The document the canvas is rendering; null when there is nothing to show. */ - document: WorkflowDocument | null; - /** Re-reads that document's source (the applied-status read). */ - refetch: () => Promise; -} - -export function useStrategyCanvas( - presetId: string, - source: StrategyDocumentSource, - structuralWritesDisabled = false, -) { - const { t } = useTranslation('canvas'); - const { document, refetch } = source; +export function useStrategyCanvas(presetId: string, document: WorkflowDocument | null) { // The editing surface's flat state view of the rendered document. No YAML // is parsed on this path. const parsed = useMemo(() => (document ? parsedPresetFromIr(document) : undefined), [document]); @@ -73,45 +30,7 @@ export function useStrategyCanvas( const creatorId = useDerivedCreatorId(presetId); const [form, setForm] = useState({ label: '', description: '', nextTarget: '', promptBody: '' }); - const [saveStatuses, setSaveStatuses] = useState>>({}); const [activeSection, setActiveSection] = useState
('state'); - const [conflict, setConflict] = useState(null); - const [saveTriggers, setSaveTriggers] = useState>({ - state: 0, - transition: 0, - prompt: 0, - }); - - // Draft transition edges (local-only — created by onConnect, committed or - // cancelled in the inspector). The adapter merges these with the projected - // daemon edges so drafts appear on the canvas without the hook managing base - // node/edge state. - const [draftEdges, setDraftEdges] = useState([]); - - const workingRevisionRef = useRef(revision); - - useEffect(() => { - workingRevisionRef.current = revision; - }, [revision]); - - useEffect(() => { - if (conflict && revision !== conflict.currentRevision) { - setConflict(null); - } - }, [revision, conflict]); - - useEffect(() => { - function onKeyDown(e: KeyboardEvent) { - if ((e.metaKey || e.ctrlKey) && e.key === 's') { - e.preventDefault(); - setSaveTriggers((prev) => ({ ...prev, [activeSection]: prev[activeSection] + 1 })); - } - } - window.addEventListener('keydown', onKeyDown); - return () => window.removeEventListener('keydown', onKeyDown); - }, [activeSection]); - - const activeScheduleId = useMemo(() => { if (!activeSession) return undefined; @@ -119,258 +38,6 @@ export function useStrategyCanvas( return [...list].sort((a, b) => b.updated_at.localeCompare(a.updated_at))[0]?.schedule_id; }, [activeSession, schedules.data]); - function handleConflict(currentRevision: number, section: Section, retry?: () => void) { - setConflict({ currentRevision, section, retry }); - void refetch(); - } - - function handleReapply() { - if (!conflict) return; - const { section, retry } = conflict; - setConflict(null); - void refetch().then(() => { - // Transition create/reconnect conflicts replay the original transition - // command; state-edit conflicts replay the section save trigger - // (QC1 W-001). - if (retry) { - retry(); - } else { - setSaveTriggers((prev) => ({ ...prev, [section]: prev[section] + 1 })); - } - }); - } - - /** - * Spatial connect gesture → local draft transition edge (FB-SE-000). - * - * The draft is appended to `draftEdges` and selected so the edge inspector - * can take focus. No daemon call happens here — the author commits (or - * cancels) in the inspector (FB-SE-002). Re-attempting a connect from the - * same source replaces any existing draft rather than stacking duplicates. - */ - const onConnect = useCallback( - (connection: Connection) => { - const draft = createDraftTransitionEdge(connection, t('strategy.draftTransitionLabel')); - if (!draft) return; - setDraftEdges((prev) => [ - ...prev.map((e) => ({ ...e, selected: false })).filter( - (e) => !(e.data as { isDraft?: boolean })?.isDraft, - ), - draft, - ]); - }, - [t], - ); - - /** - * FB-SE-002 — the draft transition selected on the canvas. A draft edge is - * any edge carrying `data.isDraft = true` (created by {@link onConnect}). - * There is at most one draft at a time; {@link onConnect} replaces any - * existing draft instead of stacking duplicates. - */ - const selectedDraftEdge = useMemo( - () => draftEdges.find((e) => (e.data as { isDraft?: boolean } | undefined)?.isDraft) ?? null, - [draftEdges], - ); - - const states = parsed?.manifest.states; - const draftSourceState = useMemo(() => { - if (!selectedDraftEdge) return undefined; - return states?.find((s) => s.id === selectedDraftEdge.source); - }, [selectedDraftEdge, states]); - - const yaml = useStrategyYamlAuthority(structuralWritesDisabled); - const qc = useQueryClient(); - const { toast } = useToast(); - - /** - * Commit a draft transition via `strategy.patch_transition` with - * **`op: "create"`** (FB-SE-002). On success the draft is removed from - * `draftEdges` and the preset query is invalidated so the canonical edge — - * built by the daemon from the structured op — replaces it on refetch. A 409 - * revision conflict keeps the draft and routes through the same - * {@link handleConflict} path the existing edit inspector uses, so the - * conflict modal with Use current / Reapply / Review side-by-side opens. - * - * `handleConflict` is a hoisted function declaration, so it is safe to - * reference here even though it is defined textually later in the hook. - */ - const commitDraftMutation = useMutation({ - mutationFn: async (args: { condition?: string }) => { - if (!selectedDraftEdge) throw new Error('No draft transition to commit'); - return yaml.patchTransition(presetId, { - strategy_id: presetId, - base_revision: workingRevisionRef.current, - source_state_id: selectedDraftEdge.source, - new_target: selectedDraftEdge.target, - condition: args.condition, - op: 'create', - transition_kind: 'next', - }); - }, - onSuccess: (res) => { - workingRevisionRef.current = Number(res.new_revision); - setDraftEdges((prev) => prev.filter((e) => !(e.data as { isDraft?: boolean } | undefined)?.isDraft)); - toast({ - variant: 'success', - title: 'Transition created', - description: `${selectedDraftEdge?.source} → ${selectedDraftEdge?.target}`, - }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(presetId) }); - }, - onError: (error, args) => { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - // Keep the draft so the author can reconcile; refetch canonical. - // Pass a retry that replays the original transition command so - // "Reapply my edit" re-issues the create, not a state-edit save (QC1 W-001). - handleConflict(currentRevision, 'transition', () => commitDraftMutation.mutate(args)); - } else { - const message = error instanceof Error ? error.message : 'Failed to create transition'; - toast({ variant: 'error', title: message }); - } - }, - }); - - /** Discard the current draft transition without a daemon call (FB-SE-001 #4). */ - const cancelDraft = useCallback(() => { - setDraftEdges((prev) => prev.filter((e) => !(e.data as { isDraft?: boolean } | undefined)?.isDraft)); - }, []); - - /** - * FB-SE-004 — keyboard edge-creation commit. Sends the same - * `strategy.patch_transition` with **`op: "create"`** as the spatial path - * (FB-SE-002), but with explicit source/target from the dialog instead of a - * draft edge. On 409, routes through the same {@link handleConflict} path so - * the conflict modal opens. There is no local draft edge to remove on - * success — the dialog closes and the preset refetch brings the canonical - * edge. - * - * `handleConflict` is a hoisted function declaration, so it is safe to - * reference here even though it is defined textually later in the hook. - */ - const commitKeyboardCreateMutation = useMutation({ - mutationFn: async (args: { - sourceStateId: string; - targetStateId: string; - transitionKind?: 'next' | 'branch' | 'default'; - condition?: string; - }) => { - return yaml.patchTransition(presetId, { - strategy_id: presetId, - base_revision: workingRevisionRef.current, - source_state_id: args.sourceStateId, - new_target: args.targetStateId, - condition: args.condition, - transition_kind: args.transitionKind ?? 'next', - op: 'create', - }); - }, - onSuccess: (res, args) => { - workingRevisionRef.current = Number(res.new_revision); - toast({ - variant: 'success', - title: 'Transition created', - description: `${args.sourceStateId} → ${args.targetStateId}`, - }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(presetId) }); - }, - onError: (error, args) => { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - // Replay the original transition command on reapply (QC1 W-001). - handleConflict(currentRevision, 'transition', () => - commitKeyboardCreateMutation.mutate(args), - ); - } else { - const message = error instanceof Error ? error.message : 'Failed to create transition'; - toast({ variant: 'error', title: message }); - } - }, - }); - - /** - * FB-SE-003 — reconnect an existing transition edge to a new target by drag. - * - * Sends a single `strategy.patch_transition` with `op: "update"` (default) + - * `old_target` (the previous target) + `new_target` (the drag's new target). - * The daemon replaces the matched transition atomically — no delete+create, - * so the author ends with one edge for that logical rewiring. - * - * V1.115 T2: the optimistic edge update (and its revert-on-failure) are no - * longer managed in local edge state. The adapter projects from `parsed` on - * every render, so the canonical edge moves to the new target once the query - * refetch completes. On failure, the old target persists because no daemon - * state changed. - * - * `handleConflict` is a hoisted function declaration, so it is safe to - * reference here even though it is defined textually later in the hook. - */ - const reconnectTransitionMutation = useMutation({ - mutationFn: async (args: { oldEdge: Edge; newConnection: Connection }) => { - const { oldEdge, newConnection } = args; - if (!newConnection.target) throw new Error('Reconnect is missing a new target'); - const data = oldEdge.data as { transitionKind?: string; condition?: string } | undefined; - return yaml.patchTransition(presetId, { - strategy_id: presetId, - base_revision: workingRevisionRef.current, - source_state_id: oldEdge.source, - old_target: oldEdge.target, - new_target: newConnection.target, - condition: data?.condition, - transition_kind: (data?.transitionKind ?? 'next') as 'next' | 'branch' | 'default', - op: 'update', - }); - }, - onSuccess: (res, args) => { - workingRevisionRef.current = Number(res.new_revision); - toast({ - variant: 'success', - title: 'Transition reconnected', - description: `${args.oldEdge.source} → ${args.newConnection.target}`, - }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(presetId) }); - }, - onError: (error, args) => { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - // Replay the original reconnect command on reapply (QC1 W-001). - handleConflict(currentRevision, 'transition', () => - reconnectTransitionMutation.mutate(args), - ); - } else { - const message = error instanceof Error ? error.message : 'Failed to reconnect transition'; - toast({ variant: 'error', title: message }); - } - }, - }); - - /** - * React Flow reconnect gesture (dragging an existing edge end to a new - * target) → single `patch_transition` reconnect payload (FB-SE-003). - * - * Self-loops and missing endpoints are ignored so the edge snaps back to its - * prior target (no daemon call). V1.115 T2: no local optimistic update — - * the edge moves to the new target once the query refetch completes. - */ - const onReconnect = useCallback( - (oldEdge: Edge, newConnection: Connection) => { - if (!newConnection.target || newConnection.target === oldEdge.source) return; - if (newConnection.target === oldEdge.target) return; - reconnectTransitionMutation.mutate({ oldEdge, newConnection }); - }, - [reconnectTransitionMutation], - ); - return { parsed, revision, @@ -380,27 +47,7 @@ export function useStrategyCanvas( activeScheduleId, form, setForm, - saveStatuses, - setSaveStatuses, activeSection, setActiveSection, - conflict, - setConflict, - saveTriggers, - setSaveTriggers, - workingRevisionRef, - handleConflict, - handleReapply, - draftEdges, - selectedDraftEdge, - draftSourceState, - onConnect, - commitDraft: commitDraftMutation.mutate, - isCommittingDraft: commitDraftMutation.isPending, - cancelDraft, - commitKeyboardCreate: commitKeyboardCreateMutation.mutate, - isCommittingKeyboardCreate: commitKeyboardCreateMutation.isPending, - onReconnect, - isReconnecting: reconnectTransitionMutation.isPending, }; } diff --git a/apps/web/src/components/canvas/strategy-canvas/inspector-panel.tsx b/apps/web/src/components/canvas/strategy-canvas/inspector-panel.tsx index c4e31826c..4b20b38d8 100644 --- a/apps/web/src/components/canvas/strategy-canvas/inspector-panel.tsx +++ b/apps/web/src/components/canvas/strategy-canvas/inspector-panel.tsx @@ -10,12 +10,9 @@ import { useTranslation } from 'react-i18next'; import type { Node } from '@xyflow/react'; import { Info, Pencil, X } from 'lucide-react'; -import { ConflictModal } from '@/components/canvas/conflict-modal'; -import { ConflictModalBase } from '@/components/canvas/conflict-modal-base'; import type { StrategyNodeData } from '@/lib/canvas/strategy-graph'; import type { PresetState } from '@/lib/canvas/preset-yaml'; -import { getChangedFields, getConflictDraft, originalFormOf, templateRefOf, type EditForm } from './state-machine'; -import type { ConflictInfo } from './hooks/use-strategy-canvas'; +import { templateRefOf } from './state-machine'; interface InspectorPanelProps { selected: Node | null; @@ -120,61 +117,3 @@ function ReadOnlyDetails({ d, selectedState }: { d: StrategyNodeData; selectedSt ); } - -interface StrategyConflictModalProps { - conflict: ConflictInfo | null; - form: EditForm; - canonicalState: PresetState | undefined; - promptTemplateRef: string | undefined; - onUseCurrent: () => void; - onReapply: () => void; - onDismiss: () => void; -} - -export function StrategyConflictModal({ - conflict, - form, - canonicalState, - promptTemplateRef, - onUseCurrent, - onReapply, - onDismiss, -}: StrategyConflictModalProps) { - const { t } = useTranslation('canvas'); - if (!conflict) return null; - - // Transition create/reconnect conflict — the state-edit field diff - // (label/description/nextTarget/promptBody) does not apply, and there may be - // no selected state to diff against. Render a transition-specific modal so - // the conflict is surfaced even without a selected node (QC1 W-001). - if (conflict.retry) { - return ( - - ); - } - - if (!canonicalState) return null; - return ( - - ); -} diff --git a/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.test.tsx b/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.test.tsx deleted file mode 100644 index bba3dccb3..000000000 --- a/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.test.tsx +++ /dev/null @@ -1,136 +0,0 @@ -/** - * FB-SE-002 — draft transition commit UI (edge inspector draft mode). - * - * The `DraftEdgeInspector` renders the Condition field plus the locked - * Create Transition / Cancel actions, and routes commits through the - * hook-owned draft commit callback (op: "create") and cancel through the - * hook-owned draft removal. - */ -import { describe, expect, it, vi } from 'vitest'; - -import { renderInApp } from '@/test/test-providers'; -import { noopClient } from '@/test/test-providers'; -import { screen, fireEvent } from '@testing-library/react'; - -import { DraftEdgeInspector } from './edge-inspector'; - -describe('DraftEdgeInspector (FB-SE-002)', () => { - it('renders the locked copy: Create Transition, Cancel, Condition', () => { - renderInApp( - , - { client: noopClient }, - ); - - // Primary commit CTA — locked voice. - expect(screen.getByRole('button', { name: 'Create' })).toBeInTheDocument(); - // Cancel CTA — locked voice. - expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument(); - // Field labels — locked voice. - expect(screen.getByText('Condition')).toBeInTheDocument(); - // Read-only source/target display. - expect(screen.getByText('draft')).toBeInTheDocument(); - expect(screen.getByText('revise')).toBeInTheDocument(); - }); - - it('commits with the entered condition', () => { - const onCommit = vi.fn(); - renderInApp( - , - { client: noopClient }, - ); - - fireEvent.change(screen.getByLabelText('Condition'), { target: { value: 'word_count > 1000' } }); - fireEvent.click(screen.getByRole('button', { name: 'Create' })); - - expect(onCommit).toHaveBeenCalledTimes(1); - expect(onCommit).toHaveBeenCalledWith({ condition: 'word_count > 1000' }); - }); - - it('omits empty condition from the commit payload', () => { - const onCommit = vi.fn(); - renderInApp( - , - { client: noopClient }, - ); - - fireEvent.click(screen.getByRole('button', { name: 'Create' })); - expect(onCommit).toHaveBeenCalledWith({}); - }); - - it('disables the commit button while committing and shows Creating…', () => { - renderInApp( - , - { client: noopClient }, - ); - - const commit = screen.getByRole('button', { name: 'Creating…' }); - expect(commit).toBeDisabled(); - }); - - it('disables the commit with the named reason when the candidate is the structural authority (Y3)', () => { - const onCommit = vi.fn(); - renderInApp( - , - { client: noopClient }, - ); - - const commit = screen.getByRole('button', { name: 'Create' }); - expect(commit).toBeDisabled(); - expect(screen.getByTestId('draft-transition-structural-disabled')).toHaveTextContent( - 'The canvas shows a document, not the preset YAML this editor writes — author the change in Compose.', - ); - - fireEvent.click(commit); - expect(onCommit).not.toHaveBeenCalled(); - }); - - it('cancel discards the draft without committing', () => { - const onCancel = vi.fn(); - const onCommit = vi.fn(); - renderInApp( - , - { client: noopClient }, - ); - - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); - expect(onCancel).toHaveBeenCalledTimes(1); - expect(onCommit).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.tsx b/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.tsx index 9b6583b18..8952a8302 100644 --- a/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.tsx +++ b/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.tsx @@ -1,139 +1,22 @@ /** - * Transition / edge inspector section — edits the scalar `next` transition. + * Transition / edge inspector section — displays the scalar `next` transition. * - * Owns its own save button and partial-failure UI (R-V171P0-QC1-004). + * The rendered document is never the preset YAML this section would write, so + * the field is shown with the route that does reach it instead of a Save. */ -import type { MutableRefObject } from 'react'; -import { useCallback, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query'; -import { useStrategyYamlAuthority } from '@/lib/canvas/strategy-yaml-authority'; -import { queryKeys } from '@/lib/nexus/query-keys'; -import { useToast } from '@/lib/use-toast'; -import type { StrategyPatchResponse, StrategyPatchTransitionRequest } from '@42ch/nexus-contracts'; - -import { isStrategyConflictError } from '@/lib/canvas/use-strategy-data'; -import { isSectionDirty, originalFormOf, type EditForm, type SaveStatus, type Section } from '../state-machine'; +import type { EditForm } from '../state-machine'; import type { PresetState } from '@/lib/canvas/preset-yaml'; -export interface PatchStrategyTransitionArgs { - strategyId: string; - sourceStateId: string; - baseRevision: number; - oldTarget: string; - newTarget?: string; - condition?: string; - transitionKind?: StrategyPatchTransitionRequest['transition_kind']; -} - -export function usePatchStrategyTransition( - structuralWritesDisabled = false, -): UseMutationResult { - const yaml = useStrategyYamlAuthority(structuralWritesDisabled); - const qc = useQueryClient(); - const { t } = useTranslation('canvas'); - const { toast } = useToast(); - return useMutation({ - mutationFn: (args: PatchStrategyTransitionArgs) => - yaml.patchTransition(args.strategyId, { - strategy_id: args.strategyId, - base_revision: args.baseRevision, - source_state_id: args.sourceStateId, - old_target: args.oldTarget, - new_target: args.newTarget, - condition: args.condition, - transition_kind: args.transitionKind, - }), - onSuccess: (_data, args) => { - toast({ - variant: 'success', - title: t('strategy.inspector.transition.updated'), - description: `${args.sourceStateId} → ${args.newTarget ?? args.oldTarget}`, - }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(args.strategyId) }); - }, - onError: () => {}, - }); -} - interface EdgeInspectorProps { - presetId: string; selectedState: PresetState; form: EditForm; onChange: (field: K, value: EditForm[K]) => void; - workingRevisionRef: MutableRefObject; - saveTrigger: number; - saveStatus: SaveStatus | undefined; - onSaveStatus: (status: SaveStatus | undefined) => void; - onConflict: (currentRevision: number, section: Section) => void; - /** - * Compose path: the candidate document is the only structural authority, so - * this YAML transition patch is shown with its reason but cannot be issued. - */ - structuralWritesDisabled?: boolean; } -export function EdgeInspector({ - presetId, - selectedState, - form, - onChange, - workingRevisionRef, - saveTrigger, - saveStatus, - onSaveStatus, - onConflict, - structuralWritesDisabled = false, -}: EdgeInspectorProps) { +export function EdgeInspector({ selectedState, form, onChange }: EdgeInspectorProps) { const { t } = useTranslation('canvas'); - const patch = usePatchStrategyTransition(structuralWritesDisabled); - const original = originalFormOf(selectedState); - const dirty = isSectionDirty('transition', form, original); - const lastHandledTriggerRef = useRef(0); - - const handleSave = useCallback(async () => { - if (!dirty || patch.isPending || typeof selectedState.next !== 'string') { - return; - } - onSaveStatus(undefined); - - try { - const res = await patch.mutateAsync({ - strategyId: presetId, - sourceStateId: selectedState.id, - baseRevision: workingRevisionRef.current, - oldTarget: original.nextTarget, - newTarget: form.nextTarget, - transitionKind: 'next', - }); - workingRevisionRef.current = Number(res.new_revision); - onSaveStatus({ type: 'success', message: t('strategy.inspector.transition.saved') }); - } catch (error) { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - onConflict(currentRevision, 'transition'); - } else { - const message = error instanceof Error ? error.message : t('strategy.inspector.transition.saveFailed'); - onSaveStatus({ type: 'error', message }); - } - } - }, [dirty, patch.isPending, form, original, presetId, selectedState, onSaveStatus, onConflict, t]); - - // Keep a fresh callback reference for the keyboard shortcut effect so the - // effect itself does not need to depend on the callback (R-V172P1-QC1-001). - const handleSaveRef = useRef(handleSave); - handleSaveRef.current = handleSave; - - useEffect(() => { - if (saveTrigger > 0 && saveTrigger !== lastHandledTriggerRef.current) { - lastHandledTriggerRef.current = saveTrigger; - void handleSaveRef.current(); - } - }, [saveTrigger]); if (typeof selectedState.next !== 'string') return null; @@ -141,14 +24,6 @@ export function EdgeInspector({
{t('strategy.inspector.transition.title')} -
- {structuralWritesDisabled ? ( -

- {t('strategy.inspector.structuralDisabled')} -

- ) : saveStatus ? ( -

- {saveStatus.message} -

- ) : null} -
- ); -} - -/** - * Commit payload assembled by {@link DraftEdgeInspector}. Empty strings are - * normalized to `undefined` so the wire request omits the field entirely - * (matches the optional `condition` semantics on the daemon side). - * - * Note: the DTO (`StrategyPatchTransitionRequest`) has no `label` field — the - * `condition` field is the branch identifier for conditional/labeled branches. - * A Label input was previously collected and silently dropped (QC1 W-002); - * it has been removed. - */ -export interface DraftCommitArgs { - condition?: string; -} - -export interface DraftEdgeInspectorProps { - /** Source state id (read-only display). */ - sourceStateId: string; - /** Target state id (read-only display). */ - targetStateId: string; - /** True while the hook-owned commit mutation is in flight. */ - isCommitting: boolean; - /** Commit the draft — sends `strategy.patch_transition` with `op: "create"`. */ - onCommit: (args: DraftCommitArgs) => void; - /** Discard the draft edge without a daemon call. */ - onCancel: () => void; - /** - * Compose path: the candidate document is the only structural authority, so a - * draft authored on the flag-off surface is shown with its reason but cannot - * be committed through this YAML path. - */ - structuralWritesDisabled?: boolean; -} - -/** - * FB-SE-001 / FB-SE-002 — draft transition commit UI. - * - * Renders when a spatial `onConnect` draft edge is selected. Collects - * Condition before commit; the commit routes through the hook-owned - * mutation that sends `strategy.patch_transition` with **`op: "create"`**. - * A 409 keeps the draft and opens the conflict modal (Use current / Reapply / - * Review side-by-side). Voice & Content is locked by the primary spec. - */ -export function DraftEdgeInspector({ - sourceStateId, - targetStateId, - isCommitting, - onCommit, - onCancel, - structuralWritesDisabled = false, -}: DraftEdgeInspectorProps) { - const { t } = useTranslation('canvas'); - const [condition, setCondition] = useState(''); - - function handleCommit() { - const args: DraftCommitArgs = {}; - if (condition.trim()) args.condition = condition.trim(); - onCommit(args); - } - - return ( -
-
- {t('strategy.edgeCreate.title')} -
- - -
-
-

- {sourceStateId} - - → - - {targetStateId} +

+ {t('strategy.inspector.structuralDisabled')}

- - {structuralWritesDisabled ? ( -

- {t('strategy.inspector.structuralDisabled')} -

- ) : null}
); } diff --git a/apps/web/src/components/canvas/strategy-canvas/inspectors/inspector-save-trigger.test.tsx b/apps/web/src/components/canvas/strategy-canvas/inspectors/inspector-save-trigger.test.tsx deleted file mode 100644 index 7da14fb78..000000000 --- a/apps/web/src/components/canvas/strategy-canvas/inspectors/inspector-save-trigger.test.tsx +++ /dev/null @@ -1,235 +0,0 @@ -/** - * Regression coverage for R-V172P1-QC3-001. - * - * Each inspector used to fire handleSave on every render once saveTrigger became - * non-zero because the effect depends on saveTrigger + handleSave, and - * handleSave is recreated every render. A single Cmd/Ctrl+S could therefore - * issue duplicate PATCH requests on later renders. - * - * The fix uses a last-handled trigger ref so each new trigger value is consumed - * exactly once, even if React re-renders the inspector before the mutation - * settles. - */ -import { waitFor } from '@testing-library/react'; -import type { MutableRefObject } from 'react'; -import { describe, expect, it, vi } from 'vitest'; - -import { renderInApp } from '@/test/test-providers'; -import type { NexusClient } from '@/lib/nexus'; -import type { PresetState } from '@/lib/canvas/preset-yaml'; -import type { EditForm } from '../state-machine'; - -import { StateInspector } from './state-inspector'; -import { EdgeInspector } from './edge-inspector'; -import { PromptInspector } from './prompt-inspector'; - -const baseState: PresetState = { - id: 'draft', - description: 'Original description', - next: 'revise', - context_update: { template_file: 'prompts/draft.md' }, -}; - -const baseForm: EditForm = { - label: 'edited-label', - description: 'Original description', - nextTarget: 'edit', - promptBody: '# edited prompt', -}; - -function makeWorkingRevisionRef(): MutableRefObject { - return { current: 1 }; -} - -function makeClient(): NexusClient { - return { - strategyPatchState: vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }), - strategyPatchTransition: vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }), - strategyPatchPromptTemplate: vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }), - } as unknown as NexusClient; -} - -describe('inspector save trigger replay guard (R-V172P1-QC3-001)', () => { - it('StateInspector patches once per trigger value, not once per render', async () => { - const client = makeClient(); - const workingRevisionRef = makeWorkingRevisionRef(); - const { rerender } = renderInApp( - , - { client }, - ); - - rerender( - , - ); - - // Re-render with the same trigger value simulates an unrelated render - // (e.g., from parent state change) before the mutation settles. - rerender( - , - ); - - await waitFor(() => expect(client.strategyPatchState).toHaveBeenCalledTimes(1)); - - // A fresh trigger value should still be handled exactly once. - rerender( - , - ); - - await waitFor(() => expect(client.strategyPatchState).toHaveBeenCalledTimes(2)); - }); - - it('EdgeInspector patches once per trigger value, not once per render', async () => { - const client = makeClient(); - const workingRevisionRef = makeWorkingRevisionRef(); - const { rerender } = renderInApp( - , - { client }, - ); - - rerender( - , - ); - rerender( - , - ); - - await waitFor(() => expect(client.strategyPatchTransition).toHaveBeenCalledTimes(1)); - }); - - it('PromptInspector patches once per trigger value, not once per render', async () => { - const client = makeClient(); - const workingRevisionRef = makeWorkingRevisionRef(); - const { rerender } = renderInApp( - , - { client }, - ); - - rerender( - , - ); - rerender( - , - ); - - await waitFor(() => expect(client.strategyPatchPromptTemplate).toHaveBeenCalledTimes(1)); - // The component's enabled path must write the document it displays: the - // response's revision is the one the editor carries next. (The canvas never - // enables it — no canvas document is the preset YAML this writer targets.) - await waitFor(() => expect(workingRevisionRef.current).toBe(2)); - }); -}); diff --git a/apps/web/src/components/canvas/strategy-canvas/inspectors/prompt-inspector.tsx b/apps/web/src/components/canvas/strategy-canvas/inspectors/prompt-inspector.tsx index 54bcfc099..e5c971326 100644 --- a/apps/web/src/components/canvas/strategy-canvas/inspectors/prompt-inspector.tsx +++ b/apps/web/src/components/canvas/strategy-canvas/inspectors/prompt-inspector.tsx @@ -1,175 +1,39 @@ /** - * Prompt-template inspector section — edits the body of the state's prompt. + * Prompt-template inspector section — displays the body of the state's prompt. * - * Owns its own save button and partial-failure UI (R-V171P0-QC1-004). + * The rendered document is never the preset YAML this section would write, so + * the field states the route that does reach the template instead of a Save. */ -import type { MutableRefObject } from 'react'; -import { useCallback, useEffect, useRef } from 'react'; import { useTranslation } from 'react-i18next'; -import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query'; -import { useNexusClient } from '@/lib/client-context'; -import { queryKeys } from '@/lib/nexus/query-keys'; -import { useToast } from '@/lib/use-toast'; -import type { StrategyPatchPromptTemplateRequest, StrategyPatchResponse } from '@42ch/nexus-contracts'; - -import { isStrategyConflictError } from '@/lib/canvas/use-strategy-data'; -import { isSectionDirty, originalFormOf, type EditForm, type SaveStatus, type Section } from '../state-machine'; -import type { PresetState } from '@/lib/canvas/preset-yaml'; - -export interface PatchStrategyPromptTemplateArgs { - strategyId: string; - stateId: string; - baseRevision: number; - templateRef: string; - body: string; -} - -export function usePatchStrategyPromptTemplate(): UseMutationResult< - StrategyPatchResponse, - unknown, - PatchStrategyPromptTemplateArgs -> { - const client = useNexusClient(); - const qc = useQueryClient(); - const { t } = useTranslation('canvas'); - const { toast } = useToast(); - return useMutation({ - mutationFn: (args: PatchStrategyPromptTemplateArgs) => { - const req: StrategyPatchPromptTemplateRequest = { - strategy_id: args.strategyId, - state_id: args.stateId, - base_revision: args.baseRevision, - template_ref: args.templateRef, - set: { body: args.body }, - }; - return client.strategyPatchPromptTemplate(args.strategyId, args.stateId, req); - }, - onSuccess: (_data, args) => { - toast({ variant: 'success', title: t('strategy.inspector.prompt.updated'), description: args.templateRef }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(args.strategyId) }); - }, - onError: () => {}, - }); -} +import type { EditForm } from '../state-machine'; interface PromptInspectorProps { - presetId: string; - selectedState: PresetState; form: EditForm; onChange: (field: K, value: EditForm[K]) => void; - workingRevisionRef: MutableRefObject; promptTemplateRef: string; - saveTrigger: number; - saveStatus: SaveStatus | undefined; - onSaveStatus: (status: SaveStatus | undefined) => void; - onConflict: (currentRevision: number, section: Section) => void; - /** - * The preset YAML this writer targets is never the rendered document — the - * applied view is frozen and a compose candidate has no prompt-body operation - * — so the editor stays visible but inert with its reason (P6). - */ - structuralWritesDisabled?: boolean; } -export function PromptInspector({ - presetId, - selectedState, - form, - onChange, - workingRevisionRef, - promptTemplateRef, - saveTrigger, - saveStatus, - onSaveStatus, - onConflict, - structuralWritesDisabled = false, -}: PromptInspectorProps) { +export function PromptInspector({ form, onChange, promptTemplateRef }: PromptInspectorProps) { const { t } = useTranslation('canvas'); - const patch = usePatchStrategyPromptTemplate(); - const original = originalFormOf(selectedState); - const dirty = isSectionDirty('prompt', form, original); - const lastHandledTriggerRef = useRef(0); - - const handleSave = useCallback(async () => { - // No canvas document is the preset YAML this patch writes, so the Save is - // refused rather than rewriting a bundle template behind the candidate. - if (structuralWritesDisabled || !dirty || patch.isPending) return; - onSaveStatus(undefined); - - try { - const res = await patch.mutateAsync({ - strategyId: presetId, - stateId: selectedState.id, - baseRevision: workingRevisionRef.current, - templateRef: promptTemplateRef, - body: form.promptBody, - }); - workingRevisionRef.current = Number(res.new_revision); - onSaveStatus({ type: 'success', message: t('strategy.inspector.prompt.saved') }); - } catch (error) { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - onConflict(currentRevision, 'prompt'); - } else { - const message = error instanceof Error ? error.message : t('strategy.inspector.prompt.saveFailed'); - onSaveStatus({ type: 'error', message }); - } - } - }, [structuralWritesDisabled, dirty, patch.isPending, form, original, presetId, selectedState, onSaveStatus, onConflict, promptTemplateRef, t]); - - // Keep a fresh callback reference for the keyboard shortcut effect so the - // effect itself does not need to depend on the callback (R-V172P1-QC1-001). - const handleSaveRef = useRef(handleSave); - handleSaveRef.current = handleSave; - - useEffect(() => { - if (saveTrigger > 0 && saveTrigger !== lastHandledTriggerRef.current) { - lastHandledTriggerRef.current = saveTrigger; - void handleSaveRef.current(); - } - }, [saveTrigger]); return (
{t('strategy.inspector.prompt.title')} -
{promptTemplateRef}