@pazmo/ai-workflow-kit 5.2.0 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.ko.md +34 -30
  5. package/README.md +34 -30
  6. package/assets/check.mjs +127 -4
  7. package/assets/graph.mjs +2 -1
  8. package/bin/ai-workflow-kit.mjs +63 -4
  9. package/package.json +1 -1
  10. package/skills/workflow/EVALS.md +36 -11
  11. package/skills/workflow/SKILL.md +7 -5
  12. package/skills/workflow/assets/STORY.md +30 -15
  13. package/skills/workflow/references/execution.md +26 -15
  14. package/skills/workflow/references/fast-path.md +23 -0
  15. package/skills/workflow/references/graph-advanced.md +126 -0
  16. package/skills/workflow/references/graph-engineering.md +1 -122
  17. package/skills/workflow/references/graph-minimal.md +52 -0
  18. package/skills/workflow/references/intake.md +25 -9
  19. package/skills/workflow/references/jira.md +3 -3
  20. package/skills/workflow/references/light-lane.md +31 -0
  21. package/skills/workflow/references/model-selection.md +14 -0
  22. package/skills/workflow/references/role-graphs.md +2 -2
  23. package/skills/workflow/references/skill-integration.md +4 -4
  24. package/skills/workflow/references/understanding-gate.md +49 -9
  25. package/skills/workflow/references/verification.md +3 -3
  26. package/src/graph/advance.mjs +180 -0
  27. package/src/graph/approvals.mjs +29 -1
  28. package/src/graph/approve.mjs +105 -0
  29. package/src/graph/cli.mjs +126 -8
  30. package/src/graph/copies.mjs +85 -0
  31. package/src/graph/light.mjs +182 -0
  32. package/src/graph/profile.mjs +129 -0
  33. package/src/graph/snapshot.mjs +2 -1
  34. package/src/graph/verification.mjs +92 -28
  35. package/src/graph/workflow.mjs +1 -1
  36. package/src/install.mjs +53 -14
  37. package/src/jira.mjs +14 -13
  38. package/src/managed-block.mjs +3 -3
  39. package/src/version.mjs +28 -0
@@ -0,0 +1,52 @@
1
+ # Graph: the minimal plan
2
+
3
+ The standard lane after G1. Run commands from the project root; each prints compact JSON. Read [graph-advanced.md](graph-advanced.md) only for a custom plan, a role assignment, a question or a failure this page does not cover.
4
+
5
+ ## Set up once
6
+
7
+ ```bash
8
+ node .ai-workflow/bin/graph.mjs go docs/<story>.md .ai-workflow/runs/<slug>.json --scope <module-or-path>
9
+ ```
10
+
11
+ - `go` runs `profile` (if no profile exists), `init` and `begin` for the first node, and returns its brief. Run again, it returns to the node in progress. `fast-path.md` is the step-by-step version of this page.
12
+ - `profile` writes `.ai-workflow/verification.json` from `package.json`, `tsconfig.json` or `gradlew` and never overwrites one. Its `{scope}` and `{gradle-test}` placeholders resolve per run from `go --scope`, so checks stay on the touched module or path. Edit it only when detection is wrong ([verification.md](verification.md)).
13
+ - Do not run the test suite yourself first. `baseline` is optional: use it when the repository is known to have failing tests, then narrow the failing check and `init` a new run file.
14
+ - If the run file exists, run `status` and continue; never replace a run to escape a failure.
15
+
16
+ ## Three nodes, two calls each
17
+
18
+ The plan is `implement → workflow-review → workflow-verify`.
19
+
20
+ 1. `begin` implement returns a brief: covered M/V IDs, the advisory area, the checks and earlier feedback. Dispatch the implementer with it; it ends with `complete` implement, which runs the checks and records the result.
21
+ 2. `begin` workflow-review. Dispatch one reviewer with the Story's MUST/Verify and the diff. Write its findings under `.ai-workflow/evidence/` (a file elsewhere counts as a code change and makes the review stale), then `complete` with `--verdict pass|fix --notes <file>`.
22
+ 3. `begin` workflow-verify, then `complete`. Passing receipts for unchanged code are reused, not rerun.
23
+
24
+ ```bash
25
+ node .ai-workflow/bin/graph.mjs begin <run.json> implement
26
+ node .ai-workflow/bin/graph.mjs complete <run.json> implement
27
+ node .ai-workflow/bin/graph.mjs complete <run.json> workflow-review --verdict fix --notes .ai-workflow/evidence/review-1.md
28
+ ```
29
+
30
+ ## Who does what
31
+
32
+ - **Implementer:** a subagent on the host's mid tier (Claude Code: the Agent tool with `model: "sonnet"` under Opus). Brief: the Story's MUST and Verify, the `begin` brief and the intake map. Test-first, one focused test per Verify item, a second only for a distinct failure path. It simplifies while green, runs `complete implement --tests …` itself as its GREEN run (fixing and rerunning on a failure, at most twice) and returns a short summary of changed files, test results and the last `complete` result. Do not re-read its code: read the summary, `git diff --stat` and the `complete` result.
33
+ - **Reviewer:** one mid-tier subagent, read-only. Story and diff in, findings out; on pass it also drafts the four G4 lines, which main shows unchanged. A Story with G3 gets two reviewers on a strong tier.
34
+ - **Escalation:** after two failed attempts on the same node, the next attempt runs on a stronger tier (`model: "opus"`).
35
+ - Hosts without subagents do the same steps in the main session.
36
+
37
+ ## Follow `next`
38
+
39
+ | `next` | Do |
40
+ |---|---|
41
+ | a node id | `begin` it. After a fix, its brief carries the feedback. |
42
+ | `g4` | Follow `understanding-gate.md`, then `delivery`. |
43
+ | `human` / `replan` | Surface the decision and wait; a new run follows it. |
44
+ | `stop` | Three attempts used; report the evidence. |
45
+
46
+ A failing check or a review `fix` has already reset the implementation node. If `begin` reports stale work, reset the named node with `graph.mjs reset <run> <node> "<reason>"`.
47
+
48
+ ```bash
49
+ node .ai-workflow/bin/graph.mjs delivery <run.json>
50
+ ```
51
+
52
+ `delivery` needs fresh Graph evidence and G4 bound to the final snapshot. Graph evidence never approves G3 or G4.
@@ -6,11 +6,17 @@ For a PM assignment, perform only intake and return the Story proposal or questi
6
6
 
