gcf-aif-ext 0.32.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/README.md CHANGED
@@ -50,6 +50,24 @@ Updating preserves `gcf/`, `cnlp.config.json` and the pre-commit hook. Run `ai-f
50
50
 
51
51
  On Windows, run `extension add` and `extension update` from PowerShell or cmd, not Git Bash: the installer unpacks with `tar`, and Git Bash's GNU tar reads `C:\…` as a remote host (`Cannot connect to C: resolve failed`). The Windows `tar.exe` handles it.
52
52
 
53
+ ### 0.34.0
54
+
55
+ Update together with gcf-board 0.34.0 and gcf-harness-aif-ext 0.33.0 ([Until-Records-Plan](https://github.com/VirtualMaestro/GCF/blob/main/docs/Until-Records-Plan.md)). Then run `ai-factory gcf init`: the `AGENTS.md` block changed (a session starts with `ai-factory gcf audit` and states its first line; a fired D2 goes to the human, who answers on the record itself). If the audit then reports inbox entries from before the categories, run `ai-factory gcf inbox migrate` once.
56
+
57
+ - **A fired assumption reaches the operator.** A D2 whose `until:` fired and has no `answer:` is a stale until record the audit's first line names (`stale until-records: q-019 retune(input) — ask the human`); an answered one is `answered`, never stale. `gcf board --json` gives such a D2 `category: decision` with `fired: true`, and a D2 of `manual(...)` or no trigger left unanswered past `question_stale_after_commits` (20) `category: decision` with `aged: true` and `commits`: the board shows both among the decisions. The human answers on the record (`gcf question answer q-NNN`, or Overrule on the board), never as a new D1; the agent then writes the answer into each slot citing `assumed: q-NNN` and drops the record, except while an unplayed item cites it.
58
+ - **`retune(<sys>)` counts only the tunes after the record.** It fires on a tune verdict of the subsystem after the commit that wrote the D2 (or the annotation's own line); a tune before it no longer makes a new record stale at birth, an uncommitted record is `open`, and a record outside git keeps the old rule: it fires once an item of the subsystem was tuned, or on any tune in the log.
59
+ - `stale_questions` keeps what the human still owes: unanswered D1, and unanswered D2 of `manual(...)` or no trigger past the limit; answered records and live `verdict()`/`retune()` ones are out.
60
+ - **GCF's own placeholders close by themselves.** `[until: manual(purpose of <s>)]` and `[until: manual(first verdict touching <s>)]` go when content arrives (`verdict keep`, `done --constraint`); writing a subsystem's purpose (`design save --kind system`, an import, a design commit) puts it in place of the marker in an existing `systems/<s>.md` in the same commit. Old markers in a project go at the next keep or design save of that subsystem. A marker left is listed in `audit --json` with `placeholder: true`, never in the first line or on the board. A human's own `manual()` stays.
61
+ - The readset takes a D2 an item cites as `assumed:` whatever its `sys:`, and lists `d2_fired`; plain `gcf context` prints each D2 record whole, `[fired: <trigger>]` on a fired one.
62
+
63
+ ### 0.33.0
64
+
65
+ Update together with gcf-board 0.33.0 and gcf-harness-aif-ext 0.32.0 ([Main-Run-Moves-Plan](https://github.com/VirtualMaestro/GCF/blob/main/docs/Main-Run-Moves-Plan.md)). Then run `ai-factory gcf init`: the `AGENTS.md` block changed.
66
+
67
+ - **An operator's move waits behind a card's main run instead of a refusal.** A move from a terminal (stdin is a tty) or from a board that passes `GCF_MOVE_TAG`, refused as `dirty` while a card's main run holds the checkout, waits without the main lock: it says `<move> waits: the run of <card> holds gcf/ edits (…)` and a `gcf-waiting: {"behind","paths"}` line on stderr, keeps `.gcf-session/waiting/<pid>.json`, looks once a second, and goes again from its first read once the refusal's paths are clean. Nothing is written while it waits. When the run ends with the paths still dirty (your own `gcf/` edits), it gets today's refusal. Ctrl-C, or the file `.gcf-session/waiting/<pid>.cancel` (`GCF_MOVE_CANCEL` names another), cancels it: nothing recorded.
68
+ - Sessions, threads, runs, a script's move without a tty or `GCF_MOVE_TAG`, and builds, push and play do not wait: refused as before. A card's claim yields up to 5 s to a waiting move about to go.
69
+ - With an older board (no `GCF_MOVE_TAG`) a move from the board is refused as before.
70
+
53
71
  ### 0.32.0
54
72
 
55
73
  Update together with gcf-board 0.32.0 (`gcf board --json` is `schema: 6`; each refuses the other's old schema) and gcf-harness-aif-ext 0.31.0 ([Fallback-Fidelity-Plan](https://github.com/VirtualMaestro/GCF/blob/main/docs/Fallback-Fidelity-Plan.md)). Then run `ai-factory gcf init`: the `AGENTS.md` block changed.
@@ -331,7 +349,7 @@ Update together with gcf-harness-aif-ext 0.12.0 and gcf-board 0.6.0 (docs/Sessio
331
349
 
332
350
  - `gcf init` restamps an unplayed item frozen by 0.4.0 (the hash of its body alone), so its `live:` is guarded too — only while that `live:` is still the one its close committed. Commit the restamped items it names.
333
351
  - While a harness run drives an item (`.gcf-session/runs/<id>.lock` held by a live process), the core refuses any move on it, `/gcf-run` on main included, and `gcf integrate` leaves its branch unmerged; the audit and the board read it as `running`. A lock left by a run that died is taken over. `gcf board --json` reports WIP as `{count, limit, over}`.
334
- - The audit reads the `until:` of every D2 record in `open-questions.md`: a fired one is a stale until record, and the assumption goes back to the human.
352
+ - The audit reads the `until:` of every D2 record in `open-questions.md`: a fired one is a stale until record, and the assumption goes back to the human (0.34.0 refines this, see there).
335
353
  - `gcf design check` reads the text of an HTML comment in a unit or an item for forbidden words (M4) and numbers (M5); a `gcf:allow` pragma and a tool's marked region are skipped.
336
354
  - An unplayed tune or kill keeps a systems-doc line the doc held before the item's close.
337
355
  - `gcf playtest session` groups the checklist by subsystem and warns when the build is not of main: the remote's default branch when the clone knows it, else any branch but a detached HEAD or a `work/` one.
package/commands/gcf.js CHANGED
@@ -324,6 +324,7 @@ function registerContext(gcf) {
324
324
  .action(async (itemId, opts) => {
325
325
  await touchSession(itemId);
326
326
  const { buildContext, writeReadset } = await lib('context');
327
+ const { fieldOf } = await lib('question-fields');
327
328
  const ctx = await buildContext(process.cwd(), itemId);
328
329
  if (opts.readset) await writeReadset(process.cwd(), ctx);
329
330
  // Metric 1 (GCF-PRD §14): readset size over time, one csv line per call.
@@ -339,6 +340,15 @@ function registerContext(gcf) {
339
340
  [
340
341
  ...c.files.map((f) => `${f.path} (${f.tokens_est})`),
341
342
  ...(c.graveyard_hits.length ? ['graveyard hits:', ...c.graveyard_hits] : []),
343
+ // Whole records: a plan written without a run reads the value and the answer here.
344
+ ...(c.d2.length ? ['D2 assumptions:'] : []),
345
+ ...c.d2.map((rec) => {
346
+ const id = rec.match(/^- id:\s*(\S+)/)?.[1];
347
+
348
+ const mark = ` [fired: ${fieldOf(rec, 'until')}]`;
349
+
350
+ return c.d2_fired.includes(id) ? rec.replace(/^.*/, (l) => l + mark) : rec;
351
+ }),
342
352
  `total ~${c.total_tokens_est} / ${c.budget}${c.over_budget ? ' OVER BUDGET' : ''}`,
343
353
  ].join('\n'),
344
354
  );
@@ -1767,33 +1777,44 @@ function registerDecide(gcf) {
1767
1777
  }
1768
1778
 
1769
1779
  /**
1770
- * An inbox move (`plan`: its files, the ones that may carry edits not yet committed, and how to
1771
- * make it); with `commit`, committed alone under the main lock — a board has no console to
1772
- * commit from. Entries added before without a commit ride along with it. Returns the commit
1773
- * hash, or null.
1780
+ * An inbox move (`make` builds its plan: its files, the ones that may carry edits not yet
1781
+ * committed, and how to make it); with `commit`, committed alone under the main lock — a board
1782
+ * has no console to commit from. Entries added before without a commit ride along with it.
1783
+ * Returns the commit hash, or null, and the plan it made.
1784
+ * @template {{files: string[], inputs?: string[], apply: () => Promise<unknown>}} P
1774
1785
  * @param {boolean | undefined} commit
1775
1786
  * @param {string} message
1776
- * @param {{files: string[], inputs?: string[], apply: () => Promise<unknown>}} plan
1787
+ * @param {() => P | Promise<P>} make
1777
1788
  * @param {string} key the domain's move key, for the commit's trailer
1789
+ * @returns {Promise<{hash: string | null, plan: P}>}
1778
1790
  */
1779
- async function inboxMove(commit, message, plan, key) {
1791
+ async function inboxMove(commit, message, make, key) {
1780
1792
  if (!commit) {
1793
+ const plan = await make();
1781
1794
  await plan.apply();
1782
1795
 
1783
- return null;
1796
+ return { hash: null, plan };
1784
1797
  }
1785
1798
 
1786
1799
  const { commitMove } = await lib('commit-move');
1787
- const loose = (await lib('inbox')).untrackedEntries(process.cwd());
1788
-
1789
- return commitMove(process.cwd(), message, {
1790
- files: [...plan.files, ...loose],
1791
- inputs: [...(plan.inputs ?? plan.files), ...loose],
1792
- mutate: async () => {
1793
- await plan.apply();
1794
- },
1795
- commit: true,
1796
- key,
1800
+ const { untrackedEntries } = await lib('inbox');
1801
+
1802
+ // Read under the lock: a move that waited behind a main run plans again from what is there
1803
+ // now, the entries and pictures added meanwhile included.
1804
+ return (await lib('main-lock')).withMainLock(process.cwd(), async () => {
1805
+ const plan = await make();
1806
+ const loose = untrackedEntries(process.cwd());
1807
+ const hash = await commitMove(process.cwd(), message, {
1808
+ files: [...plan.files, ...loose],
1809
+ inputs: [...(plan.inputs ?? plan.files), ...loose],
1810
+ mutate: async () => {
1811
+ await plan.apply();
1812
+ },
1813
+ commit: true,
1814
+ key,
1815
+ });
1816
+
1817
+ return { hash, plan };
1797
1818
  });
1798
1819
  }
1799
1820
 
@@ -1825,12 +1846,13 @@ function registerInboxSort(inbox) {
1825
1846
  await refuseOnWork('sort an entry');
1826
1847
  const { planCategory } = await lib('inbox');
1827
1848
  const { gcfRoot } = await lib('gcf-paths');
1828
- const plan = await planCategory(gcfRoot(), id, {
1829
- category: o.category,
1830
- detail: o.detail,
1831
- vocab: await vocabulary(),
1832
- });
1833
- const hash = await inboxMove(o.commit, `gcf(inbox): sort ${id}`, plan, 'inbox-category');
1849
+ const vocab = await vocabulary();
1850
+ const { hash, plan } = await inboxMove(
1851
+ o.commit,
1852
+ `gcf(inbox): sort ${id}`,
1853
+ () => planCategory(gcfRoot(), id, { category: o.category, detail: o.detail, vocab }),
1854
+ 'inbox-category',
1855
+ );
1834
1856
  const { category, detail } = plan.entry;
1835
1857
  console.log(`${id} is ${category}${detail ? `:${detail}` : ''}${shortHash(hash)}`);
1836
1858
  });
@@ -1843,9 +1865,14 @@ function registerInboxSort(inbox) {
1843
1865
  await refuseOnWork('put an entry away');
1844
1866
  const { planLater } = await lib('inbox');
1845
1867
  const { gcfRoot } = await lib('gcf-paths');
1846
- const plan = await planLater(gcfRoot(), id, !o.off, await vocabulary());
1868
+ const vocab = await vocabulary();
1847
1869
  const [key, what] = o.off ? ['inbox-back', 'back'] : ['inbox-later', 'later'];
1848
- const hash = await inboxMove(o.commit, `gcf(inbox): ${what} ${id}`, plan, key);
1870
+ const { hash } = await inboxMove(
1871
+ o.commit,
1872
+ `gcf(inbox): ${what} ${id}`,
1873
+ () => planLater(gcfRoot(), id, !o.off, vocab),
1874
+ key,
1875
+ );
1849
1876
  console.log(`${id} ${o.off ? 'back from Later' : 'in Later'}${shortHash(hash)}`);
1850
1877
  });
1851
1878
  registerInboxCategories(inbox);
@@ -1875,12 +1902,17 @@ function registerInboxCategories(inbox) {
1875
1902
  await refuseOnWork('migrate the inbox');
1876
1903
  const { planMigrate } = await lib('inbox');
1877
1904
  const { gcfRoot } = await lib('gcf-paths');
1878
- const plan = await planMigrate(gcfRoot());
1879
- const n = plan.migrated.length;
1905
+ const first = await planMigrate(gcfRoot());
1906
+ const n = first.migrated.length;
1880
1907
  // Nothing old left: no commit, so a second run changes nothing.
1881
- const hash = n
1882
- ? await inboxMove(true, `gcf(inbox): ${n} entries to categories`, plan, 'inbox-migrate')
1883
- : null;
1908
+ const { hash, plan } = n
1909
+ ? await inboxMove(
1910
+ true,
1911
+ `gcf(inbox): ${n} entries to categories`,
1912
+ () => planMigrate(gcfRoot()),
1913
+ 'inbox-migrate',
1914
+ )
1915
+ : { hash: null, plan: first };
1884
1916
  const line = (m) =>
1885
1917
  `${m.id} → ${m.category}${m.dropped.length ? ` (dropped: ${m.dropped.join(', ')})` : ''}`;
1886
1918
  out(o.json, { migrated: plan.migrated, hash }, (r) =>
@@ -1924,14 +1956,16 @@ function registerInboxDrop(inbox) {
1924
1956
  await refuseOnWork('erase an entry');
1925
1957
  const { planDrop } = await lib('inbox');
1926
1958
  const { gcfRoot } = await lib('gcf-paths');
1927
- const plan = await planDrop(gcfRoot(), id);
1928
1959
  const { inHead } = await lib('git');
1929
- const committed = inHead(process.cwd(), plan.files[0]);
1960
+ const committed = inHead(
1961
+ process.cwd(),
1962
+ (await planDrop(gcfRoot(), id)).files[0], // the entry's own file
1963
+ );
1930
1964
  // An entry never committed leaves nothing to commit: it is only erased, from the index too.
1931
- const hash = await inboxMove(
1965
+ const { hash, plan } = await inboxMove(
1932
1966
  o.commit && committed,
1933
1967
  `gcf(inbox): drop ${id}`,
1934
- plan,
1968
+ () => planDrop(gcfRoot(), id),
1935
1969
  'inbox-drop',
1936
1970
  );
1937
1971
  if (!committed)
@@ -2000,7 +2034,8 @@ function registerInbox(gcf) {
2000
2034
  item: o.item,
2001
2035
  vocab: await vocabulary(),
2002
2036
  });
2003
- const hash = await inboxMove(o.commit, 'gcf(inbox): add', plan, 'inbox-add');
2037
+ // A new entry reads nothing that a wait could change: its plan holds.
2038
+ const { hash } = await inboxMove(o.commit, 'gcf(inbox): add', () => plan, 'inbox-add');
2004
2039
  console.log(`${plan.entry.id}${shortHash(hash)}`);
2005
2040
  });
2006
2041
  registerInboxSort(inbox);
@@ -2040,8 +2075,12 @@ function registerLessons(gcf) {
2040
2075
  if (!Array.isArray(list)) throw new Error(`${o.from}: lessons must be a JSON array`);
2041
2076
  if (!list.length) return console.log(`recorded 0 lessons for ${id}`);
2042
2077
  const { gcfRoot } = await lib('gcf-paths');
2043
- const plan = planLessons(gcfRoot(), id, list);
2044
- const hash = await inboxMove(o.commit, `gcf(lessons): ${id}`, plan, 'lessons');
2078
+ const { hash, plan } = await inboxMove(
2079
+ o.commit,
2080
+ `gcf(lessons): ${id}`,
2081
+ () => planLessons(gcfRoot(), id, list),
2082
+ 'lessons',
2083
+ );
2045
2084
  console.log(`recorded ${plan.entries.length} lessons for ${id}${shortHash(hash)}`);
2046
2085
  });
2047
2086
  }
package/extension.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://raw.githubusercontent.com/lee-to/ai-factory/2.x/schemas/extension.schema.json",
3
3
  "name": "gcf-aif-ext",
4
- "version": "0.32.0",
4
+ "version": "0.34.0",
5
5
  "description": "Game Context Framework for AI Factory",
6
6
  "skills": [
7
7
  "skills/gcf-init",
@@ -4,6 +4,9 @@ gcf_gate:
4
4
  - when `gcf/` exists and the task names a work item, run `ai-factory gcf context <item-id>` first
5
5
  - the returned file list is the readset: read those files, `gcf/INDEX.md` and `gcf/config.yml`, and nothing else under `gcf/`; `gcf/LIVE.md` in it says what the game already does
6
6
  - its `graveyard_hits` and `d2` lines are context too: what was buried before, and the assumptions in force with their `until:`
7
+ - a `d2` record marked `[fired: <trigger>]` (its id in `d2_fired`) is the human's call now: do not plan on its value
8
+ - only when the plan depends on that value, stop: `ai-factory gcf block <item-id> --reason "needs the human's answer to <q-NNN> (its until fired)"`, unless the item is already blocked on it
9
+ - a fired D2 is not re-filed as a D1: the human answers its own record
7
10
  - `over_budget: true` in the result: stop and record a D1 question instead of planning
8
11
  - an id in `depends:` that lives in `gcf/design/`, or as an item in any status but unplayed, parked or awaiting-verdict, is not played: do not plan on top of it, stop
9
12
  - a dependency awaiting its verdict is planned on: the close of this item then waits for that verdict (`ai-factory gcf block <id> --reason "waits for <dep>"`)
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,7 +19,15 @@ 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';
@@ -30,21 +37,6 @@ import { cardRunMode, liveCopies } from './integrate.js';
30
37
  import { playOnIssues } from './play-on.js';
31
38
  import { platformsOf } from './playtest-list.js';
32
39
 
33
- function git(args, cwd) {
34
- // A blame of a long file overflows the 1 MiB default, and an overflow reads as a git failure.
35
- const res = spawnSync('git', args, {
36
- windowsHide: true,
37
- cwd,
38
- encoding: 'utf8',
39
- maxBuffer: 64 * 1024 * 1024,
40
- });
41
-
42
- return res.status === 0 ? res.stdout.trim() : null;
43
- }
44
-
45
- const UNTIL_RE = /\[until:\s*(verdict\([a-z0-9-]+\)|retune\([a-z0-9-]+\)|manual\([^)]*\))\]/g;
46
- const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
47
-
48
40
  /**
49
41
  * Whether an item runs, and who works it (`running_by`): `run`, a harness run's live lock; `you`,
50
42
  * a fresh session mark this session or its run owns (`GCF_RUN_OWNER`, else
@@ -79,12 +71,15 @@ function runningOf(projectDir, id) {
79
71
  * @property {string[]} legacy_cards
80
72
  * @property {{tokens: number, budget: number, over: boolean, count: number, too_many: boolean}
81
73
  * | null} pillars
82
- * @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
83
77
  * @property {Record<string, object[]>} linter
84
78
  * @property {object[]} pragmas
85
79
  * @property {boolean} index_drift
86
80
  * @property {Array<{id: string, status: string}>} illegal_status
87
- * @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
88
83
  * @property {{errors: string[], warnings: string[]}} play_on cards' build names (lib/play-on.js)
89
84
  * @property {number} [schema]
90
85
  * @property {Array<{id: string, type: string, gate: string, status: string, system: string[],
@@ -117,6 +112,11 @@ export async function audit(projectDir) {
117
112
  const unplayed = items.filter(
118
113
  (c) => c.data.status === 'unplayed' && !named.has(c.data.milestone),
119
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
+ });
120
120
  /** @type {AuditReport} */
121
121
  const report = {
122
122
  first_line: '',
@@ -131,17 +131,12 @@ export async function audit(projectDir) {
131
131
  },
132
132
  legacy_cards: legacyCards(root),
133
133
  pillars: await pillarsOf(root, config),
134
- until: untilRecords(
135
- items,
136
- systems,
137
- verdictMatchers(projectDir, ledger, items),
138
- await questionsText(root),
139
- ),
134
+ until: untilRecords(projectDir, { items, systems, fired, questions }),
140
135
  linter: {},
141
136
  pragmas: [],
142
137
  index_drift: await drifted(root),
143
138
  illegal_status: [],
144
- stale_questions: staleQuestions(projectDir, root, config),
139
+ stale_questions: staleQuestions(questions, config),
145
140
  inbox: await inboxProblems(root, inboxVocabulary()),
146
141
  play_on: playOnIssues(items, config, await platformsOf(root)),
147
142
  // A config from before the review rows (Operator-Tasks-Plan t2 d1): the command that moves it.
@@ -277,119 +272,58 @@ async function pillarsOf(root, config) {
277
272
  }
278
273
 
279
274
  /**
280
- * Open questions older than the limit, aged by the last commit that changed their `- id:` line
281
- * beyond whitespace (GCF-PRD §7.4): a pile of unanswered ones means the human has dropped out
282
- * of the loop.
283
- */
284
- function staleQuestions(projectDir, root, config) {
285
- if (!existsSync(path.join(root, 'open-questions.md'))) return [];
286
- // null for an untracked file or outside a repository: no commit to age from. -w: a respaced
287
- // or re-ended (CRLF/LF) line keeps the commit that wrote it.
288
- const blame = git(['blame', '-w', '--porcelain', '--', 'gcf/open-questions.md'], projectDir);
289
- if (blame === null) return [];
290
- const added = [];
291
- let hash = '';
292
- for (const line of blame.split('\n')) {
293
- const head = line.match(/^([0-9a-f]{40,64}) \d+ \d+/);
294
- if (head) hash = head[1];
295
- const id = line.match(/^\t\uFEFF?- id:\s*(\S+)/)?.[1];
296
- // An uncommitted line blames to the all-zero hash: it is new, not old.
297
- if (id && !/^0+$/.test(hash)) added.push({ id, hash });
298
- }
299
-
300
- const ages = new Map();
301
- const ageOf = (h) => {
302
- if (!ages.has(h)) {
303
- const raw = git(['rev-list', '--count', `${h}..HEAD`], projectDir);
304
- // Number(null) is 0, "fresh" — the one answer that must never be guessed (see staleEntry).
305
- ages.set(h, raw === null ? null : Number(raw));
306
- }
307
-
308
- return ages.get(h);
309
- };
310
-
311
- const limit = config.question_stale_after_commits;
312
-
313
- return added
314
- .map(({ id, hash: h }) => ({ id, commits: ageOf(h), limit }))
315
- .filter((q) => q.commits === null || q.commits > limit);
316
- }
317
-
318
- /**
319
- * Whether a verdict fired. `verdict(id)` reads the files, as the ledger does (GCF-PRD §5.8): a
320
- * keep or kill left a history or graveyard line, a tune left the item's tune_count — so a
321
- * squash or a shallow clone does not hide it, and a revert takes it back.
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).
322
279
  */
323
- function verdictMatchers(projectDir, ledger, items) {
324
- const tuned = items.filter((c) => (c.data.tune_count ?? 0) > 0);
325
- const verdictLog =
326
- git(['log', '--basic-regexp', '--grep', '^gcf(verdict):', '--format=%s'], projectDir) ?? '';
327
-
328
- return {
329
- verdict: (id) =>
330
- ledger.where(id).terminal.some((t) => t !== 'done') || tuned.some((c) => c.data.id === id),
331
- // shortcut: a kept item's tunes leave no file behind, so retune(sys) also greps the verdict
332
- // subjects; upgrade when tunes get their own history line.
333
- retune: (system) =>
334
- tuned.some((c) => (c.data.system ?? []).includes(system)) ||
335
- new RegExp(`^gcf\\(verdict\\): tune .*→ (?:.*,)?${escapeRe(system)}(?:,|$)`, 'm').test(
336
- verdictLog,
337
- ),
338
- };
339
- }
340
-
341
- function untilStatus(trigger, fired) {
342
- if (trigger.startsWith('verdict(')) {
343
- return fired.verdict(trigger.slice(8, -1)) ? 'stale' : 'open';
344
- }
345
-
346
- if (trigger.startsWith('retune(')) {
347
- return fired.retune(trigger.slice(7, -1)) ? 'stale' : 'open';
348
- }
349
-
350
- return 'manual';
351
- }
352
-
353
- /** open-questions.md, or '' without one. */
354
- const questionsText = async (root) => {
355
- const file = path.join(root, 'open-questions.md');
356
-
357
- return existsSync(file) ? readFile(file, 'utf8') : '';
358
- };
359
-
360
- 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 }));
361
284
 
362
285
  /**
363
286
  * Until annotations across work items and systems docs, and the `until:` of each D2 record in
364
- * 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`.
365
290
  */
