gcf-harness-aif-ext 0.33.0 → 0.35.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.
package/README.md CHANGED
@@ -43,6 +43,10 @@ ai-factory extension update gcf-harness-aif-ext
43
43
 
44
44
  Updating keeps the hook entry valid — it points into the extension's install directory, which an update refreshes in place.
45
45
 
46
+ 0.35.0 needs gcf-aif-ext 0.36 (docs/Plan-Review-Rework-Plan.md): update both together with gcf-board 0.36.0, then run `ai-factory gcf init` (the `AGENTS.md` block changed). `/gcf-run` plan passes: the reviewer (Codex or a `claude` subagent, with the prompt of `gcf-harness codex-review <id> --kind plan --pass <k> --prompt-only`) only finds, the planning session gives each finding a verdict and fixes the plan, and records the pass with `gcf plan pass --findings`; pass 1 is a full review, the next ones check the fixes by the plan's diff. A run's planning and implementation sessions take their own model and effort (`plan_model`, `agent.plan`…; GCF's default for planning is effort high), and `run_end.plan` is `{passes, cost_usd, ms}` of the run's planning.
47
+
48
+ 0.34.0 needs gcf-aif-ext 0.35 (docs/Lessons-Review-Plan.md): update both together with gcf-board 0.35.0 (`gcf board --json` is `schema: 7`), then run `ai-factory gcf init` (the `AGENTS.md` block changed). A run whose commits changed the agent's instructions — `AGENTS.md`, `CLAUDE.md`, `.claude/`, `.ai-factory/` outside its plans and archive, the core's `INSTRUCTION_PATHS` — says so in `run_end.instructions` (`{paths, from, to, uncommitted}`: the paths its commits touched, merges and the operator's moves left out, the full hashes around them for `gcf rules diff`, and the paths it left uncommitted; a path dirty before the run counts only when the run changed its content); the board marks the run's end with the diff. Only a reminder: nothing is refused. With an older core, which has no `gcf rules diff`, the field is absent.
49
+
46
50
  0.33.0 needs gcf-aif-ext 0.34 (docs/Until-Records-Plan.md): update both together with gcf-board 0.34.0, then run `ai-factory gcf init` (the `AGENTS.md` block changed). `/gcf-run` hands the readset's `d2_fired` to its subagents with the `d2` lines and plans on no fired value: a plan that needs one blocks the item once, naming the record (`needs the human's answer to <q-NNN> (its until fired)`), and the human answers on that record, never on a new D1. The core's audit now names a fired D2 on its first line and the board shows it among the decisions; `retune(<sys>)` counts only the tunes after the record.
47
51
 
48
52
  0.32.0 changes nothing but the peer range: it runs with `gcf-aif-ext` 0.33, where an operator's move from a terminal or the board waits behind a card's main run instead of a refusal (docs/Main-Run-Moves-Plan.md). Update it together with gcf-aif-ext 0.33.0 and gcf-board 0.33.0.
@@ -61,7 +65,7 @@ Updating keeps the hook entry valid — it points into the extension's install d
61
65
 
62
66
  0.21.2 changes no code: its peer range adds core 0.22.
63
67
 
64
- 0.21.1: `/gcf-run` treats a `format:` line of `gcf plan check` (core 0.21: the plan's form against the plan profile) as polish its improve passes apply, never a block. It takes core 0.20 or 0.21 (the peer range of 0.21.0 left 0.21 out).
68
+ 0.21.1: `/gcf-run` treats a `format:` line of `gcf plan check` (core 0.21: the plan's form against the plan profile) as polish the plan's author applies, never a block. It takes core 0.20 or 0.21 (the peer range of 0.21.0 left 0.21 out).
65
69
 
66
70
  0.21.0 (bundled gcf-session 0.18.0): `run_end` also names the run's last DoD (`green`, `red`, `unknown`) and review, and the files a worktree run left uncommitted (`left`: the worktree, how many files; a rerun goes on there). A run's chat carries its subagents' and background shells' `task` events: the board shows what each does.
67
71
 
@@ -118,7 +122,7 @@ Updating keeps the hook entry valid — it points into the extension's install d
118
122
 
119
123
  0.9.2 holds `/gcf-run` to aif-implement. Run `ai-factory gcf-harness init` again after the update: it registers the new hook.
120
124
  - The implement guard: in a session that runs `/gcf-run`, a write to a code file is denied until the session invokes the aif-implement skill (gcf-run step 13), and so is a plan tick, which only aif-implement sets. Planning stays free: `gcf/`, `.ai-factory/`, `.gcf-session/` and any markdown file. After aif-implement every write is free, the fixes of a red DoD and of the review included. It works in the harness's runs and in an interactive `/gcf-run` alike, and touches no other session.
121
- - `/gcf-run` converges a plan when an improve pass finds nothing blocking: a wrong or missing behavior or task, a broken pillar invariant, a rule conflict, a task no check can prove. Polish (wording, splitting tasks, order) is applied, but no longer keeps the loop going. Before, a pass that changed any task asked for one more, and a fresh reviewer almost always changes something. The report row per pass gives the blocking and polish counts.
125
+ - `/gcf-run` converges a plan when its last review pass has no blocking finding with any verdict: one with a scenario (a state or input and the wrong result) — wrong behavior, a broken pillar invariant, a rule conflict, risk to saves. Polish (a missed procedural step, a test that does not prove its decision, wording, order) is applied by the author at their judgement and does not keep the loop going. The report row per pass gives the blocking and polish counts.
122
126
  - `/gcf-run` answers aif-plan's own questions (tests, logging, docs) itself, from the item, its DoD and the project's rules.
123
127
  - The run report marks an item whose session wrote code without aif-implement: `— code written outside aif-implement` on its line, `process` in `--json` and in its kept record. It reads the session's own events, its subagents' included, so it also covers a project without the guard registered. A write through Bash is seen by neither: the review of the diff is the check there.
124
128
  - Lessons (with core 0.7.10): after each agent session the run asks the same session, resumed, what got in its way - tools, rules, the framework, the project template - with the questions of `ai-factory gcf lessons prompt`. Its answers go to the inbox on main as lessons (`gcf lessons add`), and the board shows them on the card, in the drawer and in the inbox. The run passes `--no-lessons` to `/gcf-run`, so the agent carries no lessons instruction while it works. The turn follows a result, a handoff (before the fresh session), a timeout or an error; not a usage limit or a stop, and only for a `claude` agent with a session id. Another agent asks its lessons itself at the end of a run on main; in a worktree it records none. It takes up to 10 minutes; its cost goes on the item, and the report line says `, N lessons`. A failed lessons turn is logged and changes nothing else. A project that turns lessons off, or a core before 0.7.10, gets no turn and no flag.
@@ -162,7 +166,7 @@ Removal does not touch `.claude/settings.json`: delete the entries whose command
162
166
 
163
167
  ## What it adds
164
168
 
165
- **`/gcf-run <item-id…>`** — drives work items through plan, implementation and DoD, with every gate checked *before* the tokens are spent: the audit ritual, the gate below, the context budget. The plan is written by `aif-plan`, then improved in passes, each by a fresh subagent that reads only the plan and the readset and records every default it picks; `ai-factory gcf plan check <id>` runs after each pass, and a pass with no blocking finding (a wrong or missing behavior or task, a broken pillar invariant, a rule conflict, an unprovable task) ends the loop. A blocking finding left after `plan_passes` passes (3 by default), or a question only the human can answer (a save format, a public API, a new dependency, a pillar conflict), blocks the item before any code is written. The DoD is `ai-factory gcf verify <id>` — the gate's checks, the item's `live:` delta, and the project's `dod.build` and `dod.test` commands from `gcf/config.yml` — plus a review by a fresh subagent, up to `dod_attempts` attempts. Every item ends in a state the core records: `gcf submit` (gate `verdict` or `decision` — waits for the human), `gcf close` (gate `auto` — done, or a soft unit closed as `unplayed`) or `gcf block` with the reason. The verdict and the decision belong to the human: the pipeline stops at `submit` and prints the playtest list.
169
+ **`/gcf-run <item-id…>`** — drives work items through plan, implementation and DoD, with every gate checked *before* the tokens are spent: the audit ritual, the gate below, the context budget. The plan is written by `aif-plan`, then reviewed in passes: the reviewer finds, the planning session gives verdicts and fixes the plan and records every default it picks, `gcf plan pass --findings` records the pass, and `ai-factory gcf plan check <id>` runs after each pass; the loop ends when the last pass has no blocking finding of any verdict (a scenario of wrong behavior, a broken pillar invariant, a rule conflict, risk to saves). A blocking finding left after `plan_passes` passes (3 by default), or a question only the human can answer (a save format, a public API, a new dependency, a pillar conflict), blocks the item before any code is written. The DoD is `ai-factory gcf verify <id>` — the gate's checks, the item's `live:` delta, and the project's `dod.build` and `dod.test` commands from `gcf/config.yml` — plus a review by a fresh subagent, up to `dod_attempts` attempts. Every item ends in a state the core records: `gcf submit` (gate `verdict` or `decision` — waits for the human), `gcf close` (gate `auto` — done, or a soft unit closed as `unplayed`) or `gcf block` with the reason. The verdict and the decision belong to the human: the pipeline stops at `submit` and prints the playtest list.
166
170
 
167
171
  **`ai-factory gcf-harness gate <item-id…>`** — the `/gcf-run` gate as code (`--each`: each item alone, see 0.14.0 above). It reads one `gcf audit --json` report and exits 1 with a one-line reason when the items may not go: a core older than 0.4.0, a `schema:` other than 1 in `gcf/config.yml`, an id with no work item, a feature (run its children; the feature closes when they are finished), an item that is not `ready`, an unplayed dependency, no WIP room for the batch (items awaiting a verdict + the batch's `gate: verdict` items over `wip_built_limit`), or two items of the batch touching the same system unless both say `parallel: ok`. The tune limit is not a gate rule: `verdict tune` itself refuses at the limit, and an item tuned up to it still gets its last build. The skill runs it and stops on a non-zero exit — no model compares the numbers.
168
172
 
@@ -15,6 +15,8 @@ import { codexInstalled, codexModels, slugOf } from 'gcf-session';
15
15
 
16
16
  const HERE = path.dirname(fileURLToPath(import.meta.url));
17
17
  export const FINDINGS_SCHEMA = path.join(HERE, 'codex-review.schema.json');
18
+ // The plan's finding carries its proof (Plan-Review-Rework-Plan d5); the code's schema stays.
19
+ export const PLAN_SCHEMA = path.join(HERE, 'codex-review.plan.schema.json');
18
20
  export const REVIEW_TIMEOUT_MS = 25 * 60_000;
19
21
 
20
22
  const ANSWER = [
@@ -23,13 +25,33 @@ const ANSWER = [
23
25
  'Answer with the findings only, as the schema says.',
24
26
  ];
25
27
 
28
+ /**
29
+ * The plan review's rubric (d5), one line an idea: the prompt's text, and SKILL.md holds each
30
+ * line word for word (skill-format.test.js), so the author judges by what the reviewer was told.
31
+ */
32
+ export const PLAN_RUBRIC = [
33
+ 'blocking: the game or the tool does the wrong thing or not what the item asks, a pillar ' +
34
+ 'invariant breaks, a design decision contradicts a hard project rule, or saves or data are ' +
35
+ 'at risk',
36
+ 'a blocking finding names its `where` (d# or t#), its `scenario` (the state or input and the ' +
37
+ 'wrong result), its `evidence` (file:line or the rule quoted) and its `why_not_later` (why a ' +
38
+ 'red test or the code review would not catch it at the same cost)',
39
+ 'the core records a blocking finding without a `scenario` as polish',
40
+ 'polish: a missed procedural step of a project rule, a test that does not prove its decision, ' +
41
+ 'wording, order, the split of tasks, a missing behavior with no scenario',
42
+ "not a finding: the choice of a fixture, the list of a test's cases, values the code gives, " +
43
+ '"add more cases"',
44
+ ];
45
+
26
46
  /**
27
47
  * The review's prompt: what to read and how to answer; the reviewer reads the files itself. The
28
- * plan's carries aif-improve's criteria and the pillars' invariants; the code's the diff file and
29
- * the pillars' review questions (SKILL.md steps 9, 15).
30
- * @param {{id: string, kind: string, plan: string, diff?: string | null}} o
48
+ * code's: the diff file and the pillars' review questions (SKILL.md steps 14, 15). The plan's
49
+ * (d4, d6): `full` reviews the whole plan; `check`, with the diff of the plan since the earlier
50
+ * pass, only what the author's fixes cause or expose.
51
+ * @param {{id: string, kind: string, plan: string, diff?: string | null, mode?: string,
52
+ * cycle?: number, pass?: number}} o
31
53
  */
32
- export function reviewPrompt({ id, kind, plan, diff }) {
54
+ export function reviewPrompt({ id, kind, plan, diff, mode, cycle, pass }) {
33
55
  if (kind === 'code')
34
56
  return [
35
57
  `Review the code change of work item ${id} before its commit. The diff is in ${diff};`,
@@ -40,17 +62,71 @@ export function reviewPrompt({ id, kind, plan, diff }) {
40
62
  ...ANSWER,
41
63
  ].join('\n');
42
64
 
65
+ const tail = [
66
+ 'Sort each finding by these rules:',
67
+ ...PLAN_RUBRIC.map((l) => `- ${l}`),
68
+ // A Claude subagent gets no schema file: the contract is in the text (the core refuses a
69
+ // finding without its summary).
70
+ 'Answer with JSON only, {"findings": [...]}, each finding an object with exactly these',
71
+ 'fields: severity ("blocking" or "polish"), summary (what is wrong, never empty), and where,',
72
+ 'scenario, evidence, why_not_later and raises, each a string or null; no other field.',
73
+ ];
74
+ // An older core answers no mode, and a check needs its diff: either way the whole plan.
75
+ if (mode === 'check' && diff)
76
+ return [...checkOf({ id, plan, diff, cycle, pass }), ...tail].join('\n');
77
+
43
78
  return [
44
- `Audit the implementation plan of work item ${id}: ${plan}.`,
79
+ `Review the implementation plan of work item ${id}: ${plan}.`,
45
80
  `Read the item gcf/work/${id}.md, the plan, and the code the plan names. Change nothing.`,
46
- 'Apply the criteria of an improve pass: every task provable by a check, nothing the item asks',
47
- 'missing, no wrong behavior, no conflict with a project rule. Check every task against the',
48
- 'invariant of each pillar in gcf/PILLARS.md, and against the graveyard_hits lines of',
49
- `\`ai-factory gcf context ${id} --json\`. Check each claim of the plan against the code.`,
50
- ...ANSWER,
81
+ 'Find the states where the feature does the wrong thing: a win, an undo, a save, the rules',
82
+ 'that already hold. Check every task against the invariant of each pillar in gcf/PILLARS.md,',
83
+ `and against the graveyard_hits lines of \`ai-factory gcf context ${id} --json\`. Check each`,
84
+ 'claim of the plan against the code.',
85
+ ...tail,
51
86
  ].join('\n');
52
87
  }