7
7
  Derive before asking: actor, desired outcome, terms/entities, state change, invariant/forbidden outcome, failure, external side effect, and observable evidence.
8
8
 
9
+ ## Explore with a subagent
10
+
11
+ Before asking or drafting, explore. With subagents, the Story subagent (`fast-path.md` step 1, a strong tier) explores first, at most 12 tool calls, then drafts the Story and returns a map of at most 15 lines: files involved, current behavior, constraints (tests, contracts, callers) and the test command. Whoever drafts the Story (the Story subagent or the main session) first runs `node .ai-workflow/bin/graph.mjs copies <files or folders the change touches>` and follows the rule it prints: parallel copies that have the behavior are in To-be unless the request names one with a word the code uses for it (cite `file:line`), else `OPEN BLOCKING`; never ASSUMED one copy and the rest into OUT. `D1. Copies:` gives the list and the decision. One explorer saves a serial step: exploration and drafting happen in one context. Hosts without subagents read the code in the main session. Pass the map on to the implementer.
12
+
9
13
  ## Question policy
10
14
 
11
15
  - Ask **only blocking** unknowns that change behavior, ownership, or failure semantics.
12
16
  - Ask one decision per turn by default; **at most three** independent, closely related questions.
13
17
  - Stop after **two question rounds**. Draft with safe defaults labeled `ASSUMED`; keep unsafe gaps as `OPEN BLOCKING`.
18
+ - Every sentence of the request maps to a MUST, or to OUT with the reason. A request that asks for two things (add a line here, branch the text there) gets both; never pick one.
19
+ - `ASSUMED` defaults come from the code, not from new design. Change the place where the request's text or area already is, and branch on values the touched code already receives. A new signal, a new screen area or a new dependency needs a reason in the Decision line.
14
20
  - Apply the matching lenses in `domain-risks.md` before drafting. In a Payment/money or Data or system migration Story, a lens item that changes behavior and that neither the requirement nor a human settled is `OPEN BLOCKING`, never `ASSUMED`; reasonable people could pick either side.
15
21
  - Never ask implementation or **HOW** questions before the contract is clear. Database, queue, lock, and file choices belong to planning.
16
22
  - Offer a concrete default rather than an open questionnaire when a conventional safe choice exists.
@@ -28,19 +34,29 @@ Cover these points in a few connected sentences:
28
34
 
29
35
  Explain observable behavior here, not implementation choices. Label a suspected cause as a hypothesis. Use an analogy only when it clarifies the real behavior, and connect it back to that behavior. For a simple change, one or two sentences are enough. Do not force a diagram, quiz, separate explainer artifact, or another approval round.
30
36
 
31
- Put this explanation at the start of the Story's Goal section, with the formal criteria and technical evidence below it. It is part of the same contract, not a second requirements source. The reader should be able to judge the desired outcome before seeing field names, gate IDs or commands.
37
+ In the Story, this explanation becomes the Goal's three lines (As-is, To-be, Unchanged); the formal criteria and technical evidence follow in the later sections. It is part of the same contract, not a second requirements source. The reader should be able to judge the desired outcome before seeing field names, gate IDs or commands.
32
38
 
33
39
  ## Output recipe
34
40
 
35
41
  Create one Story from `../assets/STORY.md`:
36
42
 
37
- 1. Goal: actor + observable outcome.
38
- 2. Domain: terms and business invariants only.
39
- 3. MUST: numbered positive and negative behavior.
40
- 4. SHOULD: useful but non-blocking behavior.
41
- 5. OUT: explicit exclusions that prevent scope expansion.
42
- 6. Decisions: human choices, `ASSUMED`, and material open items.
43
+ 1. Goal: exactly three numbered lines — `1. As-is:` (what happens today and why it hurts), `2. To-be:` (what happens after), `3. Unchanged:` (what must stay as it is).
44
+ 2. Domain: `Terms:` and `Invariant:` as numbered lists, one item per line, never comma-joined. Code identifiers are fine.
45
+ 3. Decisions: human choices, `ASSUMED`, and material open items. They sit above MUST so the reader judges them first.
46
+ 4. MUST: numbered positive and negative behavior.
47
+ 5. SHOULD: useful but non-blocking behavior.
48
+ 6. OUT: explicit exclusions that prevent scope expansion.
43
49
  7. Verify: V# cases mapped to M#; include success and failure.
50
+ 8. Record footer: after Verify, a `---` line, then `Status:`, `Owner:`, `Lane:` and the gate lines. Write `Lane: light` only when all five rules in `light-lane.md` hold; otherwise `Lane: standard`.
51
+
52
+ Item shape for D, M, S and O:
53
+
54
+ - The item line is a short title: the condition, case or area.
55
+ - Details go in nested numbers under it.
56
+ - Results that happen together share one line, joined with `+`.
57
+ - A new nested number means a different action or a different result.
58
+ - A purpose, explanation or evidence goes in parentheses on the title line or on the same line. It is not its own number.
59
+ - An item that its title says completely has no nested numbers.
44
60
 
45
61
  Keep it one-screen by default. Do not copy it into an “AI spec.”
46
62
 
@@ -76,7 +92,7 @@ Show the full concise draft, beginning with the plain-language explanation above
76
92
 
77
93
  `Understanding gate (G1): <artifact> · <date> · Check-in: accepted`
78
94
 
79
- Then verify instead of assuming. Write `Status: Approved` and the G1 record first, then run
95
+ `node .ai-workflow/bin/graph.mjs approve G1 <story-file> --response <reply-file>` writes the approval JSON, the gate line and `Status: Approved`, then runs both checks. By hand: verify instead of assuming. Write `Status: Approved` and the G1 record first, then run
80
96
  both checks and report both exit codes:
81
97
 