366
- function untilRecords(items, systems, fired, questions) {
291
+ function untilRecords(projectDir, { items, systems, fired, questions }) {
367
292
  const docs = [
368
- ...items.map((c) => ({ rel: `work/${c.name}`, body: c.body })),
369
- ...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 })),
370
295
  ];
371
296
  const until = [];
372
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
+
373
310
  // A quoted line (an inbox entry's text in a note:) holds no annotation, as for the gate.
374
- const own = doc.body
375
- .split('\n')
376
- .filter((l) => !l.startsWith('>'))
377
- .join('\n');
378
- for (const m of own.matchAll(UNTIL_RE)) {
379
- 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
+ }
380
322
  }
381
323
  }
382
324
 
383
- for (const rec of questions.replace(/\r\n/g, '\n').split(/\n(?=- id:)/)) {
384
- const id = rec.match(/^- id:\s*(\S+)/)?.[1];
385
- const trigger = fieldOf(rec, 'until')?.match(D2_UNTIL_RE)?.[1];
386
- if (!id || !trigger || !/^D2\b/.test(fieldOf(rec, 'class') ?? '')) continue;
387
- until.push({
388
- file: 'gcf/open-questions.md',
389
- id,
390
- trigger,
391
- status: untilStatus(trigger, fired),
392
- });
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 });
393
327
  }
