gcf-aif-ext 0.31.0 → 0.34.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/main-lock.js CHANGED
@@ -4,13 +4,28 @@
4
4
  // holds it across the merge and the move it records.
5
5
  import { AsyncLocalStorage } from 'node:async_hooks';
6
6
  import { link, mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';
7
- import { readFileSync } from 'node:fs';
7
+ import {
8
+ existsSync,
9
+ mkdirSync,
10
+ readdirSync,
11
+ readFileSync,
12
+ renameSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ } from 'node:fs';
8
16
  import { randomUUID } from 'node:crypto';
9
17
  import path from 'node:path';
18
+ // Not `process.stdin.isTTY`: reading it opens stdin, which may keep a piped command alive.
19
+ import { isatty } from 'node:tty';
20
+ import { dirtyGcf, moveBy } from './git.js';
21
+ import { refusal } from './refusal.js';
10
22
 
11
23
  const chain = new AsyncLocalStorage();
12
24
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
13
25
 
26
+ /** How often a move waiting behind a main run looks at gcf/, and how long a claim yields to one. */
27
+ export const waitTiming = { pollMs: 1000, yieldMs: 5000 };
28
+
14
29
  export const lockFile = (projectDir) =>
15
30
  path.join(path.resolve(projectDir), '.gcf-session', 'main.lock');
16
31
 
@@ -179,10 +194,187 @@ async function clearStale(file, text) {
179
194
  * @returns {Promise<T>}
180
195
  */
181
196
  export async function withMainLock(projectDir, fn, { waitMs = 60000 } = {}) {
182
- const file = lockFile(projectDir);
183
197
  const held = chain.getStore() ?? new Set();
184
- if (held.has(file)) return fn();
198
+ if (held.has(lockFile(projectDir))) return fn();
199
+ const once = () => holding(projectDir, held, fn, waitMs);
200
+ if (!mayWait()) return once();
201
+
202
+ // The operator's move stopped by a main run's gcf/ edits waits for them, without the lock (the
203
+ // run's own moves need it), then goes again from its first read (docs/Main-Run-Moves-Plan.md).
204
+ const wait = waiter(projectDir);
205
+ try {
206
+ for (;;) {
207
+ try {
208
+ return await once();
209
+ } catch (e) {
210
+ await wait(e);
211
+ }
212
+ }
213
+ } finally {
214
+ wait.end();
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Only the operator waits, from a terminal or a board that knows its move (`GCF_MOVE_TAG`): a
220
+ * session's or a script's command is killed by its caller's timeout, maybe mid-commit.
221
+ */
222
+ const mayWait = () => moveBy() === 'operator' && (isatty(0) || Boolean(process.env.GCF_MOVE_TAG));
223
+
224
+ const TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
225
+
226
+ /**
227
+ * The card a live main run works now; null with none, or when the lock holds the token of a
228
+ * build, a push or a play: their edits are no run's that a commit of it would clear.
229
+ */
230
+ function mainRunCard(projectDir) {
231
+ try {
232
+ const file = path.join(path.resolve(projectDir), '.gcf-session', 'runs', `${MAIN_RUN}.lock`);
233
+ const [pid, item] = readFileSync(file, 'utf8')
234
+ .split('\n')
235
+ .map((s) => s.trim());
236
+ const n = Number(pid);
237
+
238
+ return item && !TOKEN.test(item) && n > 0 && n !== process.pid && alive(n) ? item : null;
239
+ } catch {
240
+ return null;
241
+ }
242
+ }
185
243
 
244
+ const waitingDir = (projectDir) => path.join(path.resolve(projectDir), '.gcf-session', 'waiting');
245
+
246
+ /**
247
+ * The records of moves waiting behind a main run (`.gcf-session/waiting/<pid>.json`), each with
248
+ * its `pid` and `file`. A record whose process died is left over: it is removed, not listed.
249
+ * @returns {Array<{pid: number, file: string, message?: string, items?: string[],
250
+ * tag?: string | null, behind?: string, paths?: string[], cancel?: string, going?: boolean}>}
251
+ */
252
+ export function liveWaiting(projectDir) {
253
+ const dir = waitingDir(projectDir);
254
+ let names;
255
+ try {
256
+ names = readdirSync(dir);
257
+ } catch {
258
+ return [];
259
+ }
260
+
261
+ return names.flatMap((name) => {
262
+ const pid = Number(/^(\d+)\.json$/.exec(name)?.[1]);
263
+ if (!pid) return [];
264
+ const file = path.join(dir, name);
265
+ if (!alive(pid)) {
266
+ rmSync(file, { force: true });
267
+
268
+ return [];
269
+ }
270
+
271
+ try {
272
+ return [{ ...JSON.parse(readFileSync(file, 'utf8')), pid, file }];
273
+ } catch {
274
+ return [];
275
+ }
276
+ });
277
+ }
278
+
279
+ /**
280
+ * The wait of one move: `wait(e)` rethrows a failure that is no main run's `dirty` refusal;
281
+ * else it keeps its record, tells once, and resolves when the refusal's paths are clean. It
282
+ * rethrows the refusal when the run is gone, and refuses on a cancel file. Its record says
283
+ * `going` once the paths cleared and the move goes again. `wait.end()` removes the record and
284
+ * the cancel file, on every way out of the move.
285
+ */
286
+ function waiter(projectDir) {
287
+ const dir = waitingDir(projectDir);
288
+ const record = path.join(dir, `${process.pid}.json`);
289
+ const cancel = process.env.GCF_MOVE_CANCEL || path.join(dir, `${process.pid}.cancel`);
290
+ let told = false;
291
+
292
+ /** @param {any} e */
293
+ const wait = async (e) => {
294
+ const card = e?.refusal?.code === 'dirty' ? mainRunCard(projectDir) : null;
295
+ if (!card) throw e;
296
+ const { paths } = e.refusal;
297
+ const { message = 'the move', items = [] } = e.move ?? {};
298
+ const tag = process.env.GCF_MOVE_TAG || null;
299
+ const keep = (going = false) => {
300
+ // Whole or not at all: a reader never parses half a record.
301
+ writeFileSync(
302
+ `${record}.tmp`,
303
+ JSON.stringify({ message, items, tag, behind: card, paths, cancel, going }),
304
+ );
305
+ renameSync(`${record}.tmp`, record);
306
+ };
307
+
308
+ mkdirSync(dir, { recursive: true });
309
+ if (!told) {
310
+ // A cancel a dead move of this pid left behind is no cancel of this one.
311
+ rmSync(cancel, { force: true });
312
+ }
313
+
314
+ keep();
315
+ if (!told) {
316
+ told = true;
317
+ process.stderr.write(
318
+ `${message} waits: the run of ${card} holds gcf/ edits (${paths.join(', ')}); it goes ` +
319
+ 'when they are committed. Nothing is written while it waits.\n' +
320
+ `gcf-waiting: ${JSON.stringify({ behind: card, paths })}\n`,
321
+ );
322
+ }
323
+
324
+ if (!(await cleared(card, paths, message))) throw e;
325
+ // It goes again: a Cancel from now on comes too late (the board answers "already recorded").
326
+ keep(true);
327
+ };
328
+
329
+ /** True once `paths` are clean, false when the run is gone with them still dirty. */
330
+ const cleared = async (card, paths, message) => {
331
+ // shortcut: one `git status` a second per waiting move, cheap for a few; watch gcf/ when
332
+ // many moves wait at once.
333
+ for (;;) {
334
+ await sleep(waitTiming.pollMs);
335
+ if (existsSync(cancel)) {
336
+ rmSync(cancel, { force: true });
337
+ throw refusal(
338
+ 'cancelled',
339
+ {},
340
+ `${message}: cancelled while it waited behind the run of ${card} — nothing was recorded`,
341
+ );
342
+ }
343
+
344
+ const dirty = new Set(dirtyGcf(projectDir));
345
+ if (!paths.some((p) => dirty.has(p))) return true;
346
+ // Gone with its edits left: they are no run's now, and today's refusal names them.
347
+ if (!mainRunCard(projectDir)) return false;
348
+ }
349
+ };
350
+
351
+ // A cancel that came as it went is no cancel of a later move under the same pid.
352
+ wait.end = () => {
353
+ rmSync(record, { force: true });
354
+ rmSync(cancel, { force: true });
355
+ };
356
+
357
+ return wait;
358
+ }
359
+
360
+ /**
361
+ * A card's claim lets a waiting move go first (docs/Main-Run-Moves-Plan.md d4): after a run's
362
+ * last commit gcf/ is clean, and a claim would soil it again before the move's next look. Only
363
+ * when every waiting move's paths are clean already, and for `waitTiming.yieldMs` at most.
364
+ */
365
+ export async function yieldToWaiting(projectDir) {
366
+ const waits = liveWaiting(projectDir);
367
+ if (!waits.length) return;
368
+ const dirty = new Set(dirtyGcf(projectDir));
369
+ if (waits.some((w) => (w.paths ?? []).some((p) => dirty.has(p)))) return;
370
+ const until = Date.now() + waitTiming.yieldMs;
371
+ while (Date.now() < until && waits.some((w) => existsSync(w.file) && alive(w.pid)))
372
+ await sleep(100);
373
+ }
374
+
375
+ /** Take the main lock, run `fn` under it, let it go. */
376
+ async function holding(projectDir, held, fn, waitMs) {
377
+ const file = lockFile(projectDir);
186
378
  await mkdir(path.dirname(file), { recursive: true });
187
379
  const token = randomUUID();
188
380
  const until = Date.now() + waitMs;
package/lib/plan-check.js CHANGED
@@ -10,13 +10,17 @@ 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, REVIEW_DEFAULTS } from './gcf-paths.js';
13
+ import { modelFamily, readConfig, REVIEW_DEFAULTS } from './gcf-paths.js';
14
14
 
15
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 `.`.
18
- const PASS_LINE =
19
- /^- pass (\d+)(?: \(cycle (\d+)\))?: blocking (\d+), polish (\d+)(?:, by ([\w.:-]+))?$/;
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
+ );
20
24
  const SECTION = { plan: /^## Passes\s*$/, code: /^## Reviews\s*$/ };
21
25
  const HEADING = { plan: '## Passes', code: '## Reviews' };
22
26
  const PASSES_ANY = /^## Passes\s*$/m;
@@ -32,7 +36,7 @@ export function planPasses(text, kind = 'plan') {
32
36
  if (/^## /.test(line)) inside = SECTION[kind].test(line);
33
37
  const m = inside ? PASS_LINE.exec(line.trim()) : null;
34
38
  if (!m) continue;
35
- const by = m[5] ? { by: m[5] } : {};
39
+ const by = m[5] ? { by: m[5], ...(m[6] ? { for: m[6] } : {}) } : {};
36
40
  out.push({ pass: +m[1], cycle: +(m[2] ?? 0), blocking: +m[3], polish: +m[4], ...by });
37
41
  }
38
42
 
@@ -180,13 +184,15 @@ export async function planCheck(projectDir, id) {
180
184
  /**
181
185
  * `gcf plan pass` (Hold-Plan d12, t2 d3): record pass K of the current cycle in the plan's
182
186
  * section of `kind` (`## Passes`, the code's `## Reviews`), K the next number, and answer the
183
- * verdict on the cycle's passes so far.
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).
184
189
  * @param {string} projectDir
185
190
  * @param {string} id
186
- * @param {{blocking: number, polish: number, by?: string, kind?: string}} pass
191
+ * @param {{blocking: number, polish: number, by?: string, for?: string, kind?: string}} pass
187
192
  */
188
- export async function recordPass(projectDir, id, { blocking, polish, by, kind = 'plan' }) {
189
- 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);
190
196
  if (!KINDS.includes(kind)) throw new Error(`--kind is ${KINDS.join(' | ')}, got ${kind}`);
191
197
  const item = (await buildLedger(projectDir)).item(id);
192
198
  if (!item) throw new Error(`${id} is not a work item of gcf/work/`);
@@ -197,7 +203,7 @@ export async function recordPass(projectDir, id, { blocking, polish, by, kind =
197
203
  const cycle = Number(item.data.plan_cycle ?? 0);
198
204
  const k = planPasses(text, kind).filter((x) => x.cycle === cycle).length + 1;
199
205
  const tag = cycle ? ` (cycle ${cycle})` : '';
200
- const line = `- pass ${k}${tag}: blocking ${blocking}, polish ${polish}${by ? `, by ${by}` : ''}`;
206
+ const line = `- pass ${k}${tag}: blocking ${blocking}, polish ${polish}${whoOf(by, pass.for)}`;
201
207
  writeFileSync(file, withPass(text, line, kind));
202
208
  const r = await planCheck(projectDir, id);
203
209
  const now = kind === 'plan' ? { passes: r.passes, verdict: '' } : r.review;
@@ -213,12 +219,28 @@ export async function recordPass(projectDir, id, { blocking, polish, by, kind =
213
219
  return { id, kind, pass: k, cycle, verdict, passes: now.passes.map((x) => x.blocking) };
214
220
  }
215
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 '';
232
+
233
+ return row && rowKey(by) !== rowKey(row) ? `, by ${by}, for ${row}` : `, by ${by}`;
234
+ }
235
+
216
236
  /** The refusal of a pass's counts and reviewer, if any. */
217
- function passArgs(blocking, polish, by) {
237
+ function passArgs(blocking, polish, by, row) {
218
238
  for (const [k, v] of Object.entries({ blocking, polish }))
219
239
  if (!Number.isInteger(v) || v < 0) throw new Error(`--${k} is a count of findings, 0 or more`);
220
240
  if (by !== undefined && !/^[\w.-]+(:[\w.-]+){0,2}$/.test(by))
221
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');
222
244
  }
223
245
 
224
246
  /** The plan with `line` at the end of its section of `kind`, the section added when none. */
package/lib/play.js CHANGED
@@ -17,7 +17,7 @@ import { configDoc } from './config-doc.js';
17
17
  import { readConfig } from './gcf-paths.js';
18
18
  import { isValidId } from './id.js';
19
19
  import { buildLedger } from './ledger.js';
20
- import { alive, claimMainRun, MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
20
+ import { alive, claimMainRun, locked, MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
21
21
  import { atomicWrite, renameRetrying } from './safe-path.js';
22
22
  import { commitMove } from './commit-move.js';
23
23
  import { commandEnv } from './shell-env.js';
@@ -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);
@@ -1847,25 +1848,26 @@ export async function setupPlay(projectDir, opts) {
1847
1848
  const o = { ...rest, words };
1848
1849
  needSetup(dir, o);
1849
1850
  const file = path.join(dir, 'gcf', 'config.yml');
1850
- const was = existsSync(file) ? readFileSync(file, 'utf8') : '';
1851
- const doc = playDoc(was, o);
1852
- // The same setup again (an agent proposed what is there): nothing to write, nothing to commit.
1853
- const same =
1854
- JSON.stringify(configDoc(was).toJS()?.play ?? null) === JSON.stringify(doc.toJS().play);
1855
- const hash = same
1856
- ? null
1857
- : await commitMove(dir, 'gcf(config): play', {
1858
- files: [file],
1859
- commit,
1860
- key: 'config',
1861
- mutate: async () => {
1862
- // Read again under the lock: a move meanwhile may have changed the file.
1863
- const now = existsSync(file) ? readFileSync(file, 'utf8') : '';
1864
- const next = playDoc(now, o);
1865
- playOf(next.toJS());
1866
- await atomicWrite(file, next.toString());
1867
- },
1868
- });
1851
+ // Under the lock from the first read: a move that waited behind a main run reads again.
1852
+ const hash = await locked(dir, commit, async () => {
1853
+ const was = existsSync(file) ? readFileSync(file, 'utf8') : '';
1854
+ const doc = playDoc(was, o);
1855
+ // The same setup again (an agent proposed what is there): nothing to write, nothing to commit.
1856
+ const same =
1857
+ JSON.stringify(configDoc(was).toJS()?.play ?? null) === JSON.stringify(doc.toJS().play);
1858
+
1859
+ return same
1860
+ ? null
1861
+ : commitMove(dir, 'gcf(config): play', {
1862
+ files: [file],
1863
+ commit,
1864
+ key: 'config',
1865
+ mutate: async () => {
1866
+ playOf(doc.toJS());
1867
+ await atomicWrite(file, doc.toString());
1868
+ },
1869
+ });
1870
+ });
1869
1871
 
1870
1872
  return { hash, play: playOf(await readConfig(path.join(dir, 'gcf'))) };
1871
1873
  }
package/lib/review.js CHANGED
@@ -7,7 +7,7 @@ import { mkdirSync, writeFileSync } from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { cutOf, globTest } from './changes.js';
9
9
  import { onWorkBranch } from './commit-move.js';
10
- import { gcfRoot, readConfig } from './gcf-paths.js';
10
+ import { fallbackOf, gcfRoot, readConfig } from './gcf-paths.js';
11
11
  import { buildLedger } from './ledger.js';
12
12
  import { KINDS, stallOf } from './plan-check.js';
13
13
  import { codeTree, NOT_CODE } from './verify-stamp.js';
@@ -22,8 +22,8 @@ const out = (dir, args) => {
22
22
  };
23
23
 
24
24
  /**
25
- * Row k of the review of `kind` for item `id`: `{row: {agent, model, effort} | null, by, rows,
26
- * more, accepted}`; with `diff` (the code's), the diff file the reviewer reads.
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
27
  * @param {string} projectDir
28
28
  * @param {string} id
29
29
  * @param {{kind: string, pass: number, diff?: boolean}} o
@@ -45,6 +45,8 @@ export async function reviewRow(projectDir, id, { kind, pass, diff = false }) {
45
45
  more: Number(stall.more ?? 0),
46
46
  accepted: Boolean(stall.accepted),
47
47
  by: byOf(row),
48
+ // Who makes the pass when its row cannot, in order (Fallback-Fidelity-Plan d2).
49
+ fallback: fallbackOf(row),
48
50
  ...(withDiff
49
51
  ? { diff: reviewDiff(projectDir, id, { base: stall.base, noDiff: config.no_diff }) }
50
52
  : {}),
@@ -9,7 +9,7 @@ import { existsSync, readdirSync, readFileSync, rmSync, statSync, utimesSync } f
9
9
  import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
10
10
  import { spawnSync } from 'node:child_process';
11
11
  import path from 'node:path';
12
- import { alive, withMainLock } from './main-lock.js';
12
+ import { alive, withMainLock, yieldToWaiting } from './main-lock.js';
13
13
  import { enterFolder } from './shelf.js';
14
14
 
15
15
  // A run's default timeout: an agent can implement for long without a gcf command. The harness
@@ -87,6 +87,7 @@ export async function claimSession(projectDir, id, owner = ownerOf(), opts = {})
87
87
  const file = markOf(projectDir, id);
88
88
  await excludeSession(projectDir);
89
89
  await mkdir(path.dirname(file), { recursive: true });
90
+ await yieldToWaiting(projectDir);
90
91
 
91
92
  // Under the main lock: two sessions claiming at once must not both pass the check.
92
93
  return withMainLock(projectDir, async () => {
@@ -4,8 +4,10 @@ import { readFile } from 'node:fs/promises';
4
4
  import { existsSync } from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { parseBlocks, itemsOf } from 'cnlp-kit';
7
- import { parse } from './frontmatter.js';
8
- import { scalarIn } from './design.js';
7
+ import { parse, serialize } from './frontmatter.js';
8
+ import { blockOrder, scalarIn } from './design.js';
9
+ import { atomicWrite } from './safe-path.js';
10
+ import { PLACEHOLDER_RE } from './d2-states.js';
9
11
 
10
12
  const NONE_LINE = '- none: no item of this subsystem has collapsed yet';
11
13
 
@@ -81,9 +83,9 @@ export function putBlock(lines, specs, spec, { rendered, raw = false }) {
81
83
 
82
84
  /**
83
85
  * Append `addLines` to the `key:` bullet block of a body, skipping lines already there. A
84
- * `- none: …` placeholder gives way: CNL-P reads it as the whole content or not at all. The
85
- * block stands where `order` (the profile's block keys, see blockOrder) puts it: M1 refuses
86
- * any other place.
86
+ * `- none: …` placeholder, or a GCF marker line, gives way: CNL-P reads it as the whole content
87
+ * or not at all. The block stands where `order` (the profile's block keys, see blockOrder) puts
88
+ * it: M1 refuses any other place.
87
89
  */
88
90
  export function upsertBlock(rawBody, key, addLines, order) {
89
91
  // A CRLF checkout: `\r` before each `\n` would stop the block match at its first line and
@@ -91,8 +93,11 @@ export function upsertBlock(rawBody, key, addLines, order) {
91
93
  const body = lf(rawBody);
92
94
  const existing = blockLines(body, key);
93
95
  const fresh = addLines.filter((l) => !existing.includes(l));
94
- if (!fresh.length) return body;
95
- const kept = existing.filter((l) => !/^- none\b/.test(l));
96
+ // GCF's own manual() markers (d2-states.js) stand in for content too; a human's manual() stays.
97
+ // An old merge left one beside the very lines merged again: content arriving takes it out.
98
+ const marked = addLines.length > 0 && existing.some((l) => PLACEHOLDER_RE.test(l));
99
+ if (!fresh.length && !marked) return body;
100
+ const kept = existing.filter((l) => !/^- none\b/.test(l) && !PLACEHOLDER_RE.test(l));
96
101
  // A key the profile does not know goes last, after every block it does.
97
102
  const specs = (order.includes(key) ? order : [...order, key]).map((k) => ({ key: k }));
98
103
  const lead = /** @type {RegExpMatchArray} */ (body.match(/^\n*/))[0];
@@ -178,17 +183,59 @@ export function removeLines(rawBody, key, dropLines) {
178
183
 
179
184
  const lf = (text) => String(text).replace(/\r\n/g, '\n');
180
185
 
181
- /** Purpose lines a new systems doc starts with: design/<sys>.md's `purpose:`, or a marker. */
182
- async function purposeLines(root, system) {
186
+ const markerOf = (system) => `[until: manual(purpose of ${system})]`;
187
+
188
+ const designOf = async (root, system) => {
183
189
  const file = path.join(root, 'design', `${system}.md`);
184
- const text = existsSync(file) ? lf(await readFile(file, 'utf8')) : '';
185
- const pre = text.split(/^## /m)[0];
190
+
191
+ return existsSync(file) ? lf(await readFile(file, 'utf8')) : '';
192
+ };
193
+
194
+ /** The purpose lines of a design text (design/<sys>.md, or a bundle's system part); none: TBD. */
195
+ function purposeIn(text) {
196
+ const pre = lf(text).split(/^## /m)[0];
186
197
  const bullets = blockLines(pre, 'purpose').filter((l) => !/^- (TBD|none\b)/.test(l));
187
198
  if (bullets.length) return bullets;
188
199
  const scalar = scalarIn(pre, 'purpose');
189
- if (scalar && scalar !== 'TBD') return [`- ${scalar}`];
190
200
 
191
- return [`- the purpose of ${system} is not written yet [until: manual(purpose of ${system})]`];
201
+ return scalar && scalar !== 'TBD' ? [`- ${scalar}`] : [];
202
+ }
203
+
204
+ /** Purpose lines a new systems doc starts with: design/<sys>.md's `purpose:`, or a marker. */
205
+ async function purposeLines(root, system) {
206
+ const lines = purposeIn(await designOf(root, system));
207
+
208
+ return lines.length
209
+ ? lines
210
+ : [`- the purpose of ${system} is not written yet ${markerOf(system)}`];
211
+ }
212
+
213
+ /**
214
+ * systems/<system>.md when it holds GCF's purpose marker and `design` (design/<system>.md's
215
+ * text, or what a move is about to write there) has a purpose; else null. Only then does a move
216
+ * stage the doc: a doc it leaves alone would refuse the move for edits of its own.
217
+ * @param {string} root
218
+ * @param {string} system
219
+ * @param {string} [design]
220
+ */
221
+ export async function purposeTarget(root, system, design) {
222
+ const file = path.join(root, 'systems', `${system}.md`);
223
+ if (!existsSync(file) || !purposeIn(design ?? (await designOf(root, system))).length) return null;
224
+ const { body } = parse(lf(await readFile(file, 'utf8')));
225
+
226
+ return blockLines(body, 'purpose').some((l) => l.includes(markerOf(system))) ? file : null;
227
+ }
228
+
229
+ /** The purpose marker of systems/<system>.md replaced by design/'s purpose; never starts a doc. */
230
+ export async function fillPurpose(root, system) {
231
+ const design = await designOf(root, system);
232
+ const file = await purposeTarget(root, system, design);
233
+ if (!file) return null;
234
+ const { data, body } = parse(lf(await readFile(file, 'utf8')));
235
+ const order = await blockOrder('system');
236
+ await atomicWrite(file, serialize(data, upsertBlock(body, 'purpose', purposeIn(design), order)));
237
+
238
+ return file;
192
239
  }
193
240
 
194
241
  /**
package/lib/work-ops.js CHANGED
@@ -1019,7 +1019,7 @@ async function keepPack(projectDir, name) {
1019
1019
  }
1020
1020
 
1021
1021
  /** Refuse a milestone keep that would carry changes of gcf/ or the plans but the pack's own. */
1022
- function refuseLoose(projectDir, name, own) {
1022
+ function refuseLoose(projectDir, name, own, order) {
1023
1023
  const loose = changedIn(projectDir).filter((c) => !own.has(c.file));
1024
1024
  if (loose.length) {
1025
1025
  // The board's Commit clears only gcf/'s edits: a loose plan gets the words alone.
@@ -1028,6 +1028,7 @@ function refuseLoose(projectDir, name, own) {
1028
1028
  loose.every((c) => all.includes(c.file)) ? all : [],
1029
1029
  `commit or stash these first, keep --milestone ${name} would carry them: ` +
1030
1030
  loose.map((c) => c.file).join(', '),
1031
+ { message: `gcf(verdict): keep ${name}`, items: order },
1031
1032
  );
1032
1033
  }
1033
1034
  }
@@ -1086,7 +1087,7 @@ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
1086
1087
  const pack = await keepPack(projectDir, name);
1087
1088
  const order = keepOrder(pack);
1088
1089
  const own = new Set(pack.map((i) => path.relative(projectDir, i.file).replaceAll('\\', '/')));
1089
- refuseLoose(projectDir, name, own);
1090
+ refuseLoose(projectDir, name, own, order);
1090
1091
  refuseKeepBusy(projectDir, name, commit);
1091
1092
 
1092
1093
  const saved = pack.map((i) => [i.file, readFileSync(i.file)]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-aif-ext",
3
- "version": "0.31.0",
3
+ "version": "0.34.0",
4
4
  "description": "Game Context Framework for AI Factory",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -19,11 +19,16 @@ workflow:
19
19
  1. run `ai-factory gcf audit --json` and read the report
20
20
  2. state the first line verbatim: items waiting too long block dependent work, so they lead
21
21
  3. for each stale until record: name the file, the trigger that fired and the line to re-check; for each entry of `stale_questions`: name the question id and ask the human for the answer
22
- 4. for a stale until record of `gcf/open-questions.md`: the D2 assumption its `id` names expired - ask the human to confirm it, then cite `answer: <id>` and remove the record, or to replace the value
23
- 5. read the `design` summary: blocking findings first (run `ai-factory gcf design check` for the list), then the count of ready units
24
- 6. semantic pass, only when the mechanical report is clean or the human asks: read the systems docs of ONE subsystem the human names and report pairs of lines that contradict each other as D1 questions
25
- 7. list the pragmas: each `gcf:allow` is a standing exception, and a growing list is the linter rotting
26
- 8. propose the next actions, ranked, proposed actions <= 3: playtest, answer a D1, take a ready unit, or collapse a stale record
22
+ 4. for a stale until record of `gcf/open-questions.md`: the D2 assumption its `id` names fired - propose the answer in chat, to confirm the value or replace it; a fired D2 is not re-filed as a D1
23
+ 5. the human answers it: the board's Overrule, or `ai-factory gcf question answer <id> --text="<answer>"`; do not answer it yourself
24
+ 6. only after the record carries the human's `answer:`: write it into each slot that cites `assumed: <id>`, cite `answer: <id>` there, then remove the record
25
+ 7. an unplayed item keeps its `assumed: <id>`, as its body is frozen: the answered record stays while an unplayed item cites it, and leaves after that item's verdict
26
+ 8. a stale until annotation in `gcf/systems/` or `gcf/work/` becomes a D1; on the human's go-ahead file it with `ai-factory gcf question add --class D1 --question "<the line> - still true?" --proposed "<its value>" --sys <s>`
27
+ 9. list the `manual(...)` until records, the `placeholder` ones aside: GCF closes its own placeholders
28
+ 10. read the `design` summary: blocking findings first (run `ai-factory gcf design check` for the list), then the count of ready units
29
+ 11. semantic pass, only when the mechanical report is clean or the human asks: read the systems docs of ONE subsystem the human names and report pairs of lines that contradict each other as D1 questions
30
+ 12. list the pragmas: each `gcf:allow` is a standing exception, and a growing list is the linter rotting
31
+ 13. propose the next actions, ranked, proposed actions <= 3: playtest, answer a D1, take a ready unit, or collapse a stale record
27
32
 
28
33
  invocation:
29
34
  - run at session start, after a long break, or on demand
@@ -29,7 +29,8 @@ forbidden_behaviors:
29
29
  - do not reuse an id: an ended id stays ended; rework gets a new id with `reopens: <old id>`
30
30
  - do not put an id in `depends` for order alone: `depends` names an item whose data or code this one uses, and order goes in `priority`
31
31
  - do not remove an answered D1 record while a unit in its `blocks:` lacks the answer, or names a receiver you cannot tell: it stays
32
- - do not remove a D2 record cited as `assumed: q-NNN`: it stays in `gcf/open-questions.md` until its `until:` fires; when the human confirms the value earlier, rewrite each citation to `answer: q-NNN` first
32
+ - do not remove a D2 record without the human's `answer:`, nor before each citation `assumed: q-NNN` outside an unplayed item reads `answer: q-NNN`
33
+ - do not touch an unplayed item's `assumed: q-NNN`: its body is frozen; the answered record stays while an unplayed item cites it, and leaves after that item's verdict
33
34
 
34
35
  outputs:
35
36
  - each answered slot gets a provenance record `- slot: <block>` with `answer: manual`, or `answer: q-NNN` when it closes a question
@@ -53,15 +54,16 @@ workflow:
53
54
  11. when no pillar fits, ask whether the unit is out of scope or a pillar is missing, and write a D1 question for the answer
54
55
  12. write each answer into the unit in place, with its `answer:` provenance record
55
56
  13. a record of `gcf/open-questions.md` with the human's `answer:` that names this unit in `blocks:` goes into the slot of every unit it blocks, each with `answer: q-NNN`; it leaves the file after the last of them has it
56
- 14. run `ai-factory gcf design check --json` until the unit's entry in `units` reads `ready: true`, then commit the answered unit
57
- 15. run `ai-factory gcf take <id>`, or `take <id> <id> --feature <feature-id>` to group units; a unit without its milestone takes `--milestone <name>` from `gcf/game.md`; it writes `gcf/work/<id>.md`
58
- 16. in each mechanic or resource item write `contract:` from the code tree and `interactions:` from the units and items that write the same state
59
- 17. write the item's `live:` delta (a feature's children keep `none: parent`; the feature writes the capability), run `ai-factory gcf design check`, and commit
60
- 18. when the work is several items (a feature's children, or a batch), cut them along subsystem boundaries: each a thin slice that builds and tests alone
61
- 19. two items of one subsystem that change different files get `parallel: ok`, and their `contract:` or `intent:` names those files
62
- 20. set each item's dependencies with `ai-factory gcf depends <id> --add <ids>`: it commits the item's edits too, and a feature's child never depends on its feature
63
- 21. rank the items with `ai-factory gcf prioritize <id> <id> …`: dependencies first, then by value
64
- 22. report the item paths, each item's gate, and for a verdict item the one question the playtest will answer
57
+ 14. a D2 record with the human's `answer:` overrules its `assumed:`: write it into each slot that cites `assumed: q-NNN`, cite `answer: q-NNN` there, then remove the record, the unplayed items aside
58
+ 15. run `ai-factory gcf design check --json` until the unit's entry in `units` reads `ready: true`, then commit the answered unit
59
+ 16. run `ai-factory gcf take <id>`, or `take <id> <id> --feature <feature-id>` to group units; a unit without its milestone takes `--milestone <name>` from `gcf/game.md`; it writes `gcf/work/<id>.md`
60
+ 17. in each mechanic or resource item write `contract:` from the code tree and `interactions:` from the units and items that write the same state
61
+ 18. write the item's `live:` delta (a feature's children keep `none: parent`; the feature writes the capability), run `ai-factory gcf design check`, and commit
62
+ 19. when the work is several items (a feature's children, or a batch), cut them along subsystem boundaries: each a thin slice that builds and tests alone
63
+ 20. two items of one subsystem that change different files get `parallel: ok`, and their `contract:` or `intent:` names those files
64
+ 21. set each item's dependencies with `ai-factory gcf depends <id> --add <ids>`: it commits the item's edits too, and a feature's child never depends on its feature
65
+ 22. rank the items with `ai-factory gcf prioritize <id> <id> …`: dependencies first, then by value
66
+ 23. report the item paths, each item's gate, and for a verdict item the one question the playtest will answer
65
67
 
66
68
  invocation:
67
69
  - run when work starts on a unit or a group of units, when non-design work needs an item, or when a fresh idea needs a home