82
98
  ```
@@ -93,4 +109,4 @@ unless both exit 0, and never claim the gate passed without that output.
93
109
 
94
110
  No approval means no implementation.
95
111
 
96
- For new v3 Graph runs, the G1 artifact must be JSON with `gate: "G1"`, canonical `storyHash`, and `responseRef` to the actual user decision. Store it under `.ai-workflow/approvals/`; `verification.md` gives the binding format. Document shape checks alone do not prove approval binding or delivery.
112
+ For new v3 Graph runs, the G1 artifact must be JSON with `gate: "G1"`, canonical `storyHash`, and `responseRef` to the actual user decision. A `Lane: light` Story's G1 JSON also has `lane: "light"`. Store it under `.ai-workflow/approvals/`; `verification.md` gives the binding format. Document shape checks alone do not prove approval binding or delivery.
@@ -4,7 +4,7 @@ The canonical Story stays local and remains the source of truth. Jira is an opti
4
4
 
5
5
  ## Preview first
6
6
 
7
- Run `ai-workflow-kit jira preview <story-file> --root <project>` for a paste-ready, readable preview. This command never loads a connector, writes a publication record or creates an issue. Draft Stories can be previewed; invalid Stories fail validation. Review the entire preview for confidential content before sharing it. The preview intentionally includes only Goal, Domain, MUST, SHOULD, OUT, Decisions and Verify, not Owner or gate records.
7
+ Run `ai-workflow-kit jira preview <story-file> --root <project>` for a paste-ready, readable preview. This command never loads a connector, writes a publication record or creates an issue. Draft Stories can be previewed; invalid Stories fail validation. Review the entire preview for confidential content before sharing it. The preview intentionally includes only the seven Story sections (v2 order: Goal, Domain, Decisions, MUST, SHOULD, OUT, Verify; a v1 Story keeps its order), not Status, Owner or gate records.
8
8
 
9
9
  In Codex, use `$workflow`; in Claude Code, use `/workflow`. After a user asks to publish, check the approved Story and G1 evidence, resolve the exact Jira site, project and optional parent, and obtain explicit publication authorization. Requirements approval alone does not authorize an external write. If the host has no supported connector or the user has not supplied a target, return the preview and stop. Never claim an issue exists without its verified key and URL.
10
10
 
@@ -39,9 +39,9 @@ Only literal `publish: true` enables publication. Missing target or adapter retu
39
39
 
40
40
  ## Verification, retries and failures
41
41
 
42
- Before create, the library checks Story shape and one Approved/Delivered Status plus one G1 record in the metadata, then stores a private local intent under `.ai-workflow/publications/`. Publication requires a plain preamble: title, Status, Owner, gate records, optional G4 restatement and blank lines only. Comments, fences and other blocks cannot supply approval. Publication additionally requires a separate nonempty G1 evidence artifact; a self-reference or hard link to the Story is insufficient. This is stricter than the general checker. The host must establish that the evidence records genuine human approval. The library searches for an existing issue, rejects malformed or multiple matches, reads the chosen issue back, and compares title, target, identity, heading/list order and content. JSON object-property ordering is irrelevant; semantic document differences fail verification. On success it returns `status: 'published'`, the verified key/URL and relative record path. A retry verifies again and never automatically updates an existing issue.
42
+ Before create, the library checks Story shape and one Approved/Delivered Status plus one G1 record in the metadata (the preamble or the record footer, outside fences), then stores a private local intent under `.ai-workflow/publications/`. Publication requires a plain preamble: title, Status, Owner, Lane, gate records, optional G4 lines and blank lines only. Comments, fences and other blocks cannot supply approval. Publication additionally requires a separate nonempty G1 evidence artifact; a self-reference or hard link to the Story is insufficient. This is stricter than the general checker. The host must establish that the evidence records genuine human approval. The library searches for an existing issue, rejects malformed or multiple matches, reads the chosen issue back, and compares title, target, identity, heading/list order and content. JSON object-property ordering is irrelevant; semantic document differences fail verification. On success it returns `status: 'published'`, the verified key/URL and relative record path. A retry verifies again and never automatically updates an existing issue.
43
43
 
44
- Gate metadata belongs in the preamble, except a trailing block of `Understanding gate (G1/G3/G4): ...` and `G4: PASS — ...` records after all Verify content, which is also excluded from preview/ADF. No requirement content may follow that trailing block. Ordinary section prose (including `Status:` or `Owner:` paragraphs) remains public content. This is not a general confidential-content detector.
44
+ Records belong in the preamble or in the record footer: the final run of `Status:`, `Owner:`, `Lane:`, `Understanding gate (G1/G3/G4): ...`, `G4: PASS — ...` and `G4: APPROVED — ...` lines after all Verify content, optionally opened by `---`. The checker and the preview read the same footer, and it is excluded from preview/ADF. A gate record inside Verify followed by more content is an error. Ordinary section prose (including `Status:` or `Owner:` paragraphs) remains public content, and a `---` rule followed by more Verify content stays content. This is not a general confidential-content detector.
45
45
 
46
46
  The record contains only schema/state, derived identity, content digest, target and verified issue identity; no Story body, gate evidence, credentials or transport errors. Keep the original Story unchanged. Include publication records when moving this workflow to another machine, subject to the team's policy for Jira URLs; protect them against deletion/tampering. Deleting records, changing the identity or implementing a host adapter that blindly creates defeats deduplication.
47
47
 
@@ -0,0 +1,31 @@
1
+ # Light lane
2
+
3
+ Use it when the Story footer says `Lane: light`. Intake chooses the lane; the human approves it at G1, and the G1 JSON records `lane: "light"`.
4
+
5
+ ## When a change is light
6
+
7
+ All five must hold; otherwise the Story is `Lane: standard`:
8
+
9
+ 1. reversible;
10
+ 2. inside one module;
11
+ 3. no external contract change (API, schema, message, or configuration other services read);
12
+ 4. no persistent data touched;
13
+ 5. not in a high-risk area of `domain-risks.md`.
14
+
15
+ ## Steps
16
+
17
+ ```bash
18
+ node .ai-workflow/bin/graph.mjs light docs/<story>.md .ai-workflow/runs/<slug>.json
19
+ ```
20
+
21
+ Without `.ai-workflow/verification.json`, run `node .ai-workflow/bin/graph.mjs profile docs/<story>.md` first.
22
+
23
+ 1. Dispatch the implementer: a subagent on the host's mid tier (Claude Code: the Agent tool with `model: "sonnet"`), with the Story and the intake map. Test-first, one focused test per Verify item. It returns a short summary.
24
+ 2. `node .ai-workflow/bin/graph.mjs check <run.json>` runs every check once. On a failure, send the tail to the implementer and run `check` again; after two failed attempts, a stronger tier (`model: "opus"`) fixes it. A failure that existed before the change is not yours to fix: narrow that check in the profile and start a new light run, or move up.
25
+ 3. Dispatch one mid-tier reviewer with the Story and the diff. Write its findings under `.ai-workflow/evidence/`, then `node .ai-workflow/bin/graph.mjs review <run.json> --verdict pass|fix --notes <file>`. After a `fix`: implementer, `check`, then `review --verdict pass` with any unfixed finding noted; one review round per run.
26
+ 4. G4 per `understanding-gate.md`, then `node .ai-workflow/bin/graph.mjs delivery <run.json>`.
27
+
28
+ ## Moving lanes
29
+
30
+ - Up: when the work breaks a rule above, set `Lane: standard (from light: <reason>)` and continue with [graph-minimal.md](graph-minimal.md). No new G1; G4 shows the change.
31
+ - Down: a standard run cannot become light without a new G1; `light` refuses a Story that has a standard run.
@@ -2,6 +2,20 @@
2
2
 
3
3
  Use this policy before model dispatch, in standalone delivery and every role flow. The kit supplies the rule; the host supplies available models and executes the choice. This is instruction policy, not a model router, provider SDK or Graph CLI flag. Jev is not required.
4
4
 
5
+ ## Kit defaults
6
+
7
+ With subagents (Claude Code), the work is split by role; `fast-path.md` gives the exact calls:
8
+
9
+ | Role | Model |
10
+ |---|---|
11
+ | Intake, G1 explanation, lane, plan, G4 summary, joins | The main model (the user's session) |
12
+ | Story drafting with its own exploration (scope) | A strong tier: `model: "opus"`, one short call |
13
+ | Implementation, review | The host's **mid tier**: `model: "sonnet"` |
14
+ | Review of a Story that needs G3 | Two reviewers on a strong tier |
15
+ | Verification | The CLI, no model |
16
+
17
+ Subagents keep small, fresh contexts; the main session stays thin, because every main turn re-reads its whole context. After **two failed attempts** on the same node, the next implementation attempt runs on a stronger tier (`model: "opus"`). Hosts without subagents keep everything in the main session. The rules below apply when these defaults do not fit, for example when the user names other models.
18
+
5
19
  ## Discover once, then choose
6
20
 
7
21
  1. Honor explicit user model choices, permitted providers, data boundaries, delegation rules and remaining time/cost limits. This policy grants no new permissions.
@@ -2,7 +2,7 @@
2
2
 
3
3
  **The kit manages how an assigned job gets finished. Office manages how several jobs achieve one goal.**
4
4
 
5
- Use this guide when assigned a role objective. If the dispatcher supplied an existing run/node/started token, return to that node instead of initializing another run. Without a role assignment, use the normal delivery flow in `graph-engineering.md`.
5
+ Use this guide when assigned a role objective. If the dispatcher supplied an existing run/node/started token, return to that node instead of initializing another run. Without a role assignment, use the normal delivery flow in `graph-minimal.md`; `graph-advanced.md` has the lower-level protocol.
6
6
 
7
7
  ## Ownership
8
8
 
@@ -14,7 +14,7 @@ Standalone use has the same local rules. Codex/Claude runs the CLI and tools. No
14
14
 
15
15
  Every role follows [model-selection.md](model-selection.md) before model dispatch. The host discovers and invokes permitted models; the role name does not fix a model tier. Model selection adds no assignment fields or CLI flags and cannot bypass local graph checks.
16
16
 
17
- Task `input.verification` supplies the selected project recipe path/hash and checks relevant to this node's V scope. Read the recipe and only relevant feature entries; the CLI runs profile argv, not Markdown. Delivery `workflow-review` and role `review` also receive `input.reviewBudget`: default 3 with adaptation and no nested delegation. Apply the shared round allocation in `skill-integration.md`; Office/host enforces actual worker counts.
17
+ Task `input.verification` supplies the selected project recipe path/hash and checks relevant to this node's V scope. Read the recipe and only relevant feature entries; the CLI runs profile argv, not Markdown. Delivery `workflow-review` and role `review` also receive `input.reviewBudget`: default 1 (2 for a G3 Story) and no nested delegation. Apply the shared round allocation in `skill-integration.md`; Office/host enforces actual worker counts.
18
18
 
19
19
  If PM and Developer disagree about completion, return the exact requirement and evidence to Office. Resolve the shared criteria there. A changed requirement or assignment starts a new run; do not silently edit the bound source or reuse old completion evidence.
20
20
 
@@ -52,11 +52,11 @@ Office/host assigns roles, runs agents, transports messages and owns global exec
52
52
 
53
53
  ### One review allocation
54
54
 
55
- Before dispatch, the caller chooses the round's allocation and records the reason in existing review evidence. Graph review task input supplies `reviewBudget`: **default 3 agents**, 0–2 for small changes, 4–5 for specific high-risk seams. Host/user limits take precedence, including zero delegation. This is an operating default, not a measured optimum or a CLI-enforced scheduler.
55
+ Before dispatch, the caller chooses the round's allocation and records the reason in existing review evidence. Graph review task input supplies `reviewBudget`: **default 1 agent** on the host's mid tier (`model-selection.md`), 1 for small changes, 2 on the main model for a Story that needs G3. Host/user limits take precedence, including zero delegation. This is an operating default, not a measured optimum or a CLI-enforced scheduler.
56
56
 
57
- - Normal round: combine correctness/security, tests/spec/runtime evidence, and maintainability/performance into three bounded assignments. Give each only the relevant diff, requirements and evidence references.
58
- - Docs/mechanical changes: 0–1; a small behavioral change: 1–2. Add a specialist only for a named uncovered risk such as authorization or migration recovery; state why 4–5 is needed.
59
- - Count **all** simplify/review/validation/report workers in the same round. Main performs simplification and aggregation by default. Reviewers return findings directly and do not re-delegate. New rounds need changed code or a named unresolved concern; unchanged work does not earn another full panel.
57
+ - Normal round: one reviewer covers correctness/security, tests against the Story's Verify items, and maintainability. Give it only the Story's MUST/Verify, the diff and evidence references.
58
+ - Docs/mechanical changes: 0–1. A G3 Story gets a second reviewer for its named risk, such as authorization or migration recovery.
59
+ - Count **all** simplify/review/validation/report workers in the same round. The implementer simplifies while green; main aggregates findings. Reviewers return findings directly and do not re-delegate. New rounds need changed code or a named unresolved concern; unchanged work does not earn another full panel.
60
60
  - Check the installed skill before invoking it. `requesting-code-review` dispatches one reviewer per filled template, so each assignment counts as one worker. For a selected `ce-code-review`, `mode:agent` selects output, not a worker cap. If its internal fan-out cannot fit the allocation, use the direct bounded review instead of launching it and hoping. Do not invent `max_reviewers` flags. Preserve any required independent-review coverage; report a gap if host limits prevent it.
61
61
 
62
62
  The host enforces actual dispatch counts. Graph's ready-node width is a separate DAG limit and does not cap nested skill workers. Model choice follows `model-selection.md`; extra personas on one model are not the multi-model evidence of Pstack `interrogate`. Do not automatically append interrogate to CE review.
@@ -1,24 +1,64 @@
1
1
  # G4 Human Understanding Gate
2
2
 
3
- This gate checks ownership of the actual implementation. It is not a generated summary ceremony.
3
+ This gate checks that the owner knows what the actual implementation does before delivery. It has two modes:
4
4
 
5
- ## Predict before reveal
5
+ - **`ai-summary`** is the default. The agent explains the change in four short numbered lines, and the human approves.
6
+ - **`human-restatement`** is used when the owner asks for it, and it is required for any Story with a G3 decision (high-risk or hard-to-reverse work). The checker and the delivery check reject `ai-summary` for G3 Stories.
6
7
 
7
- Before presenting G4, run `node .ai-workflow/bin/graph.mjs status <run.json>` and require `action: g4`. Graph readiness only establishes recorded workflow evidence; it never supplies the human answer or approves this gate. For work completed before graph installation, initialize a run and record freshly checked implementation/review/verification evidence before continuing.
8
+ Before presenting G4 in either mode, run `node .ai-workflow/bin/graph.mjs status <run.json>` and require `action: g4`. Graph readiness only establishes recorded workflow evidence. It never supplies the human's answer and never approves this gate. For work completed before graph installation, initialize a run and record freshly checked implementation, review and verification evidence before continuing.
9
+
10
+ ## Mode `ai-summary`
11
+
12
+ Write these four lines in the user's language, one or two lines each, from the approved Story, the diff, the test results and the review findings:
13
+
14
+ ```
15
+ 1. 사용자가 겪는 변화: <what changes for the person using it>
16
+ 2. 지킨 규칙과 실패할 때 동작: <the invariant kept and what happens on failure>
17
+ 3. 확인한 테스트: <which tests or checks proved it>
18
+ 4. 확인하지 못한 것: <what is unproven: the evidence boundary>
19
+ ```
20
+
21
+ Ask for approval and **END THE TURN.**
22
+
23
+ - Only an explicit approval from the human counts, such as "승인" or an equivalent reply.
24
+ - Silence, continuing the conversation, or a reply produced by another agent never counts.
25
+ - If the human corrects a line, fix it and ask again.
26
+
27
+ ## Mode `human-restatement`
28
+
29
+ Predict before reveal:
8
30
 
9
31
  1. Gather the approved Story, test results, review findings, and the **raw diff** or mechanical diff/stat. Show only that evidence; do not explain the solution yet.
10
- 2. Ask in the user's language: “이 변경 뒤에 사용자가 겪는 일이 어떻게 달라질까요? 꼭 지켜야 할 규칙과 실패했을 때의 동작은 무엇인가요? 어떤 테스트가 그걸 확인했고, 아직 확인하지 못한 것은 무엇인가요?” **END THE TURN.**
32
+ 2. Ask in the user's language: "이 변경 뒤에 사용자가 겪는 일이 어떻게 달라질까요? 꼭 지켜야 할 규칙과 실패했을 때의 동작은 무엇인가요? 어떤 테스트가 그걸 확인했고, 아직 확인하지 못한 것은 무엇인가요?" **END THE TURN.**
11
33
  3. Only after the human answers, **compare** the answer with the Story, diff, runtime flow, and tests.
12
34
  4. Return three short sections: correct, missed, incorrect/risky. Never reward confident guessing.
13
35
  5. If a core gap remains, teach only that gap and require a one- or two-sentence **restatement**. Repeat until the owner can explain behavior, one invariant/failure path, and the evidence boundary.
14
36
 
15
37
  ## Record
16
38
 
17
- Save raw evidence, the actual human answer, and evaluation privately under `.ai-workflow/approvals/`. The referenced G4 JSON records `gate: "G4"`, the canonical `storyHash`, current Graph `snapshot`, `runId`, and a nonempty `responseRef` pointing to the real response. See `verification.md`. Binding detects reuse; it does not authenticate a person. Never invent a response or obtain it from another agent. Then record:
39
+ Save the evidence, the human's actual reply, and (for `human-restatement`) the evaluation privately under `.ai-workflow/approvals/`.
40
+
41
+ The referenced G4 JSON records:
42
+
43
+ - `gate: "G4"`
44
+ - `mode`: `"ai-summary"` or `"human-restatement"`
45
+ - for `ai-summary`, `summary` (an array of the four lines shown) and `approvalText` (the human's reply)
46
+ - the canonical `storyHash`
47
+ - the current Graph `snapshot` and `runId`
48
+ - a nonempty `responseRef` pointing to the real response
49
+
50
+ See `verification.md`. `graph delivery` rejects a record whose mode differs from the Story's G4 line. Binding detects reuse; it does not authenticate a person. Never invent a response or obtain it from another agent.
51
+
52
+ Then replace the existing `Understanding gate (G4)` line in the Story's record footer; each gate line appears once. For `ai-summary`, add the mode:
53
+
54
+ `Understanding gate (G4): <artifact> · <date> · Check-in: accepted · Mode: ai-summary`
55
+
56
+ Append the pass line for the mode:
18
57
 
19
- `Understanding gate (G4): <artifact> · <date> · Check-in: accepted`
58
+ - `ai-summary`: `G4: APPROVED — <owner> approved the AI summary`
59
+ - `human-restatement` (a gate line without `Mode:`): `G4: PASS — <what the human correctly restated>`
20
60
 
21
- Also append `G4: PASS — <what the human correctly restated>`. Set `Status: Delivered` only after both records exist and the document checks and bound delivery check exit 0:
61
+ `node .ai-workflow/bin/graph.mjs approve G4 <run.json> --summary <four-lines-file> --response <reply-file>` writes the JSON, both footer lines and `Status: Delivered`, then runs the delivery check. By hand, set `Status: Delivered` only after both records exist and the document checks and the bound delivery check exit 0:
22
62
 
23
63
  ```