394
328
 
395
329
  return until;
@@ -421,7 +355,7 @@ const itemAlerts = (report) => [
421
355
 
422
356
  /** Alerts about the documents. @param {AuditReport} report */
423
357
  const docAlerts = (report) => [
424
- report.until.filter((u) => u.status === 'stale').length && 'stale until-records present',
358
+ staleUntil(report.until),
425
359
  report.pillars?.over && 'PILLARS over token budget',
426
360
  report.pillars?.too_many && `PILLARS has ${report.pillars.count} pillars (max ${PILLARS_MAX})`,
427
361
  report.stale_questions.length &&
@@ -435,6 +369,17 @@ const docAlerts = (report) => [
435
369
  ...inboxAlerts(report.inbox),
436
370
  ];
437
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
+
438
383
  /** Alerts about gcf/config.yml. @param {AuditReport} report */
439
384
  const configAlerts = (report) => [
440
385
  report.review_migration &&
package/lib/board.js CHANGED
@@ -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';
@@ -439,7 +440,16 @@ export async function board(projectDir) {
439
440
  i.needed_by = items.filter((o) => o.depends.includes(i.id)).map((o) => o.id);
440
441
 
441
442
  const live = await readLive(root);
442
- 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)));
443
453
  const { units, design } = await designOf(projectDir, ledger, questions);
444
454
 
445
455
  return {
@@ -480,13 +490,7 @@ export async function board(projectDir) {
480
490
  inbox,
481
491
  // A lesson kind met in 3 runs or more: it rises to Needs you (decision 32).
482
492
  inbox_repeats: lessonRepeats(inbox),
483
- // The class stays in the file; the screen shows the category (§2.7, decision 32). An agent
484
- // writes every question record: its origin is one.
485
- questions: questions.map((q) => ({
486
- ...q,
487
- category: /^D1\b/.test(q.class ?? '') ? 'decision' : 'assumption',
488
- origin: 'agent',
489
- })),
493
+ questions,
490
494
  history: await historyOf(root),
491
495
  graveyard: await graveyardOf(root),
492
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