53
88
 
89
+ /**
90
+ * The file the author keeps pass `pass` of `cycle` in (SKILL.md): the reviewer's findings, then
91
+ * the author's verdicts; the next check reads it.
92
+ */
93
+ export const findingsFile = (id, cycle, pass) =>
94
+ `.gcf-session/review/${id}.c${cycle}.p${pass}.findings.json`;
95
+
96
+ /**
97
+ * A check's own lines (d4): only what the diff's changes cause or expose, and the blocking
98
+ * findings of the pass before the author rejected or downgraded, read from that pass's file with
99
+ * their scenario and evidence; none before pass 1 of a cycle.
100
+ */
101
+ function checkOf({ id, plan, diff, cycle = 0, pass = 1 }) {
102
+ const before = pass > 1 ? findingsFile(id, cycle, pass - 1) : null;
103
+
104
+ return [
105
+ `Check the fixes to the implementation plan of work item ${id}: ${plan}.`,
106
+ `The diff of the plan since the last review is in ${diff}. Read it, the whole plan with its`,
107
+ `## Findings (each earlier finding with the author's verdict), the item gcf/work/${id}.md`,
108
+ 'and the code. Change nothing.',
109
+ 'Give only the findings the changes of the diff cause or expose: a fault outside the changed',
110
+ 'lines counts when a change exposed it.',
111
+ ...(before
112
+ ? [
113
+ 'Besides, re-examine each blocking finding of the pass before that the author rejected',
114
+ `or downgraded, whatever the diff touches: that pass's findings, with their scenario,`,
115
+ `evidence and the author's verdict and reason, are in ${before}.`,
116
+ ]
117
+ : []),
118
+ 'Answer three questions: is each blocking finding the author accepted in the pass before',
119
+ 'closed; did a change bring a new blocking one; was each blocking finding of the pass before',
120
+ 'that the author rejected or downgraded rightly so. One that was not and still holds is',
121
+ 'blocking again, its `raises` the tag of that earlier finding (p1.2, c1.p1.2). Reopen no',
122
+ 'earlier finding accepted and fixed, unless the diff breaks its fix. Anything else you',
123
+ 'notice is polish, a note to the implementer.',
124
+ ];
125
+ }
126
+
127
+ /** The prompt of `gcf review row`'s answer `row`: its mode and diff file as the core gave them. */
128
+ export const promptOf = (row) => reviewPrompt({ ...row, diff: row.diff?.file ?? null });
129
+
54
130
  /**
55
131
  * Run the pass: `{findings, by}`, `{skipped: why}` (the row is not Codex's, no Codex) or
56
132
  * `{failed: why}`; no Codex and a failure add the row's `fallback`. `row` is `gcf review row`'s
@@ -92,12 +168,12 @@ function run(projectDir, cmd, { row, slug, effort, timeoutMs }) {
92
168
  const args = [
93
169
  ...['exec', '-', '-s', 'read-only', '-m', slug],
94
170
  ...['-c', `model_reasoning_effort=${effort}`, '--ephemeral'],
95
- ...['--output-schema', FINDINGS_SCHEMA, '-o', out],
171
+ ...['--output-schema', row.kind === 'plan' ? PLAN_SCHEMA : FINDINGS_SCHEMA, '-o', out],
96
172
  ];
97
173
  const res = spawnSync(cmd.exe, [...cmd.pre, ...args], {
98
174
  windowsHide: true,
99
175
  cwd: projectDir,
100
- input: reviewPrompt({ ...row, diff: row.diff?.file ?? null }),
176
+ input: promptOf(row),
101
177
  encoding: 'utf8',
102
178
  timeout: timeoutMs ?? REVIEW_TIMEOUT_MS,
103
179
  shell: cmd.shell,
@@ -0,0 +1,32 @@
1
+ {
2
+ "type": "object",
3
+ "additionalProperties": false,
4
+ "required": ["findings"],
5
+ "properties": {
6
+ "findings": {
7
+ "type": "array",
8
+ "items": {
9
+ "type": "object",
10
+ "additionalProperties": false,
11
+ "required": [
12
+ "severity",
13
+ "summary",
14
+ "where",
15
+ "scenario",
16
+ "evidence",
17
+ "why_not_later",
18
+ "raises"
19
+ ],
20
+ "properties": {
21
+ "severity": { "enum": ["blocking", "polish"] },
22
+ "summary": { "type": "string" },
23
+ "where": { "type": ["string", "null"] },
24
+ "scenario": { "type": ["string", "null"] },
25
+ "evidence": { "type": ["string", "null"] },
26
+ "why_not_later": { "type": ["string", "null"] },
27
+ "raises": { "type": ["string", "null"] }
28
+ }
29
+ }
30
+ }
31
+ }
32
+ }
@@ -17,7 +17,7 @@ import { spawnSync } from 'node:child_process';
17
17
  import path from 'node:path';
18
18
  import { fileURLToPath } from 'node:url';
19
19
  import { metricsCommand, runsCommand } from './metrics.js';
20
- import { codexReview } from './codex-review.js';
20
+ import { codexReview, promptOf } from './codex-review.js';
21
21
  import {
22
22
  run,
23
23
  card,
@@ -685,15 +685,24 @@ function registerCodexReview(harness) {
685
685
  )
686
686
  .requiredOption('--kind <kind>', 'plan or code')
687
687
  .requiredOption('--pass <k>', 'the pass number, 1 or more')
688
+ .option(
689
+ '--prompt-only',
690
+ "print the pass's prompt for a Claude row's subagent; no Codex runs (the core is asked)",
691
+ )
688
692
  .option(
689
693
  '--json',
690
- 'machine output: {findings, by} | {skipped, fallback?} | {failed, by?, fallback?}',
694
+ 'machine output: {findings, by} | {skipped, fallback?} | {failed, by?, fallback?}; ' +
695
+ 'with --prompt-only {prompt, mode}',
691
696
  )
692
697
  .action((id, o) => {
693
698
  const r = /** @type {any} */ (codexReviewOf(process.cwd(), id, o));