24
64
  node .ai-workflow/bin/check.mjs story <story-file>
@@ -26,6 +66,6 @@ node .ai-workflow/bin/check.mjs gate G4 <story-file>
26
66
  node .ai-workflow/bin/graph.mjs delivery <run.json>
27
67
  ```
28
68
 
29
- Run them and report the exit codes; never claim the gate passed without that output. A `story` run on a Story that is not yet `Delivered` does not check G4 at all, and says so. Use `G4: N/A — <specific reason>` only when no implementation behavior changed; never use it to bypass uncertainty.
69
+ Run them and report the exit codes. Never claim the gate passed without that output. A `story` run on a Story that is not yet `Delivered` does not check G4 at all, and says so.
30
70
 
31
- Document-only `G4: N/A` remains a shape-check exception, not executable delivery proof. The strengthened delivery check requires a bound human G4 plus fresh Graph evidence; do not relabel N/A as runtime verification.
71
+ Use `G4: N/A — <specific reason>` only when no implementation behavior changed. Never use it to bypass uncertainty. Document-only `G4: N/A` remains a shape-check exception, not executable delivery proof. The delivery check requires a bound human G4 plus fresh Graph evidence; do not relabel N/A as runtime verification.
@@ -15,7 +15,7 @@ For each Story V ID, describe the real user entry point, preconditions, action,
15
15
 
16
16
  ## Project profile
17
17
 
18
- Create `.ai-workflow/verification.json` (review it like executable code):
18
+ Run `node .ai-workflow/bin/graph.mjs profile <story.md>` first: it writes this file from `package.json`, `tsconfig.json` or `gradlew` and never overwrites one. Edit it, or create `.ai-workflow/verification.json` by hand when detection fails (review it like executable code):
19
19
 
20
20
  ```json
