gcf-aif-ext 0.29.2 → 0.31.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/domain.js CHANGED
@@ -212,11 +212,12 @@ const ITEM_SPECS = {
212
212
  },
213
213
  ],
214
214
  },
215
- // Planning that does not converge (Hold-Plan d16): the run's stall, the operator's two answers.
215
+ // A review that does not converge (Hold-Plan d16, Operator-Tasks-Plan t2): the plan's or the
216
+ // code's; the run's stall, the operator's two answers, which take the kind the card stands on.
216
217
  plan_stall: {
217
- label: 'planning stall',
218
- help: "The run's stop: the plan's passes keep finding blocking issues past plan_passes",
219
- args: ['gcf', 'plan', 'stall', '{id}'],
218
+ label: 'review stall',
219
+ help: "The run's stop: the review's rows are over and a pass still finds blocking issues",
220
+ args: ['gcf', 'review', 'stall', '{id}'],
220
221
  fields: [
221
222
  { key: 'passes', label: 'Blocking findings of each pass', kind: 'text', required: true },
222
223
  { key: 'reason', label: 'Reason', kind: 'longtext' },
@@ -224,8 +225,10 @@ const ITEM_SPECS = {
224
225
  },
225
226
  plan_more: {
226
227
  label: 'more passes',
227
- help: 'The plan improves N more passes, then the same check decides',
228
- args: ['gcf', 'plan', 'more', '{id}'],
228
+ help:
229
+ 'The plan or the code gets N more review passes on the last row, then the same check ' +
230
+ 'decides',
231
+ args: ['gcf', 'review', 'more', '{id}'],
229
232
  fields: [
230
233
  {
231
234
  key: 'passes',
@@ -238,9 +241,11 @@ const ITEM_SPECS = {
238
241
  ],
239
242
  },
240
243
  plan_accept: {
241
- label: 'implement as is',
242
- help: 'The plan goes to implementation as it is, its open findings with it',
243
- args: ['gcf', 'plan', 'accept', '{id}'],
244
+ label: 'go on as is',
245
+ help:
246
+ 'The plan goes to implementation, or the code to its submit, as it is, its open ' +
247
+ 'findings with it',
248
+ args: ['gcf', 'review', 'accept', '{id}'],
244
249
  fields: [],
245
250
  },
246
251
  mode: {
@@ -1014,9 +1019,9 @@ const CHANGES = [
1014
1019
  'block',
1015
1020
  'unblock',
1016
1021
  'plan pass',
1017
- 'plan stall',
1018
- 'plan more',
1019
- 'plan accept',
1022
+ 'review stall',
1023
+ 'review more',
1024
+ 'review accept',
1020
1025
  'inbox add',
1021
1026
  'inbox category',
1022
1027
  'inbox later',
package/lib/gcf-paths.js CHANGED
@@ -14,7 +14,6 @@ export const DEFAULT_CONFIG = {
14
14
  pillars_budget: 1500,
15
15
  envelope_default_spread: 0.3,
16
16
  unplayed_warn_after: 5,
17
- plan_passes: 3,
18
17
  dod_attempts: 2,
19
18
  // Minutes a dod.test or dod.build command may take before it is killed (0: no limit).
20
19
  dod_timeout_min: 60,
@@ -110,6 +109,73 @@ function gatesOf(v = {}) {
110
109
  );
111
110
  }
112
111
 
112
+ // The review passes of a plan and of the code (Operator-Tasks-Plan t2 d1): row k makes pass k,
113
+ // the next goes only while the last found something blocking; the rows over, the operator
114
+ // decides. An empty list: no review of that kind.
115
+ export const REVIEW_AGENTS = ['claude', 'codex'];
116
+ export const REVIEW_DEFAULTS = {
117
+ plan: [
118
+ { agent: 'claude', model: 'opus', effort: 'high' },
119
+ { agent: 'claude', model: 'opus', effort: 'high' },
120
+ { agent: 'codex', model: 'astra', effort: 'medium' },
121
+ ],
122
+ code: [
123
+ { agent: 'claude', model: 'opus', effort: 'high' },
124
+ { agent: 'claude', model: 'opus', effort: 'high' },
125
+ ],
126
+ };
127
+
128
+ /** A review row's refusal, if any: three plain words, the agent one GCF runs. */
129
+ export function reviewRowProblem(r) {
130
+ if (typeof r !== 'object' || r === null || Array.isArray(r))
131
+ return 'a row is {agent, model, effort}';
132
+ if (!REVIEW_AGENTS.includes(r.agent))
133
+ return `agent must be ${REVIEW_AGENTS.join(' | ')}, got ${r.agent}`;
134
+ for (const k of ['model', 'effort'])
135
+ if (typeof r[k] !== 'string' || !RUN_WORD.test(r[k])) return `${k} must be one plain word`;
136
+
137
+ return null;
138
+ }
139
+
140
+ /**
141
+ * The one command that moves a config from before t2 (`plan_passes`, `plan_review:`) to
142
+ * `review.plan` (t2 d1), or null: `plan_passes N` gives N Claude rows, the pass `plan_review.at`
143
+ * the outside reviewer's (Codex unless `agent: none`). `config set review.*` drops the old keys.
144
+ * @param {Record<string, any>} raw config.yml as the file has it
145
+ */
146
+ export function reviewMigration(raw) {
147
+ const old = raw?.plan_review;
148
+ if (raw?.plan_passes === undefined && old === undefined) return null;
149
+ const n = Number.isInteger(raw.plan_passes) ? raw.plan_passes : 3;
150
+ const at = Number(old?.at ?? 3);
151
+ const codex = (old?.agent ?? 'codex') === 'codex';
152
+ const rows = Array.from({ length: n }, (_, k) =>
153
+ codex && k + 1 === at
154
+ ? `codex:${old?.model ?? 'astra'}:${old?.effort ?? 'medium'}`
155
+ : 'claude:opus:high',
156
+ );
157
+
158
+ return `ai-factory gcf config set review.plan --value "${rows.join(', ') || 'none'}"`;
159
+ }
160
+
161
+ function reviewOf(v = {}) {
162
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
163
+ throw new Error('gcf/config.yml: review must map plan and code to their rows');
164
+ const out = {};
165
+ for (const kind of ['plan', 'code']) {
166
+ const rows = v[kind] ?? REVIEW_DEFAULTS[kind];
167
+ if (!Array.isArray(rows))
168
+ throw new Error(`gcf/config.yml: review.${kind} must be a list of rows`);
169
+ rows.forEach((r, n) => {
170
+ const why = reviewRowProblem(r);
171
+ if (why) throw new Error(`gcf/config.yml: review.${kind} row ${n + 1}: ${why}`);
172
+ });
173
+ out[kind] = rows.map(({ agent, model, effort }) => ({ agent, model, effort }));
174
+ }
175
+
176
+ return out;
177
+ }
178
+
113
179
  // Files listed and never opened on the board's Changes screen (Board-PRD §5.25): the project's
114
180
  // call, GCF names no stack's files.
115
181
  function noDiffOf(v = []) {
@@ -179,6 +245,7 @@ export function configOf(parsed) {
179
245
  chat: chatOf(config.chat),
180
246
  gates: gatesOf(config.gates),
181
247
  no_diff: noDiffOf(config.no_diff),
248
+ review: reviewOf(config.review),
182
249
  };
183
250
  }
184
251
 
package/lib/handoff.js CHANGED
@@ -11,7 +11,7 @@ import { planPasses, planTicks } from './plan-check.js';
11
11
  import { listQuestions } from './questions.js';
12
12
  import { recordsOf } from './verdict-fs.js';
13
13
  import { serves } from './devices.js';
14
- import { planTextOf, playNotesOf, playNotesProblems, rowsFor } from './play-notes.js';
14
+ import { planTextOf, playNotesIssues, playNotesOf, rowsFor, unplacedOf } from './play-notes.js';
15
15
 
16
16
  /** A row's state without asking devices: what is set up and built (the panel asks the rest). */
17
17
  function rowOf(play, build, ok, row) {
@@ -208,15 +208,20 @@ function playedBlocks(c) {
208
208
  };
209
209
  }
210
210
 
211
- /** What the handoff lacks: the agent's notes, the card's criterion. */
212
- function warningsOf(c, question) {
213
- const warnings = c.decision
214
- ? []
215
- : playNotesProblems(c.notes, rowsFor(c.play, c.item.data.play_on));
211
+ /**
212
+ * What the handoff lacks (the agent's notes, the card's criterion), each with its kind and parts
213
+ * (Round14-Plan d1); `warnings` keeps their words for the CLI and an older board.
214
+ * @returns {import('./play-notes.js').PlayNotesIssue[]}
215
+ */
216
+ function issuesOf(c, question) {
217
+ const issues = c.decision ? [] : playNotesIssues(c.notes, rowsOf(c));
216
218
  if (!question.has_criterion)
217
- warnings.push("the card has no miss criterion: the question is the agent's");
219
+ issues.push({
220
+ kind: 'no_criterion',
221
+ text: "the card has no miss criterion: the question is the agent's",
222
+ });
218
223
 
219
- return warnings;
224
+ return issues;
220
225
  }
221
226
 
222
227
  /** A row of block 2 as words, and the command the board has a button for. */
@@ -234,6 +239,9 @@ function rowLines(id, build, r) {
234
239
 
235
240
  const list = (head, items) => (items?.length ? [head, ...items.map((x) => ` - ${x}`)] : []);
236
241
 
242
+ /** The card's rows; null with no readable `play:`: unknown, not none (Round14-Plan d1). */
243
+ const rowsOf = (c) => (c.play ? rowsFor(c.play, c.item.data.play_on) : null);
244
+
237
245
  /** The outcome line (block 0). */
238
246
  function outcomeLine(o) {
239
247
  const b = o.build;
@@ -278,6 +286,10 @@ export function handoffLines(id, h) {
278
286
  h.waits.map((w) => (w.kind === 'question' ? `${w.id}: ${w.text}` : w.text)),
279
287
  ),
280
288
  ...technicalLine(h.technical),
289
+ ...list(
290
+ 'notes on no row:',
291
+ (h.unplaced ?? []).map((n) => (n.row ? `${n.row}: ${n.text}` : n.text)),
292
+ ),
281
293
  ...list('warnings:', h.warnings),
282
294
  ];
283
295
  }
@@ -308,6 +320,7 @@ export async function handoffOf(projectDir, id, { ledger = null, config = null,
308
320
  };
309
321
  c.build = ownBuild(c.play, item, c.builds);
310
322
  const question = questionOf(item, c.notes, decision);
323
+ const warned = issuesOf(c, question);
311
324
 
312
325
  return {
313
326
  outcome: outcomeOf(item, c.build, queueOf(dir)),
@@ -316,6 +329,8 @@ export async function handoffOf(projectDir, id, { ledger = null, config = null,
316
329
  ...playedBlocks(c),
317
330
  waits: await waitsOf(dir, id),
318
331
  technical: technicalOf(c),
319
- warnings: warningsOf(c, question),
332
+ warnings: warned.map((x) => x.text),
333
+ warned,
334
+ unplaced: decision ? [] : unplacedOf(c.notes, rowsOf(c) ?? []),
320
335
  };
321
336
  }
package/lib/plan-check.js CHANGED
@@ -10,21 +10,26 @@ 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 { 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`.
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>]`, one line each in its section: the plan's `## Passes`, the
17
+ // code's `## Reviews`, written by `gcf plan pass`. `by` may name a slug with `-` and `.`.
17
18
  const PASS_LINE =
18
- /^- pass (\d+)(?: \(cycle (\d+)\))?: blocking (\d+), polish (\d+)(?:, by (\w+))?$/;
19
- const PASSES = /^## Passes\s*$/;
19
+ /^- pass (\d+)(?: \(cycle (\d+)\))?: blocking (\d+), polish (\d+)(?:, by ([\w.:-]+))?$/;
20
+ const SECTION = { plan: /^## Passes\s*$/, code: /^## Reviews\s*$/ };
21
+ const HEADING = { plan: '## Passes', code: '## Reviews' };
20
22
  const PASSES_ANY = /^## Passes\s*$/m;
21
23
 
22
- /** The passes a plan's `## Passes` section records, of every cycle, in order. */
23
- export function planPasses(text) {
24
+ /** The review kinds: the plan's passes, the code's before its commit. */
25
+ export const KINDS = ['plan', 'code'];
26
+
27
+ /** The passes a plan's section of `kind` records, of every cycle, in order. */
28
+ export function planPasses(text, kind = 'plan') {
24
29
  const out = [];
25
30
  let inside = false;
26
31
  for (const line of text.split(/\r?\n/)) {
27
- if (/^## /.test(line)) inside = PASSES.test(line);
32
+ if (/^## /.test(line)) inside = SECTION[kind].test(line);
28
33
  const m = inside ? PASS_LINE.exec(line.trim()) : null;
29
34
  if (!m) continue;
30
35
  const by = m[5] ? { by: m[5] } : {};
@@ -35,41 +40,58 @@ export function planPasses(text) {
35
40
  }
36
41
 
37
42
  /**
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.
43
+ * The verdict on one cycle's passes (t2 d3): `converged` when the last found nothing blocking
44
+ * (or no row reviews); `continue` while a row is left for the next pass (the operator's `more`
45
+ * adds them); `stalled` when the rows are over, then the operator decides.
41
46
  */
42
- export function passVerdict(passes, planPasses, more = 0) {
43
- if (planPasses === 0) return 'converged';
47
+ export function passVerdict(passes, rows, more = 0) {
48
+ if (rows === 0) return 'converged';
44
49
  const last = passes.at(-1);
45
50
  if (!last) return 'continue';
46
51
  if (last.blocking === 0) return 'converged';
47
52
 
48
- return passes.length > planPasses + more ? 'stalled' : 'continue';
53
+ return passes.length < rows + more ? 'continue' : 'stalled';
49
54
  }
50
55
 
51
56
  /**
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.
57
+ * A card's stall of `kind` (t2 d3): `stall.plan` or `stall.code`; the form before t2
58
+ * (`{passes, …}` alone) is the plan's.
56
59
  */
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;
60
+ export function stallOf(data, kind) {
61
+ const stall = data?.stall;
62
+ if (!stall || typeof stall !== 'object') return null;
63
+ if (Array.isArray(stall.passes)) return kind === 'plan' ? stall : null;
64
+
65
+ return stall[kind] ?? null;
66
+ }
67
+
68
+ /** The review rows of `kind` the project sets (or the defaults); a broken config: the defaults. */
69
+ async function rowsOf(projectDir, kind) {
62
70
  try {
63
- limit = Number((await readConfig(path.join(path.resolve(projectDir), 'gcf'))).plan_passes);
71
+ return (await readConfig(path.join(path.resolve(projectDir), 'gcf'))).review[kind];
64
72
  } catch {
65
- // A broken config.yml: the default limit; the config's own check says what is wrong.
73
+ // A broken config.yml: the default rows; the config's own check says what is wrong.
74
+ return REVIEW_DEFAULTS[kind];
66
75
  }
76
+ }
67
77
 
68
- const legacy = data.plan_cycle === undefined && !PASSES_ANY.test(text) && done > 0;
78
+ /**
79
+ * Where the item's review of `kind` stands: the passes of its current cycle (`plan_cycle`), and
80
+ * the verdict on them. The operator's `accepted` converges it; a plan written before passes were
81
+ * recorded (no `plan_cycle`, no `## Passes`, a task ticked) counts as converged: work in flight
82
+ * does not stop at an upgrade.
83
+ */
84
+ async function passesOf(projectDir, data, { text, done, kind = 'plan' }) {
85
+ const cycle = Number(data.plan_cycle ?? 0);
86
+ const passes = planPasses(text, kind).filter((x) => x.cycle === cycle);
87
+ const stall = stallOf(data, kind);
88
+ const rows = (await rowsOf(projectDir, kind)).length;
89
+ const legacy =
90
+ kind === 'plan' && data.plan_cycle === undefined && !PASSES_ANY.test(text) && done > 0;
69
91
  const verdict =
70
- stall?.accepted || legacy ? 'converged' : passVerdict(passes, limit, Number(stall?.more ?? 0));
92
+ stall?.accepted || legacy ? 'converged' : passVerdict(passes, rows, Number(stall?.more ?? 0));
71
93
 
72
- return { cycle, passes, verdict };
94
+ return { cycle, passes, verdict, rows };
73
95
  }
74
96
 
75
97
  /**
@@ -144,23 +166,28 @@ export async function planCheck(projectDir, id) {
144
166
  problems.push(`readset ~${ctx.total_tokens_est} tokens is over the budget ${ctx.budget}`);
145
167
  const text = found === null ? '' : readFileSync(path.resolve(projectDir, plan), 'utf8');
146
168
  const format = found === null ? [] : await planFormat(projectDir, text);
147
- const { cycle, passes, verdict } = await passesOf(projectDir, item.data, text, done);
169
+ const { cycle, passes, verdict } = await passesOf(projectDir, item.data, { text, done });
170
+ const code = await passesOf(projectDir, item.data, { text, done, kind: 'code' });
148
171
 
149
172
  return {
150
173
  ...{ id, plan, tasks, done, problems, format, ok: problems.length === 0 },
151
174
  ...{ cycle, passes, converged: verdict === 'converged', stalled: verdict === 'stalled' },
175
+ // The code's review passes (t2 d3): the same verdict over `## Reviews`.
176
+ review: { passes: code.passes, verdict: code.verdict, rows: code.rows },
152
177
  };
153
178
  }
154
179
 
155
180
  /**
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.
181
+ * `gcf plan pass` (Hold-Plan d12, t2 d3): record pass K of the current cycle in the plan's
182
+ * section of `kind` (`## Passes`, the code's `## Reviews`), K the next number, and answer the
183
+ * verdict on the cycle's passes so far.
158
184
  * @param {string} projectDir
159
185
  * @param {string} id
160
- * @param {{blocking: number, polish: number, by?: string}} pass
186
+ * @param {{blocking: number, polish: number, by?: string, kind?: string}} pass
161
187
  */
162
- export async function recordPass(projectDir, id, { blocking, polish, by }) {
188
+ export async function recordPass(projectDir, id, { blocking, polish, by, kind = 'plan' }) {
163
189
  passArgs(blocking, polish, by);
190
+ if (!KINDS.includes(kind)) throw new Error(`--kind is ${KINDS.join(' | ')}, got ${kind}`);
164
191
  const item = (await buildLedger(projectDir)).item(id);
165
192
  if (!item) throw new Error(`${id} is not a work item of gcf/work/`);
166
193
  const { plan } = planTicks(projectDir, { ...item.data, id });
@@ -168,29 +195,39 @@ export async function recordPass(projectDir, id, { blocking, polish, by }) {
168
195
  if (!existsSync(file)) throw new Error(`no plan at ${plan}: write it first`);
169
196
  const text = readFileSync(file, 'utf8');
170
197
  const cycle = Number(item.data.plan_cycle ?? 0);
171
- const k = planPasses(text).filter((x) => x.cycle === cycle).length + 1;
198
+ const k = planPasses(text, kind).filter((x) => x.cycle === cycle).length + 1;
172
199
  const tag = cycle ? ` (cycle ${cycle})` : '';
173
200
  const line = `- pass ${k}${tag}: blocking ${blocking}, polish ${polish}${by ? `, by ${by}` : ''}`;
174
- writeFileSync(file, withPass(text, line));
201
+ writeFileSync(file, withPass(text, line, kind));
175
202
  const r = await planCheck(projectDir, id);
176
- const verdict = r.converged ? 'converged' : r.stalled ? 'stalled' : 'continue';
177
-
178
- return { id, pass: k, cycle, verdict, passes: r.passes.map((x) => x.blocking) };
203
+ const now = kind === 'plan' ? { passes: r.passes, verdict: '' } : r.review;
204
+ const verdict =
205
+ kind === 'plan'
206
+ ? r.converged
207
+ ? 'converged'
208
+ : r.stalled
209
+ ? 'stalled'
210
+ : 'continue'
211
+ : now.verdict;
212
+
213
+ return { id, kind, pass: k, cycle, verdict, passes: now.passes.map((x) => x.blocking) };
179
214
  }
180
215
 
181
216
  /** The refusal of a pass's counts and reviewer, if any. */
182
217
  function passArgs(blocking, polish, by) {
183
218
  for (const [k, v] of Object.entries({ blocking, polish }))
184
219
  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');
220
+ if (by !== undefined && !/^[\w.-]+(:[\w.-]+){0,2}$/.test(by))
221
+ throw new Error('--by is the reviewer: agent:model:effort, or one word');
186
222
  }
187
223
 
188
- /** The plan with `line` at the end of its `## Passes` section, the section added when none. */
189
- function withPass(text, line) {
224
+ /** The plan with `line` at the end of its section of `kind`, the section added when none. */
225
+ function withPass(text, line, kind) {
190
226
  const eol = text.includes('\r\n') ? '\r\n' : '\n';
191
227
  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}`;
228
+ const at = lines.findIndex((l) => SECTION[kind].test(l));
229
+ if (at < 0)
230
+ return `${text.replace(/\s*$/, '')}${eol}${eol}${HEADING[kind]}${eol}${eol}${line}${eol}`;
194
231
  let end = lines.findIndex((l, n) => n > at && /^## /.test(l));
195
232
  if (end < 0) end = lines.length;
196
233
  // 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
@@ -1214,16 +1214,41 @@ export function stopPlay(projectDir, { id = null } = {}) {
1214
1214
  export const stopPlayLocked = (projectDir) =>
1215
1215
  withMainLock(path.resolve(projectDir), async () => stopPlay(projectDir));
1216
1216
 
1217
- const freePort = () =>
1218
- new Promise((resolve, reject) => {
1217
+ /** `port` (0: any) taken and let go at once: the port, or null when another process holds it. */
1218
+ const listenable = (port) =>
1219
+ new Promise((resolve) => {
1219
1220
  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));
1221
+ s.on('error', () => resolve(null));
1222
+ s.listen(port, '127.0.0.1', () => {
1223
+ const { port: got } = /** @type {net.AddressInfo} */ (s.address());
1224
+ s.close(() => resolve(got));
1224
1225
  });
1225
1226
  });
1226
1227
 
1228
+ const portsFile = (dir) => path.join(session(dir), 'play-ports.json');
1229
+
1230
+ /**
1231
+ * Target `name`'s port: the one it had last while no other process holds it, so a phone's
1232
+ * `adb reverse` of it holds over the starts (a new port each start broke it, 2026-11-12); a free
1233
+ * one else, kept from then on. The player stopped just before may still hold it a moment.
1234
+ */
1235
+ async function portOf(dir, name) {
1236
+ const ports = readJson(portsFile(dir)) ?? {};
1237
+ const last = ports[name];
1238
+ if (Number.isInteger(last))
1239
+ for (let i = 0; i < 10; i++) {
1240
+ if ((await listenable(last)) === last) return last;
1241
+ await new Promise((r) => setTimeout(r, 200));
1242
+ }
1243
+
1244
+ const port = await listenable(0);
1245
+ if (port === null) throw new Error('no free port on 127.0.0.1');
1246
+ // The session folder holds the snapshot it plays: it is there.
1247
+ writeJsonSync(portsFile(dir), { ...ports, [name]: port });
1248
+
1249
+ return port;
1250
+ }
1251
+
1227
1252
  const answers = (port) =>
1228
1253
  new Promise((resolve) => {
1229
1254
  const c = net.connect({ port, host: 'localhost' });
@@ -1449,7 +1474,7 @@ async function startLocked(dir, id, { targetName, target, device, slot }) {
1449
1474
  const key = heldKey(dir, slot);
1450
1475
  const snapshot = snapOf(dir, key);
1451
1476
  stopPlay(dir);
1452
- const port = await freePort();
1477
+ const port = await portOf(dir, targetName);
1453
1478
  const at = { port, lan: lanAddress(), device: device?.id ?? null };
1454
1479
  const inCommand = commandOf(snapshot, at);
1455
1480
  // The device's name is for the eyes only: never in a command.