699
+ // A prompt that is no prompt must not reach a subagent as one.
700
+ if (o.promptOnly && !r.prompt) process.exitCode = 1;
694
701
  if (o.json) return console.log(JSON.stringify(r));
695
- if (r.findings)
696
- for (const f of r.findings) console.log(`${f.severity}: ${f.where}: ${f.text}`);
702
+ if (r.prompt) console.log(r.prompt);
703
+ else if (r.findings)
704
+ for (const f of r.findings)
705
+ console.log(`${f.severity}: ${f.where}: ${f.summary ?? f.text}`);
697
706
  else console.log(r.skipped ? `skipped: ${r.skipped}` : `failed: ${r.failed}`);
698
707
  });
699
708
  }
@@ -863,26 +872,27 @@ export function itemLock(runs, id) {
863
872
 
864
873
  /**
865
874
  * Pass k of item `id`'s review of `kind` by Codex: the row from the core (`gcf review row`, the
866
- * code's diff written with it), then the pass. GCF_CODEX (a JSON list: the command and its first
867
- * arguments) names another Codex, a test's fake.
875
+ * diff written with it: the code's, or a plan check's), then the pass; with `promptOnly`, the
876
+ * prompt alone for a Claude row's subagent (Plan-Review-Rework-Plan d6), no Codex run. GCF_CODEX
877
+ * (a JSON list: the command and its first arguments) names another Codex, a test's fake.
878
+ * @param {string} projectDir
879
+ * @param {string} id
880
+ * @param {{kind: string, pass: string, promptOnly?: boolean}} o
868
881
  */
869
- function codexReviewOf(projectDir, id, { kind, pass }) {
870
- const diff = kind === 'code' ? ['--diff'] : [];
871
- const r = cliCore(projectDir)([
872
- 'review',
873
- 'row',
874
- id,
875
- '--kind',
876
- kind,
877
- '--pass',
878
- pass,
879
- ...diff,
880
- '--json',
881
- ]);
882
- if (!r.ok) return { failed: (r.err || r.out).trim() };
882
+ export function codexReviewOf(
883
+ projectDir,
884
+ id,
885
+ { kind, pass, promptOnly },
886
+ core = cliCore(projectDir),
887
+ ) {
888
+ // A plan's full pass gets no diff from the core (`diff: null`); its check gets the frozen one.
889
+ const r = core(['review', 'row', id, '--kind', kind, '--pass', pass, '--diff', '--json']);
890
+ if (!r.ok) return { failed: (r.err || r.out).trim() || 'gcf review row failed with no output' };
891
+ const row = json(r, 'review row');
892
+ if (promptOnly) return { prompt: promptOf(row), mode: row.mode ?? null };
883
893
  const codex = process.env.GCF_CODEX ? JSON.parse(process.env.GCF_CODEX) : undefined;
884
894
 
885
- return codexReview(projectDir, { row: json(r, 'review row'), codex });
895
+ return codexReview(projectDir, { row, codex });
886
896
  }
887
897
 
888
898
  /** The autopilot's stop while the project is held (Hold-Plan d9). */
package/commands/run.js CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  import { mkdir, open, readFile, rm, writeFile } from 'node:fs/promises';
18
18
  import path from 'node:path';
19
19
  import { fileURLToPath } from 'node:url';
20
+ import { isDeepStrictEqual } from 'node:util';
20
21
  import {
21
22
  CHAT_TIMEOUT_MIN,
22
23
  SESSION_ID,
@@ -180,6 +181,9 @@ export function json(res, what) {
180
181
  // The core's rule for `item new`: a leading hyphen would read as a flag.
181
182
  const RUN_WORD = /^[A-Za-z0-9][\w.-]*$/;
182
183
 
184
+ // The phases of an item's run, each with its own model and effort (Plan-Review-Rework-Plan d10).
185
+ const RUN_PHASES = ['plan', 'implement'];
186
+
183
187
  /**
184
188
  * What one item runs on: the run's override (`run --model|--effort`, this run only) over the
185
189
  * item's own `model:` and `effort:`, over the project's (`agent.model|effort` of
@@ -193,12 +197,10 @@ const RUN_WORD = /^[A-Za-z0-9][\w.-]*$/;
193
197
  * @param {{model?: string | null, effort?: string | null}} [defaults]
194
198
  */
195
199
  export function choiceOf(item, override = {}, project = {}, defaults = {}) {
196
- const set = (v) => (v === null || v === undefined || v === 'default' ? null : String(v));
197
200
  /** @type {{model: string | null, effort: string | null}} */
198
201
  const out = { model: null, effort: null };
199
202
  for (const k of /** @type {const} */ (['model', 'effort'])) {
200
- const v =
201
- [override, item, project, defaults].map((l) => set(l?.[k])).find((x) => x !== null) ?? null;
203
+ const v = firstPick([override, item, project, defaults], k);
202
204
  if (v !== null && !RUN_WORD.test(v)) throw new Error(`${k}: ${v} is not one plain word`);
203
205
  out[k] = v;
204
206
  }
@@ -206,6 +208,44 @@ export function choiceOf(item, override = {}, project = {}, defaults = {}) {
206
208
  return out;
207
209
  }
208
210
 
211
+ /** A level's model or effort: null, missing or `default` is none. */
212
+ const pickOf = (v) => (v === null || v === undefined || v === 'default' ? null : String(v));
213
+
214
+ /** The first level's `k` that is one, or null. */
215
+ const firstPick = (levels, k) => levels.map((l) => pickOf(l?.[k])).find((x) => x !== null) ?? null;
216
+
217
+ const PICKS = ['model', 'effort'];
218
+
219
+ /** The first level's model and effort, each on its own. */
220
+
221
+ const firstOf = (levels) => ({
222
+ model: firstPick(levels, 'model'),
223
+ effort: firstPick(levels, 'effort'),
224
+ });
225
+
226
+ /**
227
+ * The item's and the project's levels of `choiceOf` in `phase` (`plan`, `implement`:
228
+ * Plan-Review-Rework-Plan d10): the item's `<phase>_model|effort` over its own; the project's
229
+ * `agent.<phase>` over `agent.model|effort` over GCF's default of the phase (`phase_defaults` of
230
+ * the core's `agent` read). GCF's default sets a flag the agent has a default of
231
+ * (`defaults`): an agent the engine knows no flags of takes none of it. No phase: as they are.
232
+ * @param {any} item
233
+ * @param {any} project the core's `agent` read
234
+ * @param {string | null | undefined} phase
235
+ * @param {{model?: string | null, effort?: string | null}} [defaults] the agent's
236
+ */
237
+ export function inPhase(item, project, phase, defaults = {}) {
238
+ if (!phase) return { item, project };
239
+ const own = { model: item?.[`${phase}_model`], effort: item?.[`${phase}_effort`] };
240
+ const gcf = project?.phase_defaults?.[phase] ?? {};
241
+ const known = Object.fromEntries(PICKS.map((k) => [k, defaults[k] ? gcf[k] : null]));
242
+
243
+ return {
244
+ item: firstOf([own, item]),
245
+ project: firstOf([project?.[phase], project, known]),
246
+ };
247
+ }
248
+
209
249
  /**
210
250
  * The agent command of one item: what it runs on (`choiceOf`) becomes `--model` and `--effort`,
211
251
  * the flags of `claude`.
@@ -325,11 +365,11 @@ async function prepare({ claimed, failed }, core, agentOf) {
325
365
  const ready = [];
326
366
  for (const { id, release } of claimed) {
327
367
  try {
328
- const { agent, choice } = agentOf(id);
368
+ const command = agentOf(id);
329
369
  const wt = json(await core(['worktree', id, '--json']), `worktree ${id}`);
330
370
  if (wt.sync) throw new Error(wt.sync);
331
371
  const lessonsPrompt = await lessonsFor(core, id);
332
- ready.push({ id, dir: wt.path, agent, choice, release, lessonsPrompt });
372
+ ready.push({ id, dir: wt.path, ...command, release, lessonsPrompt });
333
373
  } catch (e) {
334
374
  await release();
335
375
  failed.push({ id, result: 'error', error: e.message });
@@ -491,8 +531,7 @@ function recordFor(r) {
491
531
  ended: endedOf(r),
492
532
  ...resetsOf(r.limit),
493
533
  ...waitOf(r),
494
- // The session's dollars so far: claude reports a resumed session's whole total.
495
- ...(r.session_id && r.total ? { cost_usd: r.total } : {}),
534
+ ...sessionKept(r),
496
535
  // The handoffs so far: the cap holds across runs.
497
536
  ...(r.handoffs ? { handoffs: r.handoffs } : {}),
498
537
  // The fresh session a counted handoff started ended with no id: the next one is no new
@@ -506,6 +545,18 @@ function recordFor(r) {
506
545
  };
507
546
  }
508
547
 
548
+ /**
549
+ * What a record keeps of its session: the dollars so far (claude reports a resumed session's
550
+ * whole total) and the phase it ran in, whose model its resume goes on with (d10).
551
+ */
552
+ const sessionKept = (r) =>
553
+ r.session_id
554
+ ? {
555
+ ...(r.total ? { cost_usd: r.total } : {}),
556
+ ...(r.session_phase ? { session_phase: r.session_phase } : {}),
557
+ }
558
+ : {};
559
+
509
560
  /**
510
561
  * Why a record hands over when it is no context's handoff (Hold-Plan d5a): a Hold, the reserve,
511
562
  * the end of the planning phase, after which the implementation goes on.
@@ -819,14 +870,16 @@ const step13Of = (dir) => () => {
819
870
 
820
871
  /**
821
872
  * Where an item's planning stands (`gcf plan check --json` in its checkout, Hold-Plan d13): its
822
- * verdict and each pass's blocking count; null when the core cannot say.
873
+ * verdict and each pass's blocking count; null when the core cannot say. A plan with no task is
874
+ * none yet: converged only once it has one, so planning with no review rows (`review.plan:
875
+ * none`) still is a phase of its own, on its own model (Plan-Review-Rework-Plan d10).
823
876
  */
824
877
  async function planState(core, r) {
825
878
  try {
826
879
  const x = JSON.parse((await core(['plan', 'check', r.id, '--json'], { cwd: r.dir })).out);
827
880
 
828
881
  return {
829
- converged: Boolean(x.converged),
882
+ converged: Boolean(x.converged) && x.tasks > 0,
830
883
  stalled: Boolean(x.stalled),
831
884
  passes: (x.passes ?? []).map((p) => p.blocking),
832
885
  };
@@ -848,10 +901,26 @@ const runEnv = (r) => ({ GCF_RUN_ITEM: r.id, ...(r.base ? { GCF_RUN_BASE: r.base
848
901
  */
849
902
  function phasesOf(s) {
850
903
  const { r, core } = s;
851
- const ph = { now: /** @type {string | null} */ (null) };
852
- if (r.task) return { ph, env: undefined, afterRun: undefined, phaseOver: undefined };
853
- const env = async () => {
854
- ph.now = (await planState(core, r))?.converged ? 'implement' : 'plan';
904
+ const ph = {
905
+ now: /** @type {string | null} */ (null),
906
+ // The plan's passes as this run's planning started, and those it added (d12).
907
+ start: /** @type {number | null | undefined} */ (undefined),
908
+ passes: /** @type {number | null} */ (null),
909
+ };
910
+ if (r.task) return { ph, next: undefined, env: undefined, afterRun: undefined };
911
+ // The phase of the session about to start (d10): a resume goes on in its own, the cut
912
+ // session's or the one its kept record names; else the plan check's.
913
+ const ownOf = (kind) => (kind === 'resume' ? (ph.now ?? s.rec?.session_phase ?? null) : null);
914
+ const next = async (kind) => {
915
+ const own = ownOf(kind);
916
+ const state = own && ph.start != null ? null : await planState(core, r);
917
+ ph.start ??= state?.passes.length ?? null;
918
+
919
+ return own ?? (state?.converged ? 'implement' : 'plan');
920
+ };
921
+
922
+ const env = async (kind) => {
923
+ ph.now = await next(kind);
855
924
 
856
925
  return { ...s.launch?.env, ...runEnv(r), GCF_RUN_PHASE: ph.now };
857
926
  };
@@ -859,26 +928,29 @@ function phasesOf(s) {
859
928
  const over = async () => {
860
929
  if (ph.now !== 'plan') return null;
861
930
  const state = await planState(core, r);
931
+ // The passes this run added, on the session's result: the run's end sums its plan phase.
932
+ ph.passes = state && ph.start != null ? Math.max(0, state.passes.length - ph.start) : null;
862
933
 
863
934
  return state?.converged || state?.stalled ? state : null;
864
935
  };
865
936
 
866
937
  const afterRun = async () => {
867
938
  const state = await over();
868
- if (!state) return { phase: ph.now };
939
+ const phase = ph.now === 'plan' ? { phase: ph.now, passes: ph.passes } : { phase: ph.now };
940
+ if (!state) return phase;
869
941
  tellPhaseEnd(s, state);
870
942
  if (state.converged) {
871
943
  writeSync(s.fd, `[${clock()}] plan converged in ${state.passes.length} passes\n`);
872
944
 
873
- return { phase: ph.now, phaseEnded: true };
945
+ return { ...phase, phaseEnded: true };
874
946
  }
875
947
 
876
948
  await stallOf(s, state);
877
949
 
878
- return { phase: ph.now, stalledPlan: state.passes };
950
+ return { ...phase, stalledPlan: state.passes };
879
951
  };
880
952
 
881
- return { ph, env, afterRun, phaseOver: async () => Boolean(await over()) };
953
+ return { ph, next, env, afterRun, phaseOver: async () => Boolean(await over()) };
882
954
  }
883
955
 
884
956
  /** The planning phase's end as a step of the item's chat (Hold-Plan d18), when it has one. */
@@ -925,11 +997,11 @@ const itemChat = (r, launch, logs, { steps, phaseOver, rec }) =>
925
997
  * run's policy. `rec` is the session its last run kept. Returns the job's result, with
926
998
  * `skipped` (a session wrote code outside aif-implement) and `lessons` (how many went in).
927
999
  */
928
- async function itemJob(s, rec) {
1000
+ async function itemJob(s, kept) {
929
1001
  const { r, logs, launch, lock } = s;
930
1002
  const adapter = adapterFor(r.agent);
931
- // Where the card's work starts in this run: a code stall on main keeps it as its base.
932
- r.base ??= headOf(r.dir);
1003
+ await startOf(r, s.core);
1004
+ const rec = await phaseKept(s, kept);
933
1005
  // The item's steps, one watch across its sessions: a fresh one does not converge again. A
934
1006
  // handoff an earlier run left goes on past its plan: its aif-implement is no new step.
935
1007
  // A step's ok is what the work left (fix A): the DoD's row in main's verify-log.csv, the
@@ -940,15 +1012,18 @@ async function itemJob(s, rec) {
940
1012
  head: () => headOf(r.dir),
941
1013
  worktree: !r.main,
942
1014
  });
943
- if (rec?.ended === 'handoff') steps.skipPlan();
1015
+ if (rec?.ended === 'handoff' && rec.phase !== 'plan') steps.skipPlan();
944
1016
  const quota = path.join(logs, 'quota.json');
945
1017
  // This run wrote the item's record before a limit wait.
946
1018
  let persisted = false;
947
- const phases = phasesOf({ ...s, steps });
1019
+ // The command of the session the gate, the reserve and a limit wait judge (d10).
1020
+ s.live = { agent: r.agent };
1021
+ const phases = phasesOf({ ...s, steps, rec });
948
1022
  const reserve = reserveWatch(s);
949
1023
  const ran = await runJob({
950
1024
  adapter,
951
- agent: r.agent,
1025
+ // Each session's command by its phase (Plan-Review-Rework-Plan d10).
1026
+ agent: r.agentIn ? (_kind, env) => (s.live.agent = r.agentIn(env?.GCF_RUN_PHASE)) : r.agent,
952
1027
  dir: r.dir,
953
1028
  id: r.id,
954
1029
  logs,
@@ -976,26 +1051,92 @@ async function itemJob(s, rec) {
976
1051
  // A run the operator started goes now: it meets the limit, if it holds, and waits then.
977
1052
  // Automation keeps the quota's reserve as well (Hold-Plan d7, d11).
978
1053
  // After an early wake the quota state is still the cut session's: no wait for it (t1 d3).
979
- beforeSession: s.waitLimit
980
- ? async (now, o) => (o?.woke ? null : resetAhead(quota, now)) ?? (await reserve.gate())
981
- : undefined,
1054
+ beforeSession: s.waitLimit ? gateOf(s, phases, reserve, quota) : undefined,
982
1055
  wake: wakeOfRun(s, reserve),
983
1056
  clock: s.limitClock,
984
1057
  // Before a limit wait: a run killed meanwhile resumes the same session.
985
1058
  // Whole or not at all: the board reads it while the run waits (AD-34).
986
1059
  persist: (state) => {
987
1060
  persisted = true;
988
- writeAtomic(
989
- recordOf(logs, r.id),
990
- `${JSON.stringify(recordFor({ ...state, main: r.main }), null, 2)}\n`,
991
- );
1061
+ const phase = phaseOfKept(state, phases, rec);
1062
+ const kept = recordFor({ ...state, main: r.main, session_phase: phase });
1063
+ writeAtomic(recordOf(logs, r.id), `${JSON.stringify(kept, null, 2)}\n`);
992
1064
  },
993
1065
  quota,
994
1066
  learned: launch?.learned,
995
1067
  chat: itemChat(r, launch, logs, { steps, phaseOver: phases.phaseOver, rec }),
996
1068
  }).finally(reserve.stop);
997
1069
 
998
- return jobResult(r, ran, { reserve, persisted });
1070
+ return jobResult(r, ran, { reserve, persisted, rec });
1071
+ }
1072
+
1073
+ /**
1074
+ * The gate before each session of an automation run: a reset still ahead, then the quota's
1075
+ * reserve, judged on the model of the session about to start (d10).
1076
+ */
1077
+ const gateOf = (s, phases, reserve, quota) => async (now, o) => {
1078
+ if (s.r.agentIn && phases.next) s.live.agent = s.r.agentIn(await phases.next(o?.kind));
1079
+
1080
+ return (o?.woke ? null : resetAhead(quota, now)) ?? (await reserve.gate());
1081
+ };
1082
+
1083
+ /** The phase of the session a limit wait's record keeps: the cut one's, or the kept one's. */
1084
+ const phaseOfKept = (state, phases, rec) =>
1085
+ state.session_id ? (phases.ph.now ?? rec?.session_phase) : undefined;
1086
+
1087
+ /**
1088
+ * The kept session of item `s.r` as this run takes it (d10): one whose phase the work has left
1089
+ * (its plan converged since, or opened again) is not resumed on its old phase's model: the
1090
+ * rerun starts fresh in the phase it is in now, as after the planning's end (d13). A record
1091
+ * with no phase, or a plan check that fails, is taken as before.
1092
+ */
1093
+ async function phaseKept(s, rec) {
1094
+ if (s.r.task || !rec?.session_id || !rec.session_phase) return rec;
1095
+ const state = await planState(s.core, s.r);
1096
+ if (!state) return rec;
1097
+ const now = state.converged ? 'implement' : 'plan';
1098
+ if (now === rec.session_phase) return rec;
1099
+ const { session_id: _id, session_phase: _phase, ...rest } = rec;
1100
+
1101
+ return { ...rest, ended: 'handoff', counted: true, reason: 'phase', phase: now };
1102
+ }
1103
+
1104
+ /**
1105
+ * Where item `r`'s work starts in this run, and the content of each instruction path its
1106
+ * checkout had uncommitted then: one the run leaves as it was is not the run's (`instructionsOf`).
1107
+ */
1108
+ async function startOf(r, core) {
1109
+ // A code stall on main keeps it as its base.
1110
+ r.base ??= headOf(r.dir);
1111
+ if (r.dirtyBefore || !r.base) return;
1112
+ r.dirtyBefore = blobsOf(r.dir, (await instructionNames(core, r, r.base))?.uncommitted ?? []);
1113
+ }
1114
+
1115
+ /** The paths of the instructions commits since `from` changed, and those not committed, or null. */
1116
+ async function instructionNames(core, r, to) {
1117
+ try {
1118
+ const diff = ['rules', 'diff', '--from', r.base, '--to', to, '--names', '--json'];
1119
+
1120
+ return json(await core(diff, { cwd: r.dir }), 'rules diff');
1121
+ } catch {
1122
+ // A core with no such read: no mark.
1123
+ return null;
1124
+ }
1125
+ }
1126
+
1127
+ /** Each of `paths` with the hash of its content on disk; null when it is not there. */
1128
+ function blobsOf(dir, paths) {
1129
+ return Object.fromEntries(
1130
+ paths.map((p) => {
1131
+ const r = spawnSync('git', ['hash-object', '--', p], {
1132
+ windowsHide: true,
1133
+ cwd: dir,
1134
+ encoding: 'utf8',
1135
+ });
1136
+
1137
+ return [p, r.status === 0 ? r.stdout.trim() : null];
1138
+ }),
1139
+ );
999
1140
  }
1000
1141
 
1001
1142
  /**
@@ -1003,11 +1144,15 @@ async function itemJob(s, rec) {
1003
1144
  * leaves the kept record alone), `reserve` (what the reserve stood on, Hold-Plan d5), `skipped`
1004
1145
  * (a session wrote code outside aif-implement) and `lessons` (how many went in).
1005
1146
  */
1006
- function jobResult(r, ran, { reserve, persisted }) {
1147
+ function jobResult(r, ran, { reserve, persisted, rec }) {
1007
1148
  const sessions = ran.sessions ?? [];
1149
+ const plan = planSpent(sessions, rec);
1150
+ const phase = keptPhase(ran, sessions, rec);
1008
1151
 
1009
1152
  return {
1010
1153
  ...ran,
1154
+ ...(plan ? { plan } : {}),
1155
+ ...(phase ? { session_phase: phase } : {}),
1011
1156
  ranAny: sessions.some((x) => !x.notStarted),
1012
1157
  ...(ran.held === 'reserve' ? { reserve: reserve.last()?.reserve ?? {} } : {}),
1013
1158
  skipped: sessions.some((x) => skippedImplement(r, x)),
@@ -1016,6 +1161,52 @@ function jobResult(r, ran, { reserve, persisted }) {
1016
1161
  };
1017
1162
  }
1018
1163
 
1164
+ /**
1165
+ * The phase of the session a job keeps: the last one's; one not started (held at its gate after
1166
+ * a limit's reset) the phase of that session as it ran, or the kept record's.
1167
+ */
1168
+ export const keptPhase = (ran, sessions, rec) =>
1169
+ ran.phase ??
1170
+ sessions.findLast((x) => x.phase && x.session_id === ran.session_id)?.phase ??
1171
+ (ran.session_id && ran.session_id === rec?.session_id ? rec.session_phase : null);
1172
+
1173
+ /**
1174
+ * What the planning phase of a job took (Plan-Review-Rework-Plan d12): the passes this run
1175
+ * added, the dollars and milliseconds of its planning sessions; null when none planned. The
1176
+ * lessons turn after a planning session is not in it: the job keeps no turn's cost by its
1177
+ * session. A resumed session reports the dollars of the whole session: its own count from what
1178
+ * that session reached before (the kept record's, or its earlier part's in this job).
1179
+ * @param {any[]} sessions the job's sessions, each with its `phase` and `cost`
1180
+ * @param {any} [rec] the session a run before kept
1181
+ */
1182
+ export function planSpent(sessions, rec) {
1183
+ const plan = sessions.filter((x) => x.phase === 'plan');
1184
+ if (!plan.length) return null;
1185
+ const own = ownDollars(sessions, rec);
1186
+
1187
+ return {
1188
+ passes: plan.findLast((x) => Number.isInteger(x.passes))?.passes ?? null,
1189
+ cost_usd: plan.reduce((n, x) => n + (own.get(x) ?? 0), 0),
1190
+ ms: plan.reduce((n, x) => n + (x.cost?.duration_ms ?? 0), 0),
1191
+ };
1192
+ }
1193
+
1194
+ /** Each session's own dollars, by its result: a resumed one's from what its session reached. */
1195
+ function ownDollars(sessions, rec) {
1196
+ const reached = new Map(rec?.session_id ? [[rec.session_id, Number(rec.cost_usd) || 0]] : []);
1197
+ const own = new Map();
1198
+ for (const x of sessions) {
1199
+ const total = x.cost?.cost_usd;
1200
+ if (typeof total !== 'number') continue;
1201
+ const before = reached.get(x.session_id) ?? 0;
1202
+ own.set(x, Math.max(0, total - before));
1203
+ // A result with no total reads 0: the session's last known total stands.
1204
+ if (x.session_id) reached.set(x.session_id, Math.max(total, before));
1205
+ }
1206
+
1207
+ return own;
1208
+ }
1209
+
1019
1210
  // How often a session of automation reads the quota's reserve (Hold-Plan d11).
1020
1211
  const reservePollMs = () => Number(process.env.GCF_RESERVE_POLL_MS) || 5 * 60_000;
1021
1212
 
@@ -1029,7 +1220,8 @@ function wakeOfRun(s, reserve) {
1029
1220
 
1030
1221
  return wakeWatch({
1031
1222
  mark: wakeOf(s.logs, s.r.id),
1032
- model: s.r.agent,
1223
+ // The model of the session the wait is for (d10): its phase's.
1224
+ model: () => s.live.agent,
1033
1225
  command: own,
1034
1226
  reading: own ? null : reserve.reading,
1035
1227
  onWake: (by, until) => {
@@ -1060,8 +1252,9 @@ function reserveWatch(s) {
1060
1252
  let reading = null;
1061
1253
  // The operator's wake lets the reserve go till this reset (t1 d3).
1062
1254
  let released = 0;
1255
+ // The model of the session it gates or watches (d10): a phase's own week counts.
1063
1256
  const now = () =>
1064
- Date.now() < released ? { go: true } : reserveOfReading(reading, s.r.agent, pct);
1257
+ Date.now() < released ? { go: true } : reserveOfReading(reading, s.live.agent, pct);
1065
1258
  const read = async () => {
1066
1259
  try {
1067
1260
  reading = await readUsage({ command });
@@ -1139,9 +1332,18 @@ async function session(r, ctx) {
1139
1332
  };
1140
1333
  const { sessions: _, after: __, ...ran } = await itemJob(s, rec);
1141
1334
 
1142
- return { ...r, ...ran, log: await span() };
1335
+ return { ...r, ...ran, instructions: await instructionsOf(core, r), log: await span() };
1143
1336
  } catch (e) {
1144
- return { ...r, code: null, error: e.message, log: await span().catch(() => null) };
1337
+ // A job that broke after the agent's edits still names them.
1338
+ const instructions = await instructionsOf(core, r);
1339
+
1340
+ return {
1341
+ ...r,
1342
+ code: null,
1343
+ error: e.message,
1344
+ instructions,
1345
+ log: await span().catch(() => null),
1346
+ };
1145
1347
  } finally {
1146
1348
  if (keep) clearInterval(keep);
1147
1349
  await clearMarks(logs, r.id);
@@ -1150,6 +1352,30 @@ async function session(r, ctx) {
1150
1352
  }
1151
1353
  }
1152
1354
 
1355
+ /**
1356
+ * What item `r`'s run changed of the agent's instructions (Lessons-Review-Plan d9), by the
1357
+ * core's `gcf rules diff` in its checkout, a worktree's branch included: the paths its commits
1358
+ * since `r.base` touched (no merges, first parent: a `gcf(sync)` of main is not its), the full
1359
+ * hashes around them, and the paths it left uncommitted: one uncommitted before it counts only
1360
+ * when its content changed. Paths alone (`--names`): a patch could pass the pipe's bound. Null
1361
+ * when it touched none, or the core has no such read.
1362
+ */
1363
+ async function instructionsOf(core, r) {
1364
+ const to = headOf(r.dir);
1365
+ const d = r.base && to ? await instructionNames(core, r, to) : null;
1366
+ if (!d) return null;
1367
+ const before = r.dirtyBefore ?? {};
1368
+ const now = blobsOf(
1369
+ r.dir,
1370
+ d.uncommitted.filter((p) => p in before),
1371
+ );
1372
+ const uncommitted = d.uncommitted.filter((p) => !(p in before) || now[p] !== before[p]);
1373
+
1374
+ return d.paths.length || uncommitted.length
1375
+ ? { paths: d.paths, from: r.base, to, uncommitted }
1376
+ : null;
1377
+ }
1378
+
1153
1379
  const markOf = (logs, id) => path.join(logs, `${id}.session`);
1154
1380
 
1155
1381
  /** The owner item `id`'s session mark names; null with no mark or none named. */
@@ -2001,6 +2227,8 @@ export const runRow =
2001
2227
  i.process,
2002
2228
  run.id,
2003
2229
  run.started,
2230
+ // shortcut: the item's own pick, not each phase's (`phases` of the report); add per-phase
2231
+ // columns at the end when the metrics read them.
2004
2232
  i.model,
2005
2233
  i.effort,
2006
2234
  i.log?.from,
@@ -2009,7 +2237,8 @@ export const runRow =
2009
2237
 
2010
2238
  /**
2011
2239
  * What rides on an item's line beside its result: what it ran on, the bytes of its log, its
2012
- * handoffs, and its broken steps (a skipped step 13, a move with no green verify).
2240
+ * handoffs, its broken steps (a skipped step 13, a move with no green verify), its lessons and
2241
+ * what it changed of the agent's instructions.
2013
2242
  * @param {any} r
2014
2243
  * @param {string | null} [note]
2015
2244
  */
@@ -2018,13 +2247,15 @@ const extras = (r, note = null) => {
2018
2247
 
2019
2248
  return {
2020
2249
  ...r?.choice,
2021
- ...(r?.log ? { log: r.log } : {}),
2022
- ...(r?.handoffs ? { handoffs: r.handoffs } : {}),
2250
+ ...given(r, ['phases', 'plan', 'log', 'handoffs']),
2023
2251
  ...(notes ? { process: notes } : {}),
2024
- ...(r?.lessons ? { lessons: r.lessons } : {}),
2252
+ ...given(r, ['lessons', 'instructions']),
2025
2253
  };
2026
2254
  };
2027
2255
 
2256
+ /** The fields `keys` of `r` that hold something. */
2257
+ const given = (r, keys) => Object.fromEntries(keys.filter((k) => r?.[k]).map((k) => [k, r[k]]));
2258
+
2028
2259
  /** Every claimed item in its worktree at once; blocks recorded on main, verified ones merged. */
2029
2260
  async function runWorktrees(claims, ctx) {
2030
2261
  const { core, logs } = ctx;
@@ -2146,9 +2377,10 @@ async function endLines(ctx, items, runs) {
2146
2377
  }
2147
2378
 
2148
2379
  /**
2149
- * The agent command of each item and what it runs on (`{agent, choice}`), the run's override
2150
- * over the item's own over the project's: `agentOf` (main) reads the board as each item starts,
2151
- * so a main run's later items take a model or effort set meanwhile (`gcf item agent`,
2380
+ * The agent command of each item and what it runs on (`{agent, choice}`; `agentIn(phase)`, the
2381
+ * command of a phase, and `phases`, what each runs on when not all the item's own), the run's
2382
+ * override over the item's own over the project's: `agentOf` (main) reads the board as each item
2383
+ * starts, so a main run's later items take a model or effort set meanwhile (`gcf item agent`,
2152
2384
  * `gcf config set agent.model`), and a board that cannot be read leaves the run's first read;
2153
2385
  * `agentFirst` (worktree) takes the run's first read.
2154
2386
  */
@@ -2156,10 +2388,28 @@ function commandsOf(core, agent, board, override) {
2156
2388
  const itemOf = (items, id) => (items ?? []).find((i) => i.id === id);
2157
2389
  const commandOf = (b, id) => {
2158
2390
  const item = itemOf(b.items, id);
2391
+ // Each phase's at once: a bad value refuses the item before its first session.
2392
+ const at = (phase) => {
2393
+ const x = inPhase(item, b.agent, phase, defaultsOf(agent));
2394
+
2395
+ return {
2396
+ agent: agentFor(agent, x.item, override, x.project),
2397
+ choice: choiceOf(x.item, override, x.project, defaultsOf(agent)),
2398
+ };
2399
+ };
2400
+
2401
+ const base = at(null);
2402
+ const byPhase = Object.fromEntries(RUN_PHASES.map((p) => [p, at(p)]));
2403
+ const differ = RUN_PHASES.some((p) => !isDeepStrictEqual(byPhase[p].choice, base.choice));
2159
2404
 
2160
2405
  return {
2161
- agent: agentFor(agent, item, override, b.agent),
2162
- choice: choiceOf(item, override, b.agent, defaultsOf(agent)),
2406
+ ...base,
2407
+ // The command of the phase a session starts in (GCF_RUN_PHASE); none: the item's own.
2408
+ agentIn: (phase) => byPhase[phase]?.agent ?? base.agent,
2409
+ // What each phase runs on, on the item's line when they are not all the item's own.
2410
+ ...(differ && {
2411
+ phases: Object.fromEntries(RUN_PHASES.map((p) => [p, byPhase[p].choice])),
2412
+ }),
2163
2413
  };
2164
2414
  };
2165
2415
 
@@ -2307,6 +2557,9 @@ export function runEndOf(i, projectDir, launch = null) {
2307
2557
  review,
2308
2558
  left: workLeft(outcome, launch, projectDir),
2309
2559
  handoff,
2560
+ // The run changed the agent's instructions (Lessons-Review-Plan d9): a reminder, no gate.
2561
+ // What its planning phase took (Plan-Review-Rework-Plan d12): passes, dollars, time.
2562
+ ...given(i, ['instructions', 'plan']),
2310
2563
  };
2311
2564
  }
2312
2565
 
package/extension.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://raw.githubusercontent.com/lee-to/ai-factory/2.x/schemas/extension.schema.json",
3
3
  "name": "gcf-harness-aif-ext",
4
- "version": "0.33.0",
4
+ "version": "0.35.0",
5
5
  "description": "GCF orchestration harness for Claude Code: one-command card pipeline, readset guard",
6
6
  "skills": [
7
7
  "skills/gcf-run",
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  // Handoff guard (Harness-PRD §7): a PreToolUse hook the harness hands its agent runs through
3
3
  // `--settings`. When the run sees the session's context pass its handoff share it writes
4
- // .gcf-session/handoff.json; from then on every tool call of the main agent but the plan's
5
- // read and edit is denied with the handoff instruction, which the agent reads as the reason.
4
+ // .gcf-session/handoff.json; from then on every tool call of the main agent but the read and
5
+ // edit of the plan and of a plan pass's findings file is denied with the handoff instruction,
6
+ // which the agent reads as the reason.
6
7
  // The session writes its `## Handoff` into the plan and ends; the harness starts a fresh one.
7
8
  // No flag → silent allow. A subagent's call passes: the reviewer it runs ends cleanly first.
8
9
  // The flag holds for the session of its run only (AD-30): another session in the folder passes.
@@ -27,6 +28,19 @@ function isPlan(file, projectDir, flag) {
27
28
  return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
28
29
  }
29
30
 
31
+ /**
32
+ * Whether a path is a plan pass's findings file, `.gcf-session/review/<id>.c<C>.p<k>.findings
33
+ * .json`: the reviewer's answer kept and judged there lets the next session go on without a paid
34
+ * review again (Plan-Review-Rework-Plan d1).
35
+ */
36
+ function isFindings(file, projectDir) {
37
+ if (typeof file !== 'string' || !file) return false;
38
+ const abs = path.resolve(projectDir, file);
39
+ const rel = path.relative(path.join(projectDir, '.gcf-session', 'review'), abs);
40
+
41
+ return path.dirname(rel) === '.' && rel.endsWith('.findings.json');
42
+ }
43
+
30
44
  // Why the session hands over (the flag's `reason`, Hold-Plan d3), as the agent reads it first.
31
45
  const WHY = {
32
46
  hold: () => 'the operator holds this item: hand over now',
@@ -58,7 +72,11 @@ export function handoffReason(flag) {
58
72
  export function verdict(call, projectDir, flag) {
59
73
  if (!flag) return { allow: true };
60
74
  if (call?.subagent) return { allow: true };
61
- if (PLAN_KINDS.includes(call?.kind) && isPlan(call.paths[0], projectDir, flag))
75
+ const file = call?.paths?.[0];
76
+ if (
77
+ PLAN_KINDS.includes(call?.kind) &&
78
+ (isPlan(file, projectDir, flag) || isFindings(file, projectDir))
79
+ )
62
80
  return { allow: true };
63
81
 
64
82
  return { allow: false, reason: handoffReason(flag) };
@@ -126,7 +126,7 @@ export const decide = (input, projectDir, state, phase) =>
126
126
  function phaseRefusal({ now, converged } = {}) {
127
127
  if (now === 'plan')
128
128
  return (
129
- 'this session plans only: improve the plan and record each pass with gcf plan pass until ' +
129
+ 'this session plans only: review the plan in passes, record each with gcf plan pass until ' +
130
130
  'it converges (or stalls), then end your turn; a fresh session implements it'
131
131
  );
132
132
  if (now !== 'implement') return null;
@@ -19,7 +19,10 @@ const AFTER_MS = 10 * 60_000;
19
19
  /**
20
20
  * @typedef {object} Policy What the work is, for the engine.
21
21
  * @property {any} adapter the provider adapter of `agent`
22
- * @property {string} agent the agent command
22
+ * @property {string | ((kind: string, env: Record<string, string> | undefined) => string)} agent
23
+ * the agent command, or a function of the session's kind and env that gives it at each
24
+ * session's start (a run's phase picks its model, Plan-Review-Rework-Plan d10); the
25
+ * after-session turn runs with its session's
23
26
  * @property {string} dir where the sessions work
24
27
  * @property {string} id the work's id: the name of its chat files
25
28
  * @property {string} logs the folder of its chat files and windows
@@ -47,11 +50,11 @@ const AFTER_MS = 10 * 60_000;
47
50
  * @property {(ran: any, kind: string) => void} [onSession] a session ended: its result
48
51
  * @property {(n: number) => void} [onHandoff] the `n`th fresh session is about to start
49
52
  * @property {(ran: any, ask: Ask) => Promise<any>} [afterSession] the turn after a session
50
- * @property {(now: number, o: {woke: 'operator' | 'usage' | null}) => Gate | Promise<Gate>}
51
- * [beforeSession] the gate before each session (Hold-Plan d7): `{go}`, `{wait, until,
52
- * reserve?, pct?}` (a usage-limit reset still ahead, AD-19, or the quota's reserve) or `{stop,
53
- * why}`; a Date is a wait, null a go. `woke`: the wait before it ended early (t1 d3), so the
54
- * last quota state is still the cut session's
53
+ * @property {(now: number, o: {woke: 'operator' | 'usage' | null, kind: string}) => Gate |
54
+ * Promise<Gate>} [beforeSession] the gate before each session of `kind` (Hold-Plan d7):
55
+ * `{go}`, `{wait, until, reserve?, pct?}` (a usage-limit reset still ahead, AD-19, or the
56
+ * quota's reserve) or `{stop, why}`; a Date is a wait, null a go. `woke`: the wait before it
57
+ * ended early (t1 d3), so the last quota state is still the cut session's
55
58
  * @property {import('./wake.js').Wake} [wake] what ends a limit wait early (t1 d1)
56
59
  * @property {() => string | null} [hold] why the work is to stop now, its sessions handing over
57
60
  * (`hold`, `reserve`): a live session is flagged, a wait ends
@@ -112,7 +115,7 @@ async function capped(j) {
112
115
  */
113
116
  const common = (p, kind = 'after') => ({
114
117
  adapter: p.adapter,
115
- agent: p.agent,
118
+ agent: typeof p.agent === 'function' ? undefined : p.agent,
116
119
  dir: p.dir,
117
120
  flags: typeof p.flags === 'function' ? p.flags(kind) : p.flags,
118
121
  fd: p.fd,
@@ -268,7 +271,8 @@ function decisionOf(d) {
268
271
  async function gate(j, kind, rec) {
269
272
  const holding = heldNow(j.p);
270
273
  if (holding) return { held: holding };
271
- const d = decisionOf(await j.p.beforeSession?.((j.p.clock ?? realClock).now(), { woke: j.woke }));
274
+ const now = (j.p.clock ?? realClock).now();
275
+ const d = decisionOf(await j.p.beforeSession?.(now, { woke: j.woke, kind }));
272
276
  if ('stop' in d && d.stop) return { held: d.why };
273
277
  if (!('wait' in d) || !d.wait) return true;
274
278
  const reserve = Boolean(d.reserve);
@@ -298,6 +302,9 @@ function waitState(j, kind, rec) {
298
302
  };
299
303
  }
300
304
 
305
+ /** A policy value that may be a function of the session's kind (and env): its value. */
306
+ const ofKind = (v, ...args) => (typeof v === 'function' ? v(...args) : v);
307
+
301
308
  /** A session the job did not start: stopped at its gate, or held there (`held`). */
302
309
  const notStarted = (kind, rec, held) => ({
303
310
  code: 'stopped',
@@ -321,13 +328,15 @@ async function session(j, kind, rec) {
321
328
  if (go !== true) return notStarted(kind, rec, go.held);
322
329
  p.handoff?.clear?.();
323
330
  const watch = p.watch?.();
324
- const env = typeof p.env === 'function' ? await p.env(kind) : p.env;
325
- // The after-session turn resumes this session: it runs with its env.
331
+ const env = await ofKind(p.env, kind);
332
+ // The after-session turn resumes this session: it runs with its env and agent command.
326
333
  j.env = env;
334
+ j.agent = ofKind(p.agent, kind, env);
327
335
  const woke = j.woke;
328
336
  j.woke = null;
329
337
  const ran = await runSession({
330
338
  ...common(p, kind),
339
+ agent: j.agent,
331
340
  env,
332
341
  ...first(j, kind, rec),
333
342
  timeoutMs: Math.max(j.deadline - Date.now(), 1000),
@@ -416,6 +425,7 @@ async function after(j, ran, base) {
416
425
  const ask = async (prompt, { timeoutMs = AFTER_MS } = {}) => {
417
426
  turn = await runSession({
418
427
  ...common(p),
428
+ agent: j.agent ?? common(p).agent,
419
429
  env: j.env ?? common(p).env,
420
430
  prompt,
421
431
  resume: ran.session_id,
@@ -31,8 +31,9 @@ export function usageCommand(agent) {
31
31
  * The wake of a limit wait. `mark` is the operator's file (`<logs>/<id>.wake`,
32
32
  * `chats/<t>/wake`); `reading()` gives the reading another watch already keeps (automation's
33
33
  * reserve), else `command` is asked every `pollMs` while a wait lives; neither: the mark alone.
34
- * `onWake(by, until)` hears each wake.
35
- * @param {{mark: string, model?: string | null, command?: string | null,
34
+ * `onWake(by, until)` hears each wake. `model` may be a function: the model of the session the
35
+ * wait is for, read at each look.
36
+ * @param {{mark: string, model?: string | null | (() => string | null), command?: string | null,
36
37
  * reading?: (() => any) | null, pollMs?: number,
37
38
  * onWake?: (by: 'operator' | 'usage', until: Date) => void}} o
38
39
  * @returns {Wake}
@@ -86,7 +87,9 @@ export function wakeWatch({
86
87
  return woke('operator');
87
88
  }
88
89
 
89
- return usage && limitBack(reading ? reading() : own, since, { model, pct, now })
90
+ const m = typeof model === 'function' ? model() : model;
91
+
92
+ return usage && limitBack(reading ? reading() : own, since, { model: m, pct, now })
90
93
  ? woke('usage')
91
94
  : null;
92
95
  },
@@ -144,6 +144,8 @@ export type ChatEvent = At &
144
144
  unticked: number | null;
145
145
  lessons: number;
146
146
  process: string | null;
147
+ // The run changed the agent's instructions (Lessons-Review-Plan d9); absent: none.
148
+ instructions?: { paths: string[]; from: string; to: string; uncommitted: string[] };
147
149
  }
148
150
  /** The planning phase's end: converged in `passes`, or `stalled` with each pass's count. */
149
151
  | { type: 'step'; step: 'plan'; passes: number; stalled?: number[] }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-harness-aif-ext",
3
- "version": "0.33.0",
3
+ "version": "0.35.0",
4
4
  "description": "GCF orchestration harness for Claude Code: one-command card pipeline, readset guard",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,7 +28,7 @@
28
28
  "prepack": "node -e \"const p=require('./package.json'),e=require('./extension.json');if(p.version!==e.version)throw new Error('version mismatch: package.json '+p.version+' vs extension.json '+e.version);require('node:fs').statSync('node_modules/gcf-session/lib/index.js')\""
29
29
  },
30
30
  "peerDependencies": {
31
- "gcf-aif-ext": ">=0.34.0 <0.35.0"
31
+ "gcf-aif-ext": ">=0.36.0 <0.37.0"
32
32
  },
33
33
  "dependencies": {
34
34
  "gcf-session": "file:../gcf-session"
@@ -21,7 +21,7 @@ inputs:
21
21
  - 1 or more work item or design unit ids; a batch shares one playtest list and one play session, while each item's `gcf verify` runs the build and the tests itself
22
22
  - `--worktree` when `ai-factory gcf-harness run` started this session inside the item's worktree
23
23
  - `--handoff` when the harness started this session after the last one: by its context, the operator's hold, the quota's reserve, or the end of the planning phase; the plan's `## Handoff`, when there is one, says where it stopped
24
- - `--through` in your own terminal: plan and implement in this one session; without it you stop after planning (step 11a)
24
+ - `--through` in your own terminal: plan and implement in this one session; without it you stop once the plan converges
25
25
  - `--no-lessons` when the harness asks this session's lessons itself, in a turn after it ends
26
26
  - `--ask d1` or `--ask all` when the harness opened this session to the operator's chat: what to ask them with the AskUserQuestion tool; without it ask no one that way
27
27
  - `--assume` when the project's or the card's gates say `question: assume`: a question goes as your assumption, not to the human
@@ -77,13 +77,45 @@ forbidden_behaviors:
77
77
  - `accepted` true from `review row --kind code`: the human took the open findings, so skip the code review and go on to step 16
78
78
  - a code review `stalled`: commit as step 16 says, then run `ai-factory gcf review stall <id> --kind code --passes <counts> --reason "<the open finding>" --base "$GCF_RUN_BASE"` and stop
79
79
  - under `--worktree` a stall writes `{"stall": {"kind": "plan|code", "passes": [...], "reason": "..."}}` to the outcome instead; the code's comes after the commit of step 24
80
- - a review pass sorts each finding as blocking or polish, and reports how many of each it found
80
+ - a code review pass sorts each finding as blocking or polish, and reports how many of each it found
81
+ - a code review's blocking: a wrong or missing behavior, a broken pillar invariant, a conflict with a project rule, a change no test proves
82
+ - a code review's polish: wording, naming, structure, one more test - you apply it at your judgement, and it does not keep the review from converging
83
+ - a plan pass's reviewer only reads and returns findings as JSON: it never runs aif-improve and never edits the plan
84
+ - you, the plan's author, check each finding against the code, give it a verdict and edit the plan
85
+ - before each plan pass read `ai-factory gcf plan check <id> --json`: `converged` ends the passes, `stalled` is the stop of step 11 and never one pass more
86
+ - else the pass `k` is its `passes` count + 1, of the current cycle: ask only that pass of `review row --kind plan --pass <k>`, never one ahead; a stand-in asks the same pass `k` again
87
+ - its `mode`: `full` reviews the whole plan, `check` checks your fixes by the diff of the plan since the earlier pass (`diff.file` with `--diff`)
88
+ - a plan pass's subagent, a `claude` row's or a stand-in's: its prompt starts with the text of `ai-factory gcf-harness codex-review <id> --kind plan --pass <k> --prompt-only`
89
+ - the plan rubric, the reviewer's own words:
90
+ - blocking: the game or the tool does the wrong thing or not what the item asks, a pillar invariant breaks, a design decision contradicts a hard project rule, or saves or data are at risk
91
+ - a blocking finding names its `where` (d# or t#), its `scenario` (the state or input and the wrong result), its `evidence` (file:line or the rule quoted) and its `why_not_later` (why a red test or the code review would not catch it at the same cost)
92
+ - the core records a blocking finding without a `scenario` as polish
93
+ - polish: a missed procedural step of a project rule, a test that does not prove its decision, wording, order, the split of tasks, a missing behavior with no scenario
94
+ - not a finding: the choice of a fixture, the list of a test's cases, values the code gives, "add more cases"
95
+ - a check gives only the findings that the changes of the diff cause or expose, a fault outside the changed lines included
96
+ - a check also re-examines each blocking finding of pass `k`-1 that you rejected or downgraded, whatever the diff touches; pass 1 of a cycle has none
97
+ - its three questions: is each blocking finding you accepted in pass `k`-1 closed; did a change bring a new blocking one; was each one of pass `k`-1 you rejected or downgraded rightly so
98
+ - a check reopens no earlier finding accepted and fixed, unless the diff breaks its fix
99
+ - a blocking finding still present that a check raises again carries `raises: "<the earlier finding's tag>"`: the core records it accepted, and you fix the plan
100
+ - each finding's verdict: `accepted`, `rejected` with a one-line `reason`, or `downgraded` - a blocking one to polish - with a `reason`
101
+ - judge a finding's severity by the rubric, not by the reviewer's label: a blocking one the rubric calls polish is `downgraded`, one that is no finding or whose scenario the code refutes is `rejected`
102
+ - the order of a plan pass: the reviewer's answer into the findings file, your verdicts into it, your edits of the plan, `gcf plan check`, `gcf plan pass --findings`
103
+ - the findings file of pass `k` is `.gcf-session/review/<id>.c<c>.p<k>.findings.json`, `<c>` the `cycle` of `plan check --json`
104
+ - its form: `{"cycle": <c>, "pass": <k>, "by": "<by>", "for": "<the row>" or null, "findings": [...]}`
105
+ - write the reviewer's findings into it as soon as it answers, then give each its `verdict` and `reason` there; a finding with no `verdict` still waits for your judgement
106
+ - a findings file of the pass `k` that `plan check` waits for: judge the findings with no `verdict`, finish its edits, record it with its `by` and `for`, and never ask its reviewer again
107
+ - no such file: ask the pass again, none of its edits reached the plan
108
+ - keep each pass's file: the next check reads the file of pass `k`-1
109
+ - apply each accepted blocking finding; in a full pass with none, apply polish at your judgement within the plan's depth of step 8; add a task only when the item needs it
110
+ - in a pass with a blocking finding, apply of its polish only what a blocking fix needs
111
+ - a check's polish is a note for the implementer: it stays in `## Findings`, the plan unedited
112
+ - a plan leaves to the implementer fixtures, test case lists, step-by-step code and the values the code gives
81
113
  - a defect of the code already in the tree that a plan pass finds is a task of the plan, not a blocking finding
114
+ - the plan converges when its last pass holds no blocking finding, accepted, rejected or downgraded: a rejected or downgraded one gets a check
82
115
  - the plan converged under the harness (`GCF_RUN_PHASE` is `plan`): end your reply, a fresh session implements it
83
116
  - the plan converged in your own terminal without `--through`: stop, and say "run `/gcf-run <id> --handoff` in a new session"
84
- - blocking: a wrong or missing behavior, a missing or wrong task, a broken pillar invariant, a conflict with a project rule, a task no check can prove
85
- - polish: wording, splitting or merging tasks, their order, more detail - the pass applies it, and it does not keep the plan from converging
86
- - a `format:` line of `ai-factory gcf plan check` is polish: the pass brings the plan into the plan form it names, and it never blocks
117
+ - a `format:` line of `ai-factory gcf plan check` is polish that never blocks: run the check before pass 1 too
118
+ - bring the plan into the form a `format:` line names before you ask the next pass: a plan reshaped after a snapshot makes the next diff the whole plan
87
119
  - do not edit `status:` or `gcf/LIVE.md` by hand: `submit`, `close` and `block` own them
88
120
  - do not write a plan task's first implementation outside the aif-implement skill: it ticks the task done in the plan, and the board shows the item's progress from those ticks
89
121
  - a fix for a red DoD or a review finding goes in directly, without aif-implement
@@ -93,7 +125,8 @@ forbidden_behaviors:
93
125
  - a ticked task whose code aif-implement's re-entry check finds missing stays pending and gets implemented, with no question to the human
94
126
  - at aif-implement's last question, verify or commit, pick neither: go on with step 13, which verifies, and steps 14-16, which review and commit
95
127
  - an aif-implement question none of these name: answer it by the same rule - the changes stay uncommitted and unstashed, the plan's tasks go on, and GCF commits and moves the item
96
- - do not leave a task ticked that the tune note, the answer, an amend or a decision from the run's chat reopens: untick it and add the note before step 13, or aif-implement's re-entry check ticks it again over the old code
128
+ - write the tune note, the answer or the amend into the kept plan's decisions and tasks before step 10 asks a pass: a check reads only the diff since the last pass
129
+ - do not leave a task ticked that the tune note, the answer, an amend or a decision from the run's chat reopens: untick it and add the note before step 10, or aif-implement's re-entry check ticks it again over the old code
97
130
  - a `notes:` line that contradicts a slot of the card is the human's word: build by it, ask nothing, and rewrite that slot of your own card by it in your commit, as only the slots reach the documents of the systems
98
131
  - a decision from the run's chat that contradicts a slot goes the same way
99
132
  - do not ask about or block on what stops your tools here and this machine's tools can clear: a held file, an application holding a lock, a stopped service
@@ -108,7 +141,7 @@ forbidden_behaviors:
108
141
  - a call the handoff guard denies with "context at", "the operator holds this item" or "reserve" is no refusal: block nothing, write the `## Handoff` it asks for and end the reply
109
142
  - an aif-implement the implement guard denies for the planning phase or an unconverged plan is no refusal either: record the pass, if any, and end the reply; the harness starts the next session
110
143
  - a read the readset guard denies is no refusal either: drop that read; never add a `system:` or `depends:` only to read a file - when one of them is wrong in substance, fix it on main, and under `--worktree` stop with a block that names the fix
111
- - the context's `graveyard_hits`, `d2` and `d2_fired` lines belong to the readset: hand them to every fresh subagent of steps 8 and 14 in its prompt
144
+ - the context's `graveyard_hits`, `d2` and `d2_fired` lines belong to the readset: hand them to every fresh subagent of steps 10 and 14 in its prompt
112
145
  - a design question of step 12 also gets a D1 record: `ai-factory gcf question add --class D1 --question "<question>" --proposed "<your answer>" --blocks <id>`, before the block
113
146
  - under `--worktree` that question goes into the block reason only, and the human files its D1 on main
114
147
  - do not rely on a value of a D2 that step 6 lists in `d2_fired`: its trigger fired, and the value is the human's call now
@@ -131,13 +164,13 @@ workflow:
131
164
  5. gate: run `ai-factory gcf-harness gate <item-ids...>` over the whole batch; a non-zero exit is a failed gate, its stderr line is the reason; outside `--worktree`, then claim the item and take its conflict lines first
132
165
  6. readset: run `ai-factory gcf context <item-id> --json --readset`; it writes `.gcf-session/readset.json` for this session itself; `over_budget: true` stops the run with a D1 question naming the subsystem
133
166
  7. plan: run aif-plan full for the item into its `plan:` path, by default `.ai-factory/plans/<id>.md`, reading only the readset files; an existing plan (the item came back after a tune, an unblock, a continue or an amend) is kept, not rewritten
134
- 8. improve the plan in passes, each pass a fresh subagent that reads only the plan and the readset and applies aif-improve without questions, writing each default it picks into the plan
135
- 9. each pass also checks every task against the `invariant` of each pillar in `gcf/PILLARS.md`: the pass reworks a task that breaks one, and a conflict no rework removes is a pillar conflict of step 12
136
- 10. after each pass run `ai-factory gcf plan check <id>`, a failure blocks the item; then record the pass: `ai-factory gcf plan pass <id> --blocking <n> --polish <m> --by <by> --json`
137
- 11. `stalled`: run `ai-factory gcf review stall <id> --kind plan --passes <each pass's blocking count, comma-separated> --reason "<the open finding>"` and stop
167
+ 8. the plan holds decisions - behavior, interfaces, data owners, invariants, the edge cases that change the design - and tasks of a file or a component, each with what its check proves
168
+ 9. before pass 1 check the plan yourself against the project's rules in `AGENTS.md` and the `invariant` of each pillar in `gcf/PILLARS.md`: rework a task that breaks one; a conflict no rework removes is a pillar conflict of step 12
169
+ 10. review the plan in passes by `review row --kind plan`, each in the order of a plan pass; a failed `ai-factory gcf plan check <id>` blocks the item; record: `ai-factory gcf plan pass <id> --findings <file> --by <by> [--for <the row>] --json`
170
+ 11. `stalled`: run `ai-factory gcf review stall <id> --kind plan --passes <each pass's blocking count, comma-separated> --reason "<the last pass's blocking findings and their verdicts>"` and stop
138
171
  12. a question only the human can answer - a save format, a public API, a new dependency, a pillar conflict, and no other: run `ai-factory gcf block <id> --reason "<question>"` and stop
139
172
  13. run the aif-implement skill on `@<plan path>`, write the item's `live:` delta, then run `ai-factory gcf verify <id>` and check the item's negative constraints; a non-zero exit is a red DoD; attempts <= `dod_attempts`, each with a diagnosis
140
- 14. review the code in passes by `review row --kind code`: fix what each finds that holds, run `ai-factory gcf verify <id>` again, and record the pass with `gcf plan pass --kind code`
173
+ 14. review the code in passes by `review row --kind code`: fix what each finds that holds, run `ai-factory gcf verify <id>` again, and record the pass: `ai-factory gcf plan pass <id> --kind code --blocking <n> --polish <m> --by <by> --json`
141
174
  15. the code reviewer also answers the `review_question` of each pillar in `gcf/PILLARS.md` over the diff: an answer that breaks the pillar is a finding
142
175
  16. tick the plan tasks done outside aif-implement, the verify and the review; then commit the code, its plan and the `live:` delta via aif-commit
143
176
  17. gate `verdict` or `decision`: run `ai-factory gcf submit <id>`; gate `auto`: `ai-factory gcf close <id>` - a soft unit closes unplayed; the core defers what the gates defer; never pass `--unverified`, the human's call
@@ -148,7 +181,7 @@ workflow:
148
181
  22. with `--worktree`, every stop - a failed gate, an over budget readset, a failed plan check, a refused command, steps 12, 14, 18 - writes `{"block": "<reason>"}` to `.gcf-session/outcome.json` and ends the session
149
182
  23. with `--worktree`, run no `ai-factory gcf block`, `submit` or `close`: the core refuses them on a `work/` branch, and the harness records the move on main
150
183
  24. with `--worktree`, step 17 is: commit everything but `gcf/.metrics`, then run `ai-factory gcf verify <id> --mark`; the harness merges the branch
151
- 25. with `--handoff`: run steps 1, 5 and 6, read the plan's `## Handoff`; `gcf plan check <id> --json` says `converged`: skip steps 7-11, go on at step 13; else go on with the passes after `## Passes`
184
+ 25. with `--handoff`: run steps 1, 5 and 6, read the plan's `## Handoff`; `gcf plan check <id> --json` says `converged`: skip steps 7-11, go on at step 13; `stalled`: the stop of step 11; else go on at step 10
152
185
  26. with `--handoff`, take the review findings and the DoD diagnosis of `## Handoff` into steps 13-15, and delete that section alone before the commit of step 16: `## Play notes` and `## Outcome` stay
153
186
  27. without `--no-lessons` and without `--worktree`, end the run with the lessons: run `ai-factory gcf lessons prompt <id>` for each item of the run and do what it says
154
187