21
21
  {
@@ -39,7 +39,7 @@ Keep generated run/result/log/approval files under `.ai-workflow/runs/`, `.ai-wo
39
39
 
40
40
  ## Bind human decisions
41
41
 
42
- Compute the canonical Story hash with installed `storyContract` from `.ai-workflow/graph/workflow.mjs`; it excludes Status and G1/G3/G4 metadata lines. Add the existing gate line pointing to an approval JSON. Populate only after the real human decision:
42
+ Compute the canonical Story hash with installed `storyContract` from `.ai-workflow/graph/workflow.mjs`; it excludes Status, Lane and G1/G3/G4 metadata lines. A light-lane G1 JSON also records `lane: "light"`. Add the existing gate line pointing to an approval JSON. Populate only after the real human decision:
43
43
 
44
44
  ```json
45
45
  {"gate":"G1", "storyHash":"<canonical hash>", "responseRef":"<actual response reference>"}
@@ -47,7 +47,7 @@ Compute the canonical Story hash with installed `storyContract` from `.ai-workfl
47
47
 
48
48
  For a design requiring G3, set `requiresG3: true` and `design: "docs/design.md"` in the profile; the G3 JSON additionally has `decisionHash` (SHA-256 of design bytes). Obtain the decision before initialization/implementation. Small changes need no G3. Risk declaration belongs to the approved scope and reviewed profile, not a keyword classifier.
49
49
 
50
- G4 JSON additionally has the current Graph `snapshot` and `runId`; preserve prediction-before-reveal in `understanding-gate.md`. These bindings prevent accidental reuse; a host controlling repository files can forge records. They are not human identity authentication.
50
+ G4 JSON additionally has the current Graph `snapshot` and `runId`, and a `mode` that matches the Story's G4 line. An `ai-summary` record also has `summary` (an array of the four lines shown) and `approvalText` (the human's reply). `graph delivery` rejects a missing or mismatched mode, an incomplete summary, and `ai-summary` in a run that requires G3. Follow the mode procedure in `understanding-gate.md`. These bindings prevent accidental reuse; a host controlling repository files can forge records. They are not human identity authentication.
51
51
 
52
52
  ## Run and inspect
53
53
 
@@ -0,0 +1,180 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { projectFile, readJson, readProjectFile } from './storage.mjs';
5
+ import { dependencyIds, nodeById } from './task-graph.mjs';
6
+ import { taskInput, taskToken } from './workflow.mjs';
7
+ import { executeCheck, needsExecution, receiptTail, runCheck } from './verification.mjs';
8
+
9
+ // begin/complete wrap the 5.3.0 commands (status, start, verify, record, reset) so a node
10
+ // costs two model calls instead of start → result JSON → verify → record. Every rule of
11
+ // those commands still applies, because they still run.
12
+
13
+ export const VERDICTS = ['pass', 'fix', 'human', 'replan'];
14
+ const BRIEF_TEXT = 360;
15
+
16
+ const clip = (text, size) => (text.length > size ? `${text.slice(0, size - 1)}…` : text);
17
+ const clipEnd = (text, size) => (text.length > size ? `…${text.slice(-(size - 1))}` : text);
18
+
19
+ // Notes elsewhere in a git repository are untracked code to the snapshot: they would make the
20
+ // review stale. .ai-workflow/evidence is outside the snapshot.
21
+ export const NOTES_DIR = '.ai-workflow/evidence/';
22
+ export function assertNotesPath(file) {
23
+ if (file !== undefined && !path.posix.normalize(file).startsWith(NOTES_DIR)) {
24
+ throw new Error(`Write review notes under ${NOTES_DIR} (for example ${NOTES_DIR}review-1.md); a notes file elsewhere changes the code snapshot and makes the review stale.`);
25
+ }
26
+ }
27
+
28
+ function outItems(text) {
29
+ const body = text.match(/^##\s+OUT\s*$([\s\S]*?)(?=^##\s|(?![\s\S]))/im)?.[1] ?? '';
30
+ return [...body.matchAll(/^[-*]\s+(.+)$/gm)].map(match => match[1].trim());
31
+ }
32
+
33
+ /** Start a ready node, or re-read a running one, and return a compact brief. */
34
+ export async function begin({ root, runFile, nodeId, call, beforeStart }) {
35
+ const state = await call(['status', runFile]);
36
+ let started;
37
+ if (state.running.includes(nodeId)) started = taskInput(await readJson(root, runFile), nodeId);
38
+ else {
39
+ const ready = state.ready.find(node => node.id === nodeId);
40
+ if (!ready) {
41
+ const hint = state.action === 'stale' ? ` Code changed since ${state.stale.join(', ')} began; reset: graph.mjs reset ${runFile} <node> "<reason>".` : '';
42
+ throw new Error(`Node is not ready: ${nodeId} (action: ${state.action}).${hint}`);
43
+ }
44
+ await beforeStart?.(ready);
45
+ ({ started } = await call(['start', runFile, nodeId, ready.token]));
46
+ }
47
+ const story = await readProjectFile(root, started.input.story);
48
+ const failure = started.input.messages.filter(message => message.event === 'failure' || message.event === 'feedback').at(-1);
49
+ const feedback = failure?.feedback ?? failure?.summary;
50
+ return {
51
+ node: nodeId,
52
+ covers: started.covers,
53
+ area: clip([started.description, ...outItems(story).map(item => `OUT: ${item}`)].join(' | '), BRIEF_TEXT),
54
+ // Each check as this run executes it, so the host never has to open the profile.
55
+ checks: await (async () => {
56
+ const data = await readJson(root, runFile);
57
+ return (started.input.verification?.checks ?? []).map(({ id }) => {
58
+ const check = data.verification?.value.checks.find(entry => entry.id === id);
59
+ return check ? `${id}: ${runCheck(data, check).argv.join(' ')}` : id;
60
+ });
61
+ })(),
62
+ ...(state.action === 'stale' && state.stale?.includes(nodeId) ? { stale: true } : {}),
63
+ token: started.token,
64
+ // A check failure ends in its most useful lines; review notes start with theirs.
65
+ ...(feedback ? { feedback: (feedback.startsWith('Check ') ? clipEnd : clip)(feedback, BRIEF_TEXT), feedbackFile: (failure.output?.evidence ?? failure.evidence)?.[0] } : {}),
66
+ };
67
+ }
68
+
69
+ /** Write nodes a failed node sends its fix to: itself, or the nearest write nodes it depends on. */
70
+ function fixTargets(graph, nodeId) {
71
+ const node = nodeById(graph, nodeId);
72
+ if (node.access !== 'read') return [nodeId];
73
+ const targets = [];
74
+ const visit = id => {
75
+ for (const dependency of dependencyIds(graph, id)) {
76
+ if (nodeById(graph, dependency).access !== 'read') { if (!targets.includes(dependency)) targets.push(dependency); }
77
+ else visit(dependency);
78
+ }
79
+ };
80
+ visit(nodeId);
81
+ return targets;
82
+ }
83
+
84
+ async function writeEvidence(root, runId, name, text) {
85
+ const file = `.ai-workflow/evidence/${runId}/complete/${name}`;
86
+ await fs.mkdir(path.dirname(await projectFile(root, file)), { recursive: true, mode: 0o700 });
87
+ await fs.writeFile(await projectFile(root, file), text, { flag: 'wx', mode: 0o600 });
88
+ return file;
89
+ }
90
+
91
+ /** Run a node's checks, record its result and route the next step. */
92
+ export async function complete({ root, runFile, nodeId, verdict, notesFile, call, loadRun, snapshot, indexReceipt, reuseReceipt }) {
93
+ if (verdict !== undefined && !VERDICTS.includes(verdict)) throw new Error(`--verdict must be one of ${VERDICTS.join(', ')}.`);
94
+ assertNotesPath(notesFile);
95
+ const run = await loadRun();
96
+ const node = nodeById(run.graph, nodeId);
97
+ if (run.state.nodes[nodeId].status !== 'running') throw new Error(`Node is not running: ${nodeId}. Start it with: graph.mjs begin ${runFile} ${nodeId}`);
98
+ const verifies = needsExecution(run, nodeId);
99
+ const reviews = node.access === 'read' && !verifies;
100
+ if (reviews && !verdict) throw new Error('Review nodes need --verdict pass|fix|human|replan, and --notes <file> with the findings.');
101
+ const notes = notesFile ? (await readProjectFile(root, notesFile)).trim() : '';
102
+ if (verdict && verdict !== 'pass' && !notes) throw new Error('Failed evaluation needs feedback: pass --notes <file> with the findings.');
103
+ const fixes = run.history.filter(entry => entry.event === 'record' && entry.nodeId === nodeId && entry.result?.evaluation?.action === 'fix').length;
104
+ if (reviews && verdict === 'fix' && fixes >= 1) {
105
+ throw new Error('One review round per run: record --verdict pass and list the remaining findings in --notes (they go to the G4 summary as unverified), or use --verdict human for a blocking problem.');
106
+ }
107
+ // Only a pass is refused on changed code; a fix, human or replan result is still recorded.
108
+ const wantsPass = (verdict ?? 'pass') === 'pass';
109
+ const state = await call(['status', runFile]);
110
+ if (wantsPass && state.action === 'stale' && state.stale.includes(nodeId)) {
111
+ throw new Error(`Code changed since ${nodeId} began; its result is stale. Reset it: graph.mjs reset ${runFile} ${nodeId} "<reason>", then begin again.`);
112
+ }
113
+
114
+ const token = taskToken(run, nodeId);
115
+ const checks = (run.verification?.value.checks ?? []).filter(check => check.covers.some(id => node.covers.includes(id)))
116
+ .map(check => runCheck(run, check));
117
+ const receipts = [];
118
+ let failing;
119
+ if (!reviews && wantsPass) {
120
+ for (const check of checks) {
121
+ let receipt;
122
+ let file;
123
+ if (verifies) {
124
+ const result = await call(['verify', runFile, nodeId, token, check.id]);
125
+ receipt = result.verification;
126
+ file = receipt.receipt;
127
+ } else {
128
+ const before = (await snapshot(run)).fingerprint;
129
+ const reused = await reuseReceipt?.(run, check, before);
130
+ if (reused) ({ receipt, file } = reused);
131
+ else {
132
+ ({ receipt, file } = await executeCheck({ root, run, nodeId, token, check, snapshotBefore: before, snapshot }));
133
+ if (receipt.passed) await indexReceipt?.(check, receipt, file);
134
+ }
135
+ }
136
+ receipts.push(file);
137
+ if (!receipt.passed) {
138
+ failing = { check: check.id, tail: await receiptTail(root, receipt) };
139
+ break;
140
+ }
141
+ }
142
+ }
143
+
144
+ const passed = !failing && (verdict ?? 'pass') === 'pass';
145
+ const action = failing ? 'fix' : verdict;
146
+ const feedback = failing ? `Check ${failing.check} failed:\n${failing.tail}` : notes;
147
+ const label = `${nodeId}-${run.state.nodes[nodeId].attempts}-${randomUUID().slice(0, 8)}`;
148
+ const summary = notes.split('\n').find(line => line.trim())?.trim() ?? `${nodeId} ${passed ? 'passed' : 'failed'} (recorded by complete)`;
149
+ const notesEvidence = await writeEvidence(root, run.runId, `${label}.md`,
150
+ `${summary}\n\n${notes || (failing ? feedback : 'No notes.')}\n`);
151
+ const resultFile = await writeEvidence(root, run.runId, `${label}.json`, JSON.stringify({
152
+ token,
153
+ output: { summary: clip(summary, 200), evidence: [notesEvidence, ...receipts] },
154
+ evaluation: passed ? { passed: true } : { passed: false, action, feedback },
155
+ }));
156
+ await call(['record', runFile, nodeId, resultFile]);
157
+
158
+ let note;
159
+ if (!passed && action === 'fix') {
160
+ for (const target of fixTargets(run.graph, nodeId)) {
161
+ try { await call(['reset', runFile, target, clip(`fix from ${nodeId}: ${feedback}`, 300)]); }
162
+ catch (error) { note = error.message; break; }
163
+ }
164
+ }
165
+ const after = await call(['status', runFile]);
166
+ // Begin the next node here: one call fewer per node, and its brief is what the host needs next.
167
+ const nextId = after.running.length === 0 ? after.ready[0]?.id : undefined;
168
+ let brief;
169
+ try { brief = nextId ? await begin({ root, runFile, nodeId: nextId, call }) : undefined; }
170
+ catch (error) { note ??= `Recorded; begin ${nextId} failed: ${error.message}`; }
171
+ return {
172
+ node: nodeId,
173
+ status: passed ? 'completed' : 'failed',
174
+ next: nextId ?? after.ready[0]?.id ?? after.action,
175
+ ...(brief ? { brief } : {}),
176
+ ...(failing ? { failing: { check: failing.check, tail: clipEnd(failing.tail, 600) } } : {}),
177
+ ...(note ? { note: clip(note, 200) } : {}),
178
+ };
179
+ }
180
+
@@ -5,7 +5,7 @@ export function approvalPath(text, gate) {
5
5
  }
6
6
 
7
7
  // Binding prevents accidental reuse. It does not authenticate the host or the human.
8
- export async function boundApproval({ root, story, gate, expected, checkGate }) {
8
+ export async function boundApproval({ root, story, gate, expected, checkGate, validate }) {
9
9
  const checked = await checkGate({ root, file: story, gate });
10
10
  if (!checked.ok) throw new Error(checked.errors.join('\n'));
11
11
  const file = approvalPath(await readProjectFile(root, story), gate);
@@ -15,5 +15,33 @@ export async function boundApproval({ root, story, gate, expected, checkGate })
15
15
  || Object.entries(expected).some(([key, expectedValue]) => value[key] !== expectedValue)) {
16
16
  throw new Error(`${gate} approval binding changed or missing; obtain a fresh human decision for this Story/revision.`);
17
17
  }
18
+ validate?.(value);
18
19
  return { file, hash: digest(JSON.stringify(value)) };
19
20
  }
21
+
22
+ /** The G4 record mode, from its Story gate line; a line without "Mode:" is human restatement. */
23
+ export function storyG4Mode(text) {
24
+ const record = text.match(/^Understanding gate \(G4\):(.*)$/imu)?.[1] ?? '';
25
+ // Same parse as g4Mode in check.mjs; graph code receives the checker by injection.
26
+ return record.match(/\bMode:\s*([\w-]+)/iu)?.[1]?.toLowerCase() === 'ai-summary' ? 'ai-summary' : 'human-restatement';
27
+ }
28
+
29
+ // The approval JSON must hold what the Story's G4 mode promises: for ai-summary, the
30
+ // four lines shown and the human's actual reply. G3 work never uses ai-summary.
31
+ export function checkG4Record(value, { mode, requiresG3 }) {
32
+ const recorded = value.mode ?? 'human-restatement';
33
+ if (requiresG3 && (mode === 'ai-summary' || recorded === 'ai-summary')) {
34
+ throw new Error('A run that requires G3 needs G4 by human restatement, not ai-summary.');
35
+ }
36
+ if (recorded !== mode) {
37
+ throw new Error(`G4 approval mode (${recorded}) does not match the Story's G4 record (${mode}); record the approval for the mode actually used.`);
38
+ }
39
+ if (mode !== 'ai-summary') return;
40
+ if (!Array.isArray(value.summary) || value.summary.length !== 4
41
+ || !value.summary.every((line) => typeof line === 'string' && line.trim())) {
42
+ throw new Error('G4 ai-summary approval needs summary: the four non-empty lines shown to the human.');
43
+ }
44
+ if (typeof value.approvalText !== 'string' || !value.approvalText.trim()) {
45
+ throw new Error("G4 ai-summary approval needs approvalText: the human's actual reply.");
46
+ }
47
+ }