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/audit-core.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
- import { spawnSync } from 'node:child_process';
5
4
  import {
6
5
  listItems,
7
6
  listSystems,
@@ -20,30 +19,24 @@ import { STORED } from './transitions.js';
20
19
  import { openDepends } from './work-ops.js';
21
20
  import { runHolder } from './main-lock.js';
22
21
  import { markOwner, ownerOf, sessionActive } from './session-mark.js';
23
- import { fieldOf } from './question-fields.js';
22
+ import {
23
+ blameLines,
24
+ d2States,
25
+ git,
26
+ PLACEHOLDER_RE,
27
+ UNTIL_RE,
28
+ untilStatus,
29
+ verdictMatchers,
30
+ } from './d2-states.js';
24
31
  import { inboxProblems } from './inbox.js';
25
32
  import { inboxVocabulary } from './domain.js';
26
33
  import { gatePolicy, verdictDeferred } from './gates.js';
27
34
  import { milestoneState } from './milestone-state.js';
28
35
  import { mainWork } from './shelf.js';
36
+ import { cardRunMode, liveCopies } from './integrate.js';
29
37
  import { playOnIssues } from './play-on.js';
30
38
  import { platformsOf } from './playtest-list.js';
31
39
 
32
- function git(args, cwd) {
33
- // A blame of a long file overflows the 1 MiB default, and an overflow reads as a git failure.
34
- const res = spawnSync('git', args, {
35
- windowsHide: true,
36
- cwd,
37
- encoding: 'utf8',
38
- maxBuffer: 64 * 1024 * 1024,
39
- });
40
-
41
- return res.status === 0 ? res.stdout.trim() : null;
42
- }
43
-
44
- const UNTIL_RE = /\[until:\s*(verdict\([a-z0-9-]+\)|retune\([a-z0-9-]+\)|manual\([^)]*\))\]/g;
45
- const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
46
-
47
40
  /**
48
41
  * Whether an item runs, and who works it (`running_by`): `run`, a harness run's live lock; `you`,
49
42
  * a fresh session mark this session or its run owns (`GCF_RUN_OWNER`, else
@@ -78,12 +71,15 @@ function runningOf(projectDir, id) {
78
71
  * @property {string[]} legacy_cards
79
72
  * @property {{tokens: number, budget: number, over: boolean, count: number, too_many: boolean}
80
73
  * | null} pillars
81
- * @property {Array<{file: string, id?: string, trigger: string, status: string}>} until
74
+ * @property {Array<{file: string, id?: string, trigger: string,
75
+ * status: 'stale' | 'open' | 'manual' | 'answered', placeholder?: true}>} until a D2's
76
+ * `answered` once it has an answer: line; `placeholder`, a marker GCF wrote itself
82
77
  * @property {Record<string, object[]>} linter
83
78
  * @property {object[]} pragmas
84
79
  * @property {boolean} index_drift
85
80
  * @property {Array<{id: string, status: string}>} illegal_status
86
- * @property {Array<{id: string, commits: number | null, limit: number}>} stale_questions
81
+ * @property {Array<{id: string, commits: number | null, limit: number}>} stale_questions the
82
+ * unanswered D1 and D2 of `manual(...)` or no trigger past the limit
87
83
  * @property {{errors: string[], warnings: string[]}} play_on cards' build names (lib/play-on.js)
88
84
  * @property {number} [schema]
89
85
  * @property {Array<{id: string, type: string, gate: string, status: string, system: string[],
@@ -94,6 +90,7 @@ function runningOf(projectDir, id) {
94
90
  * orphan_dirs: string[], unmigrated: string[], unknown_category: string[],
95
91
  * unsorted: string[]}} inbox
96
92
  * @property {string | null} [review_migration]
93
+ * @property {boolean} [run_mode_default] run_mode unset while worktree copies live
97
94
  */
98
95
 
