gcf-aif-ext 0.29.2 → 0.32.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/lib/plan-check.js CHANGED
@@ -10,24 +10,33 @@ import { glossaryAvoids, GLOSSARY_NAME } from 'cnlp-kit/config';
10
10
  import { buildLedger } from './ledger.js';
11
11
  import { buildContext } from './context.js';
12
12
  import { loadDocProfile } from './design.js';
13
- import { readConfig } from './gcf-paths.js';
13
+ import { modelFamily, readConfig, REVIEW_DEFAULTS } from './gcf-paths.js';
14
14
 
15
- // A pass of the plan's improve loop (Hold-Plan d12): `- pass K[ (cycle C)]: blocking N, polish M[,
16
- // by codex]`, one line each in its `## Passes` section, written by `gcf plan pass`.
17
- const PASS_LINE =
18
- /^- pass (\d+)(?: \(cycle (\d+)\))?: blocking (\d+), polish (\d+)(?:, by (\w+))?$/;
19
- const PASSES = /^## Passes\s*$/;
15
+ // A review pass (Hold-Plan d12, Operator-Tasks-Plan t2 d3): `- pass K[ (cycle C)]: blocking N,
16
+ // polish M[, by <agent:model:effort>[, for <agent:model:effort>]]`, one line each in its section:
17
+ // the plan's `## Passes`, the code's `## Reviews`, written by `gcf plan pass`. `by` may name a
18
+ // slug with `-` and `.`; `for`: the row it stood in for (Fallback-Fidelity-Plan d2).
19
+ const WHO = '[\\w.:-]+';
20
+ const PASS_LINE = new RegExp(
21
+ `^- pass (\\d+)(?: \\(cycle (\\d+)\\))?: blocking (\\d+), polish (\\d+)` +
22
+ `(?:, by (${WHO})(?:, for (${WHO}))?)?$`,
23
+ );
24
+ const SECTION = { plan: /^## Passes\s*$/, code: /^## Reviews\s*$/ };
25
+ const HEADING = { plan: '## Passes', code: '## Reviews' };
20
26
  const PASSES_ANY = /^## Passes\s*$/m;
21
27
 
22
- /** The passes a plan's `## Passes` section records, of every cycle, in order. */
23
- export function planPasses(text) {
28
+ /** The review kinds: the plan's passes, the code's before its commit. */
29
+ export const KINDS = ['plan', 'code'];
30
+
31
+ /** The passes a plan's section of `kind` records, of every cycle, in order. */
32
+ export function planPasses(text, kind = 'plan') {
24
33
  const out = [];
25
34
  let inside = false;
26
35
  for (const line of text.split(/\r?\n/)) {
27
- if (/^## /.test(line)) inside = PASSES.test(line);
36
+ if (/^## /.test(line)) inside = SECTION[kind].test(line);
28
37
  const m = inside ? PASS_LINE.exec(line.trim()) : null;
29
38
  if (!m) continue;
30
- const by = m[5] ? { by: m[5] } : {};
39
+ const by = m[5] ? { by: m[5], ...(m[6] ? { for: m[6] } : {}) } : {};
31
40
  out.push({ pass: +m[1], cycle: +(m[2] ?? 0), blocking: +m[3], polish: +m[4], ...by });
32
41
  }
33
42
 
@@ -35,41 +44,58 @@ export function planPasses(text) {
35
44
  }
36
45
 
37
46
  /**
38
- * The verdict on one cycle's passes (Hold-Plan d12): `converged` when the last found nothing
39
- * blocking; `continue` while the count is within `plan_passes` (raised by the operator's `more`);
40
- * `stalled` past it: one technical pass over the limit, then the operator decides.
47
+ * The verdict on one cycle's passes (t2 d3): `converged` when the last found nothing blocking
48
+ * (or no row reviews); `continue` while a row is left for the next pass (the operator's `more`
49
+ * adds them); `stalled` when the rows are over, then the operator decides.
41
50
  */
42
- export function passVerdict(passes, planPasses, more = 0) {
43
- if (planPasses === 0) return 'converged';
51
+ export function passVerdict(passes, rows, more = 0) {
52
+ if (rows === 0) return 'converged';
44
53
  const last = passes.at(-1);
45
54
  if (!last) return 'continue';
46
55
  if (last.blocking === 0) return 'converged';
47
56
 
48
- return passes.length > planPasses + more ? 'stalled' : 'continue';
57
+ return passes.length < rows + more ? 'continue' : 'stalled';
49
58
  }
50
59
 
51
60
  /**
52
- * Where the item's planning stands: the passes of its current cycle (`plan_cycle`), and the
53
- * verdict on them. The operator's `stall.accepted` converges it; a plan written before this
54
- * version (no `plan_cycle`, no `## Passes`, a task ticked) counts as converged: work in flight
55
- * does not stop at an upgrade.
61
+ * A card's stall of `kind` (t2 d3): `stall.plan` or `stall.code`; the form before t2
62
+ * (`{passes, …}` alone) is the plan's.
56
63
  */
57
- async function passesOf(projectDir, data, text, done) {
58
- const cycle = Number(data.plan_cycle ?? 0);
59
- const passes = planPasses(text).filter((x) => x.cycle === cycle);
60
- const stall = data.stall ?? null;
61
- let limit = 3;
64
+ export function stallOf(data, kind) {
65
+ const stall = data?.stall;
66
+ if (!stall || typeof stall !== 'object') return null;
67
+ if (Array.isArray(stall.passes)) return kind === 'plan' ? stall : null;
68
+
69
+ return stall[kind] ?? null;
70
+ }
71
+
72
+ /** The review rows of `kind` the project sets (or the defaults); a broken config: the defaults. */
73
+ async function rowsOf(projectDir, kind) {
62
74
  try {
63
- limit = Number((await readConfig(path.join(path.resolve(projectDir), 'gcf'))).plan_passes);
75
+ return (await readConfig(path.join(path.resolve(projectDir), 'gcf'))).review[kind];
64
76
  } catch {
65
- // A broken config.yml: the default limit; the config's own check says what is wrong.
77
+ // A broken config.yml: the default rows; the config's own check says what is wrong.
78
+ return REVIEW_DEFAULTS[kind];
66
79
  }
80
+ }
67
81
 
68
- const legacy = data.plan_cycle === undefined && !PASSES_ANY.test(text) && done > 0;
82
+ /**
83
+ * Where the item's review of `kind` stands: the passes of its current cycle (`plan_cycle`), and
84
+ * the verdict on them. The operator's `accepted` converges it; a plan written before passes were
85
+ * recorded (no `plan_cycle`, no `## Passes`, a task ticked) counts as converged: work in flight
86
+ * does not stop at an upgrade.
87
+ */
88
+ async function passesOf(projectDir, data, { text, done, kind = 'plan' }) {
89
+ const cycle = Number(data.plan_cycle ?? 0);
90
+ const passes = planPasses(text, kind).filter((x) => x.cycle === cycle);
91
+ const stall = stallOf(data, kind);
92
+ const rows = (await rowsOf(projectDir, kind)).length;
93
+ const legacy =
94
+ kind === 'plan' && data.plan_cycle === undefined && !PASSES_ANY.test(text) && done > 0;
69
95
  const verdict =
70
- stall?.accepted || legacy ? 'converged' : passVerdict(passes, limit, Number(stall?.more ?? 0));
96
+ stall?.accepted || legacy ? 'converged' : passVerdict(passes, rows, Number(stall?.more ?? 0));
71
97
 
72
- return { cycle, passes, verdict };
98
+ return { cycle, passes, verdict, rows };
73
99
  }
74
100
 
75
101
  /**
@@ -144,23 +170,30 @@ export async function planCheck(projectDir, id) {
144
170
  problems.push(`readset ~${ctx.total_tokens_est} tokens is over the budget ${ctx.budget}`);
145
171
  const text = found === null ? '' : readFileSync(path.resolve(projectDir, plan), 'utf8');
146
172
  const format = found === null ? [] : await planFormat(projectDir, text);
147
- const { cycle, passes, verdict } = await passesOf(projectDir, item.data, text, done);
173
+ const { cycle, passes, verdict } = await passesOf(projectDir, item.data, { text, done });
174
+ const code = await passesOf(projectDir, item.data, { text, done, kind: 'code' });
148
175
 
149
176
  return {
150
177
  ...{ id, plan, tasks, done, problems, format, ok: problems.length === 0 },
151
178
  ...{ cycle, passes, converged: verdict === 'converged', stalled: verdict === 'stalled' },
179
+ // The code's review passes (t2 d3): the same verdict over `## Reviews`.
180
+ review: { passes: code.passes, verdict: code.verdict, rows: code.rows },
152
181
  };
153
182
  }
154
183
 
155
184
  /**
156
- * `gcf plan pass` (Hold-Plan d12): record pass K of the current cycle in the plan's `## Passes`
157
- * section, K the next number, and answer the verdict on the cycle's passes so far.
185
+ * `gcf plan pass` (Hold-Plan d12, t2 d3): record pass K of the current cycle in the plan's
186
+ * section of `kind` (`## Passes`, the code's `## Reviews`), K the next number, and answer the
187
+ * verdict on the cycle's passes so far. `for`: the row the pass was asked of, written only when
188
+ * `by` is someone else (self or a stand-in, Fallback-Fidelity-Plan d2).
158
189
  * @param {string} projectDir
159
190
  * @param {string} id
160
- * @param {{blocking: number, polish: number, by?: string}} pass
191
+ * @param {{blocking: number, polish: number, by?: string, for?: string, kind?: string}} pass
161
192
  */
162
- export async function recordPass(projectDir, id, { blocking, polish, by }) {
163
- passArgs(blocking, polish, by);
193
+ export async function recordPass(projectDir, id, pass) {
194
+ const { blocking, polish, by, kind = 'plan' } = pass;
195
+ passArgs(blocking, polish, by, pass.for);
196
+ if (!KINDS.includes(kind)) throw new Error(`--kind is ${KINDS.join(' | ')}, got ${kind}`);
164
197
  const item = (await buildLedger(projectDir)).item(id);
165
198
  if (!item) throw new Error(`${id} is not a work item of gcf/work/`);
166
199
  const { plan } = planTicks(projectDir, { ...item.data, id });
@@ -168,29 +201,55 @@ export async function recordPass(projectDir, id, { blocking, polish, by }) {
168
201
  if (!existsSync(file)) throw new Error(`no plan at ${plan}: write it first`);
169
202
  const text = readFileSync(file, 'utf8');
170
203
  const cycle = Number(item.data.plan_cycle ?? 0);
171
- const k = planPasses(text).filter((x) => x.cycle === cycle).length + 1;
204
+ const k = planPasses(text, kind).filter((x) => x.cycle === cycle).length + 1;
172
205
  const tag = cycle ? ` (cycle ${cycle})` : '';
173
- const line = `- pass ${k}${tag}: blocking ${blocking}, polish ${polish}${by ? `, by ${by}` : ''}`;
174
- writeFileSync(file, withPass(text, line));
206
+ const line = `- pass ${k}${tag}: blocking ${blocking}, polish ${polish}${whoOf(by, pass.for)}`;
207
+ writeFileSync(file, withPass(text, line, kind));
175
208
  const r = await planCheck(projectDir, id);
176
- const verdict = r.converged ? 'converged' : r.stalled ? 'stalled' : 'continue';
209
+ const now = kind === 'plan' ? { passes: r.passes, verdict: '' } : r.review;
210
+ const verdict =
211
+ kind === 'plan'
212
+ ? r.converged
213
+ ? 'converged'
214
+ : r.stalled
215
+ ? 'stalled'
216
+ : 'continue'
217
+ : now.verdict;
218
+
219
+ return { id, kind, pass: k, cycle, verdict, passes: now.passes.map((x) => x.blocking) };
220
+ }
221
+
222
+ /** A row as one: its Codex slug read as its family. */
223
+ const rowKey = (s) =>
224
+ s
225
+ .split(':')
226
+ .map((x, n) => (n === 1 ? modelFamily(x) : x))
227
+ .join(':');
228
+
229
+ /** A pass line's `, by …[, for …]`: `for` only when `by` is not that row. */
230
+ function whoOf(by, row) {
231
+ if (!by) return '';
177
232
 
178
- return { id, pass: k, cycle, verdict, passes: r.passes.map((x) => x.blocking) };
233
+ return row && rowKey(by) !== rowKey(row) ? `, by ${by}, for ${row}` : `, by ${by}`;
179
234
  }
180
235
 
181
236
  /** The refusal of a pass's counts and reviewer, if any. */
182
- function passArgs(blocking, polish, by) {
237
+ function passArgs(blocking, polish, by, row) {
183
238
  for (const [k, v] of Object.entries({ blocking, polish }))
184
239
  if (!Number.isInteger(v) || v < 0) throw new Error(`--${k} is a count of findings, 0 or more`);
185
- if (by !== undefined && !/^\w+$/.test(by)) throw new Error('--by is one word: the reviewer');
240
+ if (by !== undefined && !/^[\w.-]+(:[\w.-]+){0,2}$/.test(by))
241
+ throw new Error('--by is the reviewer: agent:model:effort, or one word');
242
+ if (row !== undefined && (by === undefined || !/^[\w.-]+:[\w.-]+:[\w.-]+$/.test(row)))
243
+ throw new Error('--for is the row of the pass, agent:model:effort, beside --by');
186
244
  }
187
245
 
188
- /** The plan with `line` at the end of its `## Passes` section, the section added when none. */
189
- function withPass(text, line) {
246
+ /** The plan with `line` at the end of its section of `kind`, the section added when none. */
247
+ function withPass(text, line, kind) {
190
248
  const eol = text.includes('\r\n') ? '\r\n' : '\n';
191
249
  const lines = text.split(/\r?\n/);
192
- const at = lines.findIndex((l) => PASSES.test(l));
193
- if (at < 0) return `${text.replace(/\s*$/, '')}${eol}${eol}## Passes${eol}${eol}${line}${eol}`;
250
+ const at = lines.findIndex((l) => SECTION[kind].test(l));
251
+ if (at < 0)
252
+ return `${text.replace(/\s*$/, '')}${eol}${eol}${HEADING[kind]}${eol}${eol}${line}${eol}`;
194
253
  let end = lines.findIndex((l, n) => n > at && /^## /.test(l));
195
254
  if (end < 0) end = lines.length;
196
255
  // After the section's last line with words: its blank lines stay below it.
package/lib/play-notes.js CHANGED
@@ -107,7 +107,10 @@ export function planTextOf(projectDir, item) {
107
107
  export function rowsFor(play, playOn) {
108
108
  if (!play) return [];
109
109
  const names = Object.keys(play.builds);
110
- const builds = playOn?.length ? playOn.filter((b) => names.includes(b)) : names;
110
+ // As the handoff picks them: a play_on that names no build of the project plays them all.
111
+ const builds = playOn?.some((b) => names.includes(b))
112
+ ? playOn.filter((b) => names.includes(b))
113
+ : names;
111
114
 
112
115
  return builds.flatMap((b) =>
113
116
  play.builds[b].plays_on.map((r) => ({ build: b, device: r.device, os: r.os ?? null })),
@@ -133,7 +136,8 @@ export async function playNotesTemplate(projectDir, id) {
133
136
  '- ',
134
137
  '',
135
138
  '### Rows',
136
- ...(rows.length ? rows.map((r) => `- ${rowKey(r)}: `) : ['- ']),
139
+ // No rows (a project without `plays_on`): nothing to fill in; a note of a row goes to no row.
140
+ ...rows.map((r) => `- ${rowKey(r)}: `),
137
141
  '',
138
142
  '### Watch out',
139
143
  '- ',
@@ -143,42 +147,132 @@ export async function playNotesTemplate(projectDir, id) {
143
147
  ].join('\n');
144
148
  }
145
149
 
150
+ /** A line of `### Rows` as its row (up to the first `:`, without the bullet) and its note. */
151
+ function splitRow(line) {
152
+ const s = line.replace(/^[-*]\s+/, '').trim();
153
+ const at = s.indexOf(':');
154
+
155
+ return at < 0
156
+ ? { row: null, text: s }
157
+ : { row: s.slice(0, at).trim(), text: s.slice(at + 1).trim() };
158
+ }
159
+
146
160
  /**
147
- * What the section lacks, one warning each: the form and what is in it, not its language.
161
+ * @typedef {{kind: 'no_notes' | 'section_unknown' | 'section_empty' | 'row_template' |
162
+ * 'row_unknown' | 'row_missing' | 'no_criterion', text: string, section?: string,
163
+ * row?: string}} PlayNotesIssue
164
+ */
165
+
166
+ /**
167
+ * The issues of `### Rows`. With no rows (no `plays_on`) only what the card lacks, which is
168
+ * nothing; `rows` null (the play: unreadable) keeps the template checks: the rows are unknown.
169
+ * @returns {PlayNotesIssue[]}
170
+ */
171
+ function rowIssues(notes, rows) {
172
+ /** @type {PlayNotesIssue[]} */
173
+ const issues = [];
174
+ // `rows` null: the project's play: could not be read, so the rows are unknown, not none.
175
+ if (rows === null || rows.length) {
176
+ for (const line of notes.bad_rows) {
177
+ const part = splitRow(line);
178
+ issues.push({
179
+ kind: 'row_template',
180
+ row: part.row ?? part.text,
181
+ text: `### Rows: not "<build> <device> [os]: …": ${line}`,
182
+ });
183
+ }
184
+
185
+ const known = new Set((rows ?? []).map(rowKey));
186
+ for (const r of notes.rows)
187
+ if (!known.has(rowKey(r)))
188
+ issues.push({
189
+ kind: 'row_unknown',
190
+ row: rowKey(r),
191
+ text: `### Rows: ${rowKey(r)} is no row of this card`,
192
+ });
193
+ }
194
+
195
+ const noted = new Set(notes.rows.filter((r) => r.note).map(rowKey));
196
+ for (const r of rows ?? [])
197
+ if (!noted.has(rowKey(r)))
198
+ issues.push({
199
+ kind: 'row_missing',
200
+ row: rowKey(r),
201
+ text: `### Rows: ${rowKey(r)} has no note`,
202
+ });
203
+
204
+ return issues;
205
+ }
206
+
207
+ /**
208
+ * What the section lacks, one issue each with its kind and parts (Round14-Plan d1): the form and
209
+ * what is in it, not its language. A card with no rows (a project without `plays_on`) has no
210
+ * template of rows: its row notes are no warning, the handoff shows them as `unplaced`.
148
211
  * @param {ReturnType<typeof playNotesOf>} notes
149
- * @param {Array<{build: string, device: string, os: string | null}>} rows the card's rows
212
+ * @param {Array<{build: string, device: string, os: string | null}> | null} rows the card's rows;
213
+ * null when the project's play: cannot be read
214
+ * @returns {PlayNotesIssue[]}
150
215
  */
216
+ export function playNotesIssues(notes, rows) {
217
+ if (!notes)
218
+ return [
219
+ {
220
+ kind: 'no_notes',
221
+ text: 'the plan has no ## Play notes: ai-factory gcf play-notes <id> --template',
222
+ },
223
+ ];
224
+ /** @type {PlayNotesIssue[]} */
225
+ const issues = notes.unknown.map((h) => ({
226
+ kind: 'section_unknown',
227
+ section: h,
228
+ text: `## Play notes has no section ### ${h}`,
229
+ }));
230
+ for (const section of ['Question', 'Try'])
231
+ if (!notes[section.toLowerCase()].length)
232
+ issues.push({ kind: 'section_empty', section, text: `### ${section} is empty` });
233
+ issues.push(...rowIssues(notes, rows));
234
+
235
+ return issues;
236
+ }
237
+
238
+ /** The warnings as words: what `submit`, `close` and `play-notes --json` say. */
151
239
  export function playNotesProblems(notes, rows) {
152
- if (!notes) return ['the plan has no ## Play notes: ai-factory gcf play-notes <id> --template'];
153
- const problems = notes.unknown.map((h) => `## Play notes has no section ### ${h}`);
154
- if (!notes.question.length) problems.push('### Question is empty');
155
- if (!notes.try.length) problems.push('### Try is empty');
156
- for (const line of notes.bad_rows)
157
- problems.push(`### Rows: not "<build> <device> [os]: …": ${line}`);
240
+ return playNotesIssues(notes, rows).map((x) => x.text);
241
+ }
242
+
243
+ /**
244
+ * The row notes no row of the card shows (Round14-Plan d2): lines not in the template and notes of
245
+ * rows the card does not have.
246
+ * @returns {Array<{row: string | null, text: string}>}
247
+ */
248
+ export function unplacedOf(notes, rows) {
249
+ if (!notes) return [];
158
250
  const known = new Set(rows.map(rowKey));
159
- for (const r of notes.rows)
160
- if (!known.has(rowKey(r))) problems.push(`### Rows: ${rowKey(r)} is no row of this card`);
161
- const noted = new Set(notes.rows.filter((r) => r.note).map(rowKey));
162
- for (const r of rows)
163
- if (!noted.has(rowKey(r))) problems.push(`### Rows: ${rowKey(r)} has no note`);
164
251
 
165
- return problems;
252
+ return [
253
+ ...notes.bad_rows.map(splitRow),
254
+ ...notes.rows
255
+ .filter((r) => !known.has(rowKey(r)))
256
+ .map((r) => ({ row: rowKey(r), text: r.note })),
257
+ ];
166
258
  }
167
259
 
168
260
  /** The card's notes and their warnings, from its plan in `projectDir` (main or its worktree). */
169
261
  export async function playNotesCheck(projectDir, item) {
170
262
  const dir = path.resolve(projectDir);
171
- /** @type {ReturnType<typeof playOf>} */
172
- let play = null;
263
+ /** @type {ReturnType<typeof rowsFor> | null} */
264
+ let rows = null;
173
265
  try {
174
- play = playOf(await readConfig(path.join(dir, 'gcf')));
266
+ const play = playOf(await readConfig(path.join(dir, 'gcf')));
267
+ // No play: at all: the rows are unknown too, as the handoff reads them.
268
+ rows = play ? rowsFor(play, item.data.play_on) : null;
175
269
  } catch {
176
- // A broken play: is its own command's to report; the rows are unknown then.
270
+ // A broken play: is its own command's to report; the rows are unknown then (null).
177
271
  }
178
272
 
179
273
  const notes = playNotesOf(planTextOf(dir, item));
180
274
 
181
- return { notes, warnings: playNotesProblems(notes, rowsFor(play, item.data.play_on)) };
275
+ return { notes, warnings: playNotesProblems(notes, rows) };
182
276
  }
183
277
 
184
278
  /** The plan's text without `## Play notes`: a move back to `ready` takes it (d3). */
package/lib/play.js CHANGED
@@ -894,8 +894,9 @@ const headHolds = (dir, at) => codeTree(dir, 'HEAD') === codeTree(dir, at);
894
894
  * between a run's cards (docs/Handoff-Plan.md t19).
895
895
  */
896
896
  async function freeOfCheckout(dir, id, item) {
897
- const mode =
898
- item?.data.run_mode ?? (await readConfig(path.join(dir, 'gcf'))).run_mode ?? 'worktree';
897
+ const { cardRunMode } = await import('./integrate.js');
898
+ const project = (await readConfig(path.join(dir, 'gcf'))).run_mode;
899
+ const mode = cardRunMode(dir, id, { own: item?.data.run_mode, project });
899
900
  const at = mode === 'worktree' ? cardCode(dir, id, item) : null;
900
901
 
901
902
  return at !== null && !headHolds(dir, at);
@@ -1214,16 +1215,41 @@ export function stopPlay(projectDir, { id = null } = {}) {
1214
1215
  export const stopPlayLocked = (projectDir) =>
1215
1216
  withMainLock(path.resolve(projectDir), async () => stopPlay(projectDir));
1216
1217
 
1217
- const freePort = () =>
1218
- new Promise((resolve, reject) => {
1218
+ /** `port` (0: any) taken and let go at once: the port, or null when another process holds it. */
1219
+ const listenable = (port) =>
1220
+ new Promise((resolve) => {
1219
1221
  const s = net.createServer();
1220
- s.on('error', reject);
1221
- s.listen(0, '127.0.0.1', () => {
1222
- const { port } = /** @type {net.AddressInfo} */ (s.address());
1223
- s.close(() => resolve(port));
1222
+ s.on('error', () => resolve(null));
1223
+ s.listen(port, '127.0.0.1', () => {
1224
+ const { port: got } = /** @type {net.AddressInfo} */ (s.address());
1225
+ s.close(() => resolve(got));
1224
1226
  });
1225
1227
  });
1226
1228
 
1229
+ const portsFile = (dir) => path.join(session(dir), 'play-ports.json');
1230
+
1231
+ /**
1232
+ * Target `name`'s port: the one it had last while no other process holds it, so a phone's
1233
+ * `adb reverse` of it holds over the starts (a new port each start broke it, 2026-11-12); a free
1234
+ * one else, kept from then on. The player stopped just before may still hold it a moment.
1235
+ */
1236
+ async function portOf(dir, name) {
1237
+ const ports = readJson(portsFile(dir)) ?? {};
1238
+ const last = ports[name];
1239
+ if (Number.isInteger(last))
1240
+ for (let i = 0; i < 10; i++) {
1241
+ if ((await listenable(last)) === last) return last;
1242
+ await new Promise((r) => setTimeout(r, 200));
1243
+ }
1244
+
1245
+ const port = await listenable(0);
1246
+ if (port === null) throw new Error('no free port on 127.0.0.1');
1247
+ // The session folder holds the snapshot it plays: it is there.
1248
+ writeJsonSync(portsFile(dir), { ...ports, [name]: port });
1249
+
1250
+ return port;
1251
+ }
1252
+
1227
1253
  const answers = (port) =>
1228
1254
  new Promise((resolve) => {
1229
1255
  const c = net.connect({ port, host: 'localhost' });
@@ -1449,7 +1475,7 @@ async function startLocked(dir, id, { targetName, target, device, slot }) {
1449
1475
  const key = heldKey(dir, slot);
1450
1476
  const snapshot = snapOf(dir, key);
1451
1477
  stopPlay(dir);
1452
- const port = await freePort();
1478
+ const port = await portOf(dir, targetName);
1453
1479
  const at = { port, lan: lanAddress(), device: device?.id ?? null };
1454
1480
  const inCommand = commandOf(snapshot, at);
1455
1481
  // The device's name is for the eyes only: never in a command.
package/lib/review.js ADDED
@@ -0,0 +1,108 @@
1
+ // `gcf review row` (Operator-Tasks-Plan t2 d2): who makes pass k of an item's plan or code review,
2
+ // from `review.plan|code` of gcf/config.yml (row k, past the end the last), and, for the code,
3
+ // the diff the reviewer reads: from where the card's work started to the disk, new files in,
4
+ // the framework's own files out, the project's `no_diff` named and not shown, cut as Changes cuts.
5
+ import { spawnSync } from 'node:child_process';
6
+ import { mkdirSync, writeFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { cutOf, globTest } from './changes.js';
9
+ import { onWorkBranch } from './commit-move.js';
10
+ import { fallbackOf, gcfRoot, readConfig } from './gcf-paths.js';
11
+ import { buildLedger } from './ledger.js';
12
+ import { KINDS, stallOf } from './plan-check.js';
13
+ import { codeTree, NOT_CODE } from './verify-stamp.js';
14
+
15
+ const git = (dir, args) =>
16
+ spawnSync('git', args, { windowsHide: true, cwd: dir, encoding: 'utf8', maxBuffer: 64 << 20 });
17
+
18
+ const out = (dir, args) => {
19
+ const r = git(dir, args);
20
+
21
+ return r.status === 0 ? r.stdout.trim() : null;
22
+ };
23
+
24
+ /**
25
+ * Row k of the review of `kind` for item `id`: `{row: {agent, model, effort} | null, by, fallback,
26
+ * rows, more, accepted}`; with `diff` (the code's), the diff file the reviewer reads.
27
+ * @param {string} projectDir
28
+ * @param {string} id
29
+ * @param {{kind: string, pass: number, diff?: boolean}} o
30
+ */
31
+ export async function reviewRow(projectDir, id, { kind, pass, diff = false }) {
32
+ if (!KINDS.includes(kind)) throw new Error(`--kind is ${KINDS.join(' | ')}, got ${kind}`);
33
+ if (!Number.isInteger(pass) || pass < 1) throw new Error('--pass is the pass number, 1 or more');
34
+ const item = (await buildLedger(projectDir)).item(id);
35
+ if (!item) throw new Error(`${id} is not a work item of gcf/work/`);
36
+ const config = await readConfig(gcfRoot(projectDir));
37
+ const rows = config.review[kind];
38
+ const row = rows.length ? rows[Math.min(pass, rows.length) - 1] : null;
39
+ const stall = stallOf(item.data, kind) ?? {};
40
+ const withDiff = diff && kind === 'code';
41
+
42
+ return {
43
+ ...{ id, kind, pass, rows: rows.length, row },
44
+ plan: item.data.plan ?? `.ai-factory/plans/${id}.md`,
45
+ more: Number(stall.more ?? 0),
46
+ accepted: Boolean(stall.accepted),
47
+ by: byOf(row),
48
+ // Who makes the pass when its row cannot, in order (Fallback-Fidelity-Plan d2).
49
+ fallback: fallbackOf(row),
50
+ ...(withDiff
51
+ ? { diff: reviewDiff(projectDir, id, { base: stall.base, noDiff: config.no_diff }) }
52
+ : {}),
53
+ };
54
+ }
55
+
56
+ /** A row as a pass's `by`: `agent:model:effort` (t2 d2); null with no row. */
57
+ const byOf = (row) => (row ? `${row.agent}:${row.model}:${row.effort}` : null);
58
+
59
+ /**
60
+ * The base of a card's code review: in its worktree, where its branch left the main checkout;
61
+ * on main, the commit its work started from when a stall kept one, else HEAD (the review comes
62
+ * before the commit, so HEAD to the disk is the work).
63
+ */
64
+ function baseOf(dir, base) {
65
+ if (!onWorkBranch(dir)) return base ?? out(dir, ['rev-parse', 'HEAD']);
66
+ const common = out(dir, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
67
+ const main = common && out(path.dirname(common), ['rev-parse', 'HEAD']);
68
+
69
+ return (main && out(dir, ['merge-base', 'HEAD', main])) ?? out(dir, ['rev-parse', 'HEAD']);
70
+ }
71
+
72
+ /**
73
+ * Write the code's diff for the reviewer to `.gcf-session/review/<id>.diff`: `{file, files,
74
+ * no_diff, cut}`. The disk's code against the base, as `gcf verify` sees it (`codeTree`).
75
+ * @param {string} projectDir
76
+ * @param {string} id
77
+ * @param {{base?: string, noDiff?: string[]}} [o]
78
+ */
79
+ export function reviewDiff(projectDir, id, { base, noDiff = [] } = {}) {
80
+ const dir = path.resolve(projectDir);
81
+ const from = baseOf(dir, base);
82
+ const tree = codeTree(dir);
83
+ if (!from || !tree) throw new Error('the code review needs a git repository with a commit');
84
+ const own = (p) => NOT_CODE.some((d) => p === d || p.startsWith(`${d}/`));
85
+ const hidden = noDiff.map(globTest);
86
+ // NUL-separated: git quotes a name with non-ASCII letters otherwise, and the quoted name
87
+ // matches no path (Codex review of t2).
88
+ const listed = git(dir, ['diff', '--name-only', '-z', from, tree]);
89
+ if (listed.status !== 0) throw new Error(`git diff --name-only: ${listed.stderr.trim()}`);
90
+ const names = listed.stdout.split('\0').filter((p) => p && !own(p));
91
+ const shown = names.filter((p) => !hidden.some((t) => t(p)));
92
+ const unshown = names.filter((p) => !shown.includes(p));
93
+ const diffed = shown.length ? git(dir, ['diff', from, tree, '--', ...shown]) : null;
94
+ if (diffed && diffed.status !== 0) throw new Error(`git diff: ${diffed.stderr.trim()}`);
95
+ const raw = diffed?.stdout ?? '';
96
+ const { text, cut } = cutOf(raw);
97
+ const head = unshown.length ? `# no diff (no_diff): ${unshown.join(', ')}\n` : '';
98
+ const file = path.join(dir, '.gcf-session', 'review', `${id}.diff`);
99
+ mkdirSync(path.dirname(file), { recursive: true });
100
+ writeFileSync(file, `${head}${text}`);
101
+
102
+ return {
103
+ file: path.relative(dir, file).replaceAll('\\', '/'),
104
+ files: shown,
105
+ no_diff: unshown,
106
+ cut,
107
+ };
108
+ }
@@ -123,25 +123,48 @@ function changeProblem(c) {
123
123
 
124
124
  /** A live: delta (Methodology §8): `{none: <why>}` or `{changes: [{id, change, summary}]}`. */
125
125
  /**
126
- * What is wrong with an item's `stall:` (Hold-Plan d16), or null: `{passes, reason?, more?,
127
- * accepted?}`, the blocking counts of each pass, the operator's extra passes or their yes.
126
+ * Whether one review's stall entry holds (Hold-Plan d16, t2 d3): `{passes, reason?, more?,
127
+ * accepted?, base?}`, the blocking counts of each pass, the operator's extra passes or their yes,
128
+ * the commit a code review diffs from.
128
129
  */
129
- function stallProblem(v) {
130
+ function stallEntryOk(v, kind) {
130
131
  const count = (n) => Number.isInteger(n) && n >= 0;
131
- const keys = { passes: (x) => Array.isArray(x) && x.every(count) };
132
132
  const optional = {
133
133
  reason: (x) => typeof x === 'string',
134
134
  more: (x) => count(x) && x >= 1,
135
135
  accepted: (x) => x === true,
136
+ ...(kind === 'code'
137
+ ? { base: (x) => typeof x === 'string' && /^[0-9a-f]{7,40}$/.test(x) }
138
+ : {}),
136
139
  };
140
+
141
+ return (
142
+ v !== null &&
143
+ typeof v === 'object' &&
144
+ !Array.isArray(v) &&
145
+ Array.isArray(v.passes) &&
146
+ v.passes.every(count) &&
147
+ Object.entries(v).every(([k, x]) => k === 'passes' || optional[k]?.(x))
148
+ );
149
+ }
150
+
151
+ /**
152
+ * What is wrong with an item's `stall:`, or null: `{plan?, code?}`, each a review's stall (t2);
153
+ * the form before t2, one entry alone, is the plan's.
154
+ */
155
+ function stallProblem(v) {
156
+ if (stallEntryOk(v, 'plan')) return null;
137
157
  const ok =
138
158
  v !== null &&
139
159
  typeof v === 'object' &&
140
160
  !Array.isArray(v) &&
141
- keys.passes(v.passes) &&
142
- Object.entries(v).every(([k, x]) => k === 'passes' || optional[k]?.(x));
161
+ Object.keys(v).length > 0 &&
162
+ Object.entries(v).every(([k, x]) => (k === 'plan' || k === 'code') && stallEntryOk(x, k));
143
163
 
144
- return ok ? null : 'stall must be {passes: [counts], reason?, more?: n >= 1, accepted?: true}';
164
+ return ok
165
+ ? null
166
+ : 'stall must be {plan?, code?}, each {passes: [counts], reason?, more?: n >= 1, ' +
167
+ 'accepted?: true, base?: <commit> (code)}';
145
168
  }
146
169
 
147
170
  export function liveProblem(v) {
@@ -10,7 +10,7 @@ import path from 'node:path';
10
10
 
11
11
  // Not code: the framework's own files, the plans, the run files. A move or a plan tick there
12
12
  // after the verify does not change what the DoD proved.
13
- const NOT_CODE = ['gcf', '.ai-factory', '.gcf-session'];
13
+ export const NOT_CODE = ['gcf', '.ai-factory', '.gcf-session'];
14
14
 
15
15
  const stampFile = (projectDir, id) =>
16
16
  path.join(path.resolve(projectDir), '.gcf-session', 'runs', `${id}.verified`);