99
96
  /**
@@ -104,6 +101,8 @@ function runningOf(projectDir, id) {
104
101
  export async function audit(projectDir) {
105
102
  const root = path.join(path.resolve(projectDir), 'gcf');
106
103
  const config = await readConfig(root);
104
+ const raw = await readRawConfig(root);
105
+ const live = liveCopies(projectDir);
107
106
  const items = await listItems(root);
108
107
  const systems = await listSystems(root);
109
108
  const ledger = await buildLedger(projectDir);
@@ -113,6 +112,11 @@ export async function audit(projectDir) {
113
112
  const unplayed = items.filter(
114
113
  (c) => c.data.status === 'unplayed' && !named.has(c.data.milestone),
115
114
  ).length;
115
+ const fired = verdictMatchers(projectDir, ledger, items);
116
+ const questions = await d2States(projectDir, {
117
+ fired,
118
+ limit: config.question_stale_after_commits,
119
+ });
116
120
  /** @type {AuditReport} */
117
121
  const report = {
118
122
  first_line: '',
@@ -127,25 +131,22 @@ export async function audit(projectDir) {
127
131
  },
128
132
  legacy_cards: legacyCards(root),
129
133
  pillars: await pillarsOf(root, config),
130
- until: untilRecords(
131
- items,
132
- systems,
133
- verdictMatchers(projectDir, ledger, items),
134
- await questionsText(root),
135
- ),
134
+ until: untilRecords(projectDir, { items, systems, fired, questions }),
136
135
  linter: {},
137
136
  pragmas: [],
138
137
  index_drift: await drifted(root),
139
138
  illegal_status: [],
140
- stale_questions: staleQuestions(projectDir, root, config),
139
+ stale_questions: staleQuestions(questions, config),
141
140
  inbox: await inboxProblems(root, inboxVocabulary()),
142
141
  play_on: playOnIssues(items, config, await platformsOf(root)),
143
142
  // A config from before the review rows (Operator-Tasks-Plan t2 d1): the command that moves it.
144
- review_migration: reviewMigration(await readRawConfig(root)),
143
+ review_migration: reviewMigration(raw),
144
+ // run_mode unset while worktree copies live (Fallback-Fidelity-Plan d1): main by default now.
145
+ run_mode_default: (raw.run_mode ?? null) === null && live.size > 0,
145
146
  };
146
147
  // The harness gate reads everything from this one report — it never parses gcf/ itself.
147
148
  Object.assign(report, { schema: config.schema, gates: config.gates });
148
- report.items = items.map((c) => itemRow(projectDir, config, c));
149
+ report.items = items.map((c) => itemRow(projectDir, config, live, c));
149
150
  // The card whose unfinished work lies in the folder (lib/shelf.js): the next claim shelves it.
150
151
  const work = mainWork(projectDir);
151
152
  if (work) report.main_work = work;
@@ -165,7 +166,7 @@ export async function audit(projectDir) {
165
166
  }
166
167
 
167
168
  /** An item as the report lists it for the harness gate. */
168
- function itemRow(projectDir, config, c) {
169
+ function itemRow(projectDir, config, live, c) {
169
170
  return {
170
171
  id: c.data.id,
171
172
  type: c.data.type,
@@ -178,8 +179,13 @@ function itemRow(projectDir, config, c) {
178
179
  parallel: c.data.parallel ?? 'serial',
179
180
  priority: c.data.priority ?? null,
180
181
  milestone: c.data.milestone ?? null,
181
- // Where its run goes: its own run_mode, else the project's (an autopilot batches by it).
182
- run_mode: c.data.run_mode ?? config.run_mode,
182
+ // Where its run goes: its own run_mode, where its kept session ran, worktree while its copy
183
+ // lives, else the project's (an autopilot batches by it).
184
+ run_mode: cardRunMode(projectDir, String(c.data.id), {
185
+ own: c.data.run_mode,
186
+ project: config.run_mode,
187
+ live,
188
+ }),
183
189
  // The gates in force (docs/Autonomy-Plan.md, B); `deferred`: its submit closes unplayed.
184
190
  gates: gatePolicy(config, c.data),
185
191
  deferred: verdictDeferred(config, c.data),
@@ -266,119 +272,58 @@ async function pillarsOf(root, config) {
266
272
  }
267
273
 
268
274
  /**
269
- * Open questions older than the limit, aged by the last commit that changed their `- id:` line
270
- * beyond whitespace (GCF-PRD §7.4): a pile of unanswered ones means the human has dropped out
271
- * of the loop.
275
+ * Open questions the human owes past the limit, aged by the last commit that changed their
276
+ * `- id:` line beyond whitespace (GCF-PRD §7.4): a pile of them means the human has dropped out
277
+ * of the loop. An answered record is not owed; an acting D2 waits for its trigger and a fired
278
+ * one is a stale until record (lib/d2-states.js).
272
279
  */
273
- function staleQuestions(projectDir, root, config) {
274
- if (!existsSync(path.join(root, 'open-questions.md'))) return [];
275
- // null for an untracked file or outside a repository: no commit to age from. -w: a respaced
276
- // or re-ended (CRLF/LF) line keeps the commit that wrote it.
277
- const blame = git(['blame', '-w', '--porcelain', '--', 'gcf/open-questions.md'], projectDir);
278
- if (blame === null) return [];
279
- const added = [];
280
- let hash = '';
281
- for (const line of blame.split('\n')) {
282
- const head = line.match(/^([0-9a-f]{40,64}) \d+ \d+/);
283
- if (head) hash = head[1];
284
- const id = line.match(/^\t\uFEFF?- id:\s*(\S+)/)?.[1];
285
- // An uncommitted line blames to the all-zero hash: it is new, not old.
286
- if (id && !/^0+$/.test(hash)) added.push({ id, hash });
287
- }
288
-
289
- const ages = new Map();
290
- const ageOf = (h) => {
291
- if (!ages.has(h)) {
292
- const raw = git(['rev-list', '--count', `${h}..HEAD`], projectDir);
293
- // Number(null) is 0, "fresh" — the one answer that must never be guessed (see staleEntry).
294
- ages.set(h, raw === null ? null : Number(raw));
295
- }
296
-
297
- return ages.get(h);
298
- };
299
-
300
- const limit = config.question_stale_after_commits;
301
-
302
- return added
303
- .map(({ id, hash: h }) => ({ id, commits: ageOf(h), limit }))
304
- .filter((q) => q.commits === null || q.commits > limit);
305
- }
306
-
307
- /**
308
- * Whether a verdict fired. `verdict(id)` reads the files, as the ledger does (GCF-PRD §5.8): a
309
- * keep or kill left a history or graveyard line, a tune left the item's tune_count — so a
310
- * squash or a shallow clone does not hide it, and a revert takes it back.
311
- */
312
- function verdictMatchers(projectDir, ledger, items) {
313
- const tuned = items.filter((c) => (c.data.tune_count ?? 0) > 0);
314
- const verdictLog =
315
- git(['log', '--basic-regexp', '--grep', '^gcf(verdict):', '--format=%s'], projectDir) ?? '';
316
-
317
- return {
318
- verdict: (id) =>
319
- ledger.where(id).terminal.some((t) => t !== 'done') || tuned.some((c) => c.data.id === id),
320
- // shortcut: a kept item's tunes leave no file behind, so retune(sys) also greps the verdict
321
- // subjects; upgrade when tunes get their own history line.
322
- retune: (system) =>
323
- tuned.some((c) => (c.data.system ?? []).includes(system)) ||
324
- new RegExp(`^gcf\\(verdict\\): tune .*→ (?:.*,)?${escapeRe(system)}(?:,|$)`, 'm').test(
325
- verdictLog,
326
- ),
327
- };
328
- }
329
-
330
- function untilStatus(trigger, fired) {
331
- if (trigger.startsWith('verdict(')) {
332
- return fired.verdict(trigger.slice(8, -1)) ? 'stale' : 'open';
333
- }
334
-
335
- if (trigger.startsWith('retune(')) {
336
- return fired.retune(trigger.slice(7, -1)) ? 'stale' : 'open';
337
- }
338
-
339
- return 'manual';
340
- }
341
-
342
- /** open-questions.md, or '' without one. */
343
- const questionsText = async (root) => {
344
- const file = path.join(root, 'open-questions.md');
345
-
346
- return existsSync(file) ? readFile(file, 'utf8') : '';
347
- };
348
-
349
- const D2_UNTIL_RE = /^(verdict\([a-z0-9-]+\)|retune\([a-z0-9-]+\)|manual\([^)]*\))/;
280
+ const staleQuestions = (questions, config) =>
281
+ questions
282
+ .filter((q) => q.aged)
283
+ .map((q) => ({ id: q.id, commits: q.commits, limit: config.question_stale_after_commits }));
350
284
 
351
285
  /**
352
286
  * Until annotations across work items and systems docs, and the `until:` of each D2 record in
353
- * open-questions.md (`questions` its text): a fired one is an assumption to ask the human again.
287
+ * open-questions.md (`questions` their states): a fired one is an assumption to ask the human
288
+ * again. A retune annotation counts the tunes after the commit that wrote its line; GCF's own
289
+ * markers (PLACEHOLDER_RE) are flagged `placeholder`.
354
290
  */
355
- function untilRecords(items, systems, fired, questions) {
291
+ function untilRecords(projectDir, { items, systems, fired, questions }) {
356
292
  const docs = [
357
- ...items.map((c) => ({ rel: `work/${c.name}`, body: c.body })),
358
- ...systems.map((s) => ({ rel: `systems/${s.name}`, body: s.body })),
293
+ ...items.map((c) => ({ rel: `gcf/work/${c.name}`, body: c.body })),
294
+ ...systems.map((s) => ({ rel: `gcf/systems/${s.name}`, body: s.body })),
359
295
  ];
360
296
  const until = [];
361
297
  for (const doc of docs) {
298
+ const lines = doc.body.split('\n').map((l) => l.replace(/\r$/, ''));
299
+ let blamed;
300
+ // The body is the file's tail, after its frontmatter: line i is blame line offset + i. No
301
+ // blame (an untracked file, no repository) or a line that does not match: no birth, any
302
+ // tune fires it as before.
303
+ const birthOf = (i) => {
304
+ blamed ??= blameLines(projectDir, doc.rel) ?? [];
305
+ const at = blamed.length - (lines.at(-1) === '' ? lines.length - 1 : lines.length) + i;
306
+
307
+ return blamed[at]?.text === lines[i] ? blamed[at].hash : undefined;
308
+ };
309
+
362
310
  // A quoted line (an inbox entry's text in a note:) holds no annotation, as for the gate.
363
- const own = doc.body
364
- .split('\n')
365
- .filter((l) => !l.startsWith('>'))
366
- .join('\n');
367
- for (const m of own.matchAll(UNTIL_RE)) {
368
- until.push({ file: `gcf/${doc.rel}`, trigger: m[1], status: untilStatus(m[1], fired) });
311
+ for (const [i, line] of lines.entries()) {
312
+ if (line.startsWith('>')) continue;
313
+ for (const m of line.matchAll(UNTIL_RE)) {
314
+ const birth = m[1].startsWith('retune(') ? birthOf(i) : undefined;
315
+ until.push({
316
+ file: doc.rel,
317
+ trigger: m[1],
318
+ status: untilStatus(m[1], fired, birth),
319
+ ...(PLACEHOLDER_RE.test(m[0]) && { placeholder: true }),
320
+ });
321
+ }
369
322
  }
370
323
  }
371
324
 
372
- for (const rec of questions.replace(/\r\n/g, '\n').split(/\n(?=- id:)/)) {
373
- const id = rec.match(/^- id:\s*(\S+)/)?.[1];
374
- const trigger = fieldOf(rec, 'until')?.match(D2_UNTIL_RE)?.[1];
375
- if (!id || !trigger || !/^D2\b/.test(fieldOf(rec, 'class') ?? '')) continue;
376
- until.push({
377
- file: 'gcf/open-questions.md',
378
- id,
379
- trigger,
380
- status: untilStatus(trigger, fired),
381
- });
325
+ for (const q of questions.filter((r) => r.trigger)) {
326
+ until.push({ file: 'gcf/open-questions.md', id: q.id, trigger: q.trigger, status: q.status });
382
327
  }
383
328
 
384
329
  return until;
@@ -410,7 +355,7 @@ const itemAlerts = (report) => [
410
355
 
411
356
  /** Alerts about the documents. @param {AuditReport} report */
412
357
  const docAlerts = (report) => [
413
- report.until.filter((u) => u.status === 'stale').length && 'stale until-records present',
358
+ staleUntil(report.until),
414
359
  report.pillars?.over && 'PILLARS over token budget',
415
360
  report.pillars?.too_many && `PILLARS has ${report.pillars.count} pillars (max ${PILLARS_MAX})`,
416
361
  report.stale_questions.length &&
@@ -419,11 +364,28 @@ const docAlerts = (report) => [
419
364
  Object.keys(report.linter).length && 'П2 linter findings in systems docs',
420
365
  report.index_drift && 'INDEX drift (regenerate)',
421
366
  report.design?.blocking && `${report.design.blocking} blocking design finding(s)`,
367
+ ...configAlerts(report),
368
+ ...playOnAlerts(report.play_on),
369
+ ...inboxAlerts(report.inbox),
370
+ ];
371
+
372
+ /** The fired until records, each by its D2's id or its file, for the human to answer. */
373
+ function staleUntil(until) {
374
+ const stale = until.filter((u) => u.status === 'stale');
375
+
376
+ return (
377
+ stale.length &&
378
+ `stale until-records: ${stale.map((u) => `${u.id ?? u.file} ${u.trigger}`).join(', ')}` +
379
+ ' — ask the human'
380
+ );
381
+ }
382
+
383
+ /** Alerts about gcf/config.yml. @param {AuditReport} report */
384
+ const configAlerts = (report) => [
422
385
  report.review_migration &&
423
386
  `plan_passes and plan_review: are gone, review.plan holds the passes: ` +
424
387
  report.review_migration,
425
- ...playOnAlerts(report.play_on),
426
- ...inboxAlerts(report.inbox),
388
+ report.run_mode_default && 'run_mode is main by default now; set worktree to keep parallel runs',
427
389
  ];
428
390
 
429
391
  /** A card's play_on and played_on name builds (docs/Handoff-Plan.md d8). */
package/lib/board.js CHANGED
@@ -5,11 +5,11 @@ import { readFile } from 'node:fs/promises';
5
5
  import { existsSync } from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { buildLedger } from './ledger.js';
8
- import { readConfig } from './gcf-paths.js';
8
+ import { readConfig, REVIEW_FALLBACK } from './gcf-paths.js';
9
9
  import { readLive } from './live.js';
10
10
  import { filesUnder, listInbox } from './inbox.js';
11
11
  import { phaseStatus } from './phase.js';
12
- import { verifiedBranches, worktreeOf } from './integrate.js';
12
+ import { cardRunMode, liveCopies, verifiedBranches, worktreeOf } from './integrate.js';
13
13
  import { resolveInside } from './safe-path.js';
14
14
  import { wipOf } from './audit-core.js';
15
15
  import { MAIN_RUN, lockedItem, runHolder } from './main-lock.js';
@@ -19,6 +19,7 @@ import { domainOf, hasHarness, RUNS_FROM } from './domain.js';
19
19
  import { lessonRepeats } from './inbox-categories.js';
20
20
  import { openDepends } from './work-ops.js';
21
21
  import { listQuestions } from './questions.js';
22
+ import { d2States, questionRow, verdictMatchers } from './d2-states.js';
22
23
  import { sessionActive } from './session-mark.js';
23
24
  import { shelvedCards } from './shelf.js';
24
25
  import { agentOf } from './agent-permissions.js';
@@ -32,7 +33,7 @@ import { handoffOf } from './handoff.js';
32
33
 
33
34
  // The version of the JSON below (Methodology §11): a board refuses one it does not know. Bump it
34
35
  // when a field changes meaning or goes away; a new field does not bump it.
35
- export const BOARD_SCHEMA = 5;
36
+ export const BOARD_SCHEMA = 6;
36
37
 
37
38
  /**
38
39
  * Plan progress `{tasks, done}` from its checkboxes and the plan's project path, both null
@@ -335,7 +336,7 @@ async function handoffPart(projectDir, id, read) {
335
336
  return handoff ? { handoff } : {};
336
337
  }
337
338
 
338
- async function itemOf(projectDir, c, { verified, shelved, ledger, harness, config, links }) {
339
+ async function itemOf(projectDir, c, { verified, shelved, live, ledger, harness, config, links }) {
339
340
  const builds = itemBuilds(projectDir, String(c.data.id), c.data.status, links);
340
341
  const id = String(c.data.id);
341
342
  // A trailer counts only while the item waits on main for its integrate.
@@ -369,6 +370,13 @@ async function itemOf(projectDir, c, { verified, shelved, ledger, harness, confi
369
370
  running_kind: kind,
370
371
  resumable,
371
372
  resume,
373
+ // Where a run that asks no mode takes it (Fallback-Fidelity-Plan d1): its own, where its kept
374
+ // session ran, worktree while its copy lives, the project's.
375
+ runs_in: cardRunMode(projectDir, id, {
376
+ own: c.data.run_mode,
377
+ project: config.run_mode,
378
+ live,
379
+ }),
372
380
  verified: ready,
373
381
  // Its unfinished work waits on its branch (lib/shelf.js); a run brings it back.
374
382
  ...(shelved.has(id) ? { shelved: shelved.get(id) } : {}),
@@ -398,9 +406,12 @@ async function itemsOf(projectDir, { ledger, harness, config }) {
398
406
  const verified = verifiedOf(projectDir);
399
407
  const shelved = shelvedCards(projectDir);
400
408
  const links = linksOf(projectDir);
409
+ const live = liveCopies(projectDir);
401
410
  const items = [];
402
411
  for (const c of ledger.items)
403
- items.push(await itemOf(projectDir, c, { verified, shelved, ledger, harness, config, links }));
412
+ items.push(
413
+ await itemOf(projectDir, c, { verified, shelved, live, ledger, harness, config, links }),
414
+ );
404
415
  inRunOrder(items);
405
416
  // When the wait began: the time of the commit `since` names (Board-PRD §13).
406
417
  const times = commitTimes(
@@ -429,7 +440,16 @@ export async function board(projectDir) {
429
440
  i.needed_by = items.filter((o) => o.depends.includes(i.id)).map((o) => o.id);
430
441
 
431
442
  const live = await readLive(root);
432
- const questions = await listQuestions(root);
443
+ const states = new Map(
444
+ (
445
+ await d2States(projectDir, {
446
+ fired: verdictMatchers(projectDir, ledger, ledger.items),
447
+ limit: config.question_stale_after_commits,
448
+ })
449
+ ).map((s) => [s.id, s]),
450
+ );
451
+ // The class stays in the file; the screen shows the category (§2.7, decision 32).
452
+ const questions = (await listQuestions(root)).map((q) => questionRow(q, states.get(q.id)));
433
453
  const { units, design } = await designOf(projectDir, ledger, questions);
434
454
 
435
455
  return {
@@ -454,6 +474,8 @@ export async function board(projectDir) {
454
474
  chat: config.chat,
455
475
  // The review passes of the plan and the code (Operator-Tasks-Plan t2): the rows that hold.
456
476
  review: config.review,
477
+ // Who makes a pass its row cannot make (Fallback-Fidelity-Plan d2): the rules, as data.
478
+ review_fallback: REVIEW_FALLBACK,
457
479
  // How the game is played: the project's targets and the running player; null when not set up.
458
480
  play: playFacts(projectDir, config),
459
481
  phase: await phaseOf(projectDir),
@@ -468,13 +490,7 @@ export async function board(projectDir) {
468
490
  inbox,
469
491
  // A lesson kind met in 3 runs or more: it rises to Needs you (decision 32).
470
492
  inbox_repeats: lessonRepeats(inbox),
471
- // The class stays in the file; the screen shows the category (§2.7, decision 32). An agent
472
- // writes every question record: its origin is one.
473
- questions: questions.map((q) => ({
474
- ...q,
475
- category: /^D1\b/.test(q.class ?? '') ? 'decision' : 'assumption',
476
- origin: 'agent',
477
- })),
493
+ questions,
478
494
  history: await historyOf(root),
479
495
  graveyard: await graveyardOf(root),
480
496
  units: unitsOf(units),
@@ -167,6 +167,7 @@ function refuseGateRest(dir, names, subject) {
167
167
  rest,
168
168
  `cannot record ${subject} while gcf/ holds uncommitted changes: ${rest.join(', ')} — ` +
169
169
  'commit or discard them, then try again',
170
+ { message: subject, items: names.flatMap((n) => ITEM_PATH.exec(n)?.[1] ?? []) },
170
171
  );
171
172
  }
172
173
 
@@ -93,6 +93,7 @@ async function record(
93
93
  rels.every((r) => all.includes(r)) ? all : [],
94
94
  `commit or stash these first (an answered unit is committed before its move), ` +
95
95
  `${message} would carry them: ${rels.join(', ')}`,
96
+ { message, items },
96
97
  );
97
98
  }
98
99
 
package/lib/config-set.js CHANGED
@@ -331,7 +331,7 @@ function defaultOf(s, aif) {
331
331
  if (head === 'review') return passesText(REVIEW_DEFAULTS[sub]);
332
332
  if (sub) return null;
333
333
 
334
- return head === 'run_mode' ? 'worktree' : (DEFAULT_CONFIG[head] ?? null);
334
+ return head === 'run_mode' ? 'main' : (DEFAULT_CONFIG[head] ?? null);
335
335
  }
336
336
 
337
337
  /**
package/lib/context.js CHANGED
@@ -2,7 +2,9 @@ import { mkdir, readFile, readdir } from 'node:fs/promises';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { listItems, listSystems, readConfig, tokensEst } from './gcf-paths.js';
5
- import { fieldOf } from './question-fields.js';
5
+ import { buildLedger } from './ledger.js';
6
+ import { provenanceOf } from './design.js';
7
+ import { d2States, verdictMatchers } from './d2-states.js';
6
8
  import { atomicWrite } from './safe-path.js';
7
9
  import { ownerOf } from './session-mark.js';
8
10
 
@@ -20,7 +22,7 @@ export async function writeReadset(projectDir, ctx, env = process.env) {
20
22
  /**
21
23
  * Readset assembly — the whole command is deterministic (GCF-PRD §9.1, §10.1):
22
24
  * PILLARS + LIVE.md + touched systems + the item + its parent + its depends + graveyard tag hits +
23
- * D2 assumptions whose sys overlaps. Never over_budget-throws: the caller gates.
25
+ * D2 assumptions whose sys overlaps or the item cites. Never over_budget-throws: the caller gates.
24
26
  */
25
27
  export async function buildContext(projectDir, itemId) {
26
28
  const root = path.join(path.resolve(projectDir), 'gcf');
@@ -34,7 +36,7 @@ export async function buildContext(projectDir, itemId) {
34
36
  const itemText =
35
37
  `${item.data.id} ${item.data.title ?? ''} ${systems.join(' ')} ${item.body}`.toLowerCase();
36
38
  const graveyard_hits = await graveyardHits(root, itemText);
37
- const d2 = await d2Assumptions(root, systems);
39
+ const { d2, fired } = await d2Assumptions(projectDir, config, item, systems);
38
40
 
39
41
  const extraTokens = tokensEst(graveyard_hits.join('\n')) + tokensEst(d2.join('\n'));
40
42
  const total_tokens_est = files.reduce((sum, f) => sum + f.tokens_est, 0) + extraTokens;
@@ -44,6 +46,8 @@ export async function buildContext(projectDir, itemId) {
44
46
  files,
45
47
  graveyard_hits,
46
48
  d2,
49
+ // The ids in d2 whose trigger fired with no answer: the human's call now (GCF-PRD §7.3).
50
+ d2_fired: fired,
47
51
  total_tokens_est,
48
52
  budget: config.context_budget,
49
53
  over_budget: total_tokens_est > config.context_budget,
@@ -111,18 +115,27 @@ async function graveyardHits(root, itemText) {
111
115
  return hits;
112
116
  }
113
117
 
114
- /** D2 assumptions whose sys: overlaps the item's systems (GCF-PRD §9.1). */
115
- async function d2Assumptions(root, systems) {
116
- const oqFile = path.join(root, 'open-questions.md');
117
- if (!existsSync(oqFile)) return [];
118
- const records = (await readFile(oqFile, 'utf8')).split(/\n(?=- id:)/);
119
-
120
- return records
121
- .filter((rec) => /^\s*-?\s*id:/m.test(rec) && /^D2\b/.test(fieldOf(rec, 'class') ?? ''))
122
- .filter((rec) => {
123
- const sys = fieldOf(rec, 'sys') ?? '';
118
+ /**
119
+ * D2 assumptions whose sys: overlaps the item's systems (GCF-PRD §9.1), and the ones the item
120
+ * cites as `assumed: q-NNN` whatever their sys:; `fired`, the unanswered ones whose until: fired.
121
+ */
122
+ async function d2Assumptions(projectDir, config, item, systems) {
123
+ const file = path.join(path.resolve(projectDir), 'gcf', 'open-questions.md');
124
+ const text = existsSync(file) ? await readFile(file, 'utf8') : '';
125
+ // The ledger reads every design doc: built only when a D2 can fire by a verdict.
126
+ if (!/^\s*class:\s*D2\b/m.test(text)) return { d2: [], fired: [] };
127
+ const ledger = /verdict\(/.test(text) ? await buildLedger(projectDir) : null;
128
+ const states = await d2States(projectDir, {
129
+ fired: verdictMatchers(projectDir, ledger, ledger?.items ?? []),
130
+ limit: config.question_stale_after_commits,
131
+ });
132
+ const cited = new Set(provenanceOf(item.body).map((r) => r.assumed));
133
+ const picked = states.filter(
134
+ (q) => q.d2 && (cited.has(q.id) || systems.some((s) => (q.sys ?? '').includes(s))),
135
+ );
124
136
 
125
- return systems.some((s) => sys.includes(s));
126
- })
127
- .map((rec) => rec.trim());
137
+ return {
138
+ d2: picked.map((q) => q.text),
139
+ fired: picked.filter((q) => q.status === 'stale').map((q) => q.id),
140
+ };
128
141
  }