gcf-aif-ext 0.18.9 → 0.20.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/gates.js ADDED
@@ -0,0 +1,57 @@
1
+ // The stops that wait for the operator, per project (`gates:` of gcf/config.yml) and per card
2
+ // (`skip_gates:`) — docs/Autonomy-Plan.md, B. The one place the core reads the policy.
3
+ import { GATE_POLICY } from './gcf-paths.js';
4
+
5
+ const ITEM_GATES = ['verdict', 'decision', 'question'];
6
+ const SECOND = Object.fromEntries(ITEM_GATES.map((g) => [g, GATE_POLICY[g][1]]));
7
+ // A mechanic or a resource closes unplayed; the rest of a verdict's waits (Plan phase 2).
8
+ const DEFERRABLE = ['mechanic', 'resource'];
9
+ // What an agent may decide under `decision: agent`: its own question answered, never a release.
10
+ const AGENT_DECIDES = ['spike', 'decision'];
11
+
12
+ /**
13
+ * The gates in force for `item` (its frontmatter): the project's, or every item gate on its
14
+ * second value (`skip_gates: true`) or on `wait` (`false`). `milestone` is the project's only.
15
+ * @param {{gates: Record<string, string>}} config readConfig's
16
+ * @param {Record<string, any> | null} [item]
17
+ */
18
+ export function gatePolicy(config, item = null) {
19
+ const skip = item?.skip_gates;
20
+ if (typeof skip !== 'boolean') return { ...config.gates };
21
+
22
+ return {
23
+ milestone: config.gates.milestone,
24
+ ...Object.fromEntries(ITEM_GATES.map((g) => [g, skip ? SECOND[g] : 'wait'])),
25
+ };
26
+ }
27
+
28
+ /**
29
+ * Whether `item`'s submit closes it unplayed instead of waiting for a verdict: not one whose
30
+ * delta changes a capability (A4), which waits for the verdict all the same.
31
+ */
32
+ export const verdictDeferred = (config, item) =>
33
+ item.gate === 'verdict' &&
34
+ DEFERRABLE.includes(item.type) &&
35
+ !(item.live?.changes ?? []).some((c) => c.change !== 'added') &&
36
+ gatePolicy(config, item).verdict === 'defer';
37
+
38
+ /**
39
+ * Why an agent may not `decide <choice>` on `item` (its frontmatter), or null: only under
40
+ * `decision: agent`, only go or no of a spike or a decision item waiting for its decision, with
41
+ * a reason; a child's no would pause its feature, so that stays the operator's.
42
+ */
43
+ export function agentDecideProblem(config, item, choice, reason) {
44
+ const no = (why) => `decide is the operator's here: ${why}`;
45
+ if (gatePolicy(config, item).decision !== 'agent')
46
+ return no('gates.decision is wait (the operator sets agent, or skip_gates on the card)');
47
+ if (!AGENT_DECIDES.includes(item.type) || item.gate !== 'decision')
48
+ return no(`an agent decides only a spike or a decision item, ${item.id} is a ${item.type}`);
49
+ if (item.status !== 'awaiting-decision')
50
+ return no(`${item.id} is ${item.status}, not awaiting-decision: submit it first`);
51
+ if (!['go', 'no'].includes(choice)) return no('an agent decides go or no only');
52
+ if (choice === 'no' && item.parent)
53
+ return no(`${item.id} is a child of ${item.parent}: its death pauses the feature`);
54
+ if (!String(reason ?? '').trim()) return 'an agent decides with --reason "<why>"';
55
+
56
+ return null;
57
+ }
package/lib/gcf-paths.js CHANGED
@@ -79,6 +79,37 @@ function chatOf(v = {}) {
79
79
  return chat;
80
80
  }
81
81
 
82
+ // The stops that wait for the operator (docs/Autonomy-Plan.md, B): each `wait`, as GCF always
83
+ // did, or its second value, which lets the agent go on. A release always waits.
84
+ export const GATE_POLICY = {
85
+ milestone: ['wait', 'go'],
86
+ verdict: ['wait', 'defer'],
87
+ decision: ['wait', 'agent'],
88
+ question: ['wait', 'assume'],
89
+ };
90
+
91
+ function gatesOf(v = {}) {
92
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
93
+ throw new Error('gcf/config.yml: gates must be a key: value mapping');
94
+ const extra = Object.keys(v).find((k) => !(k in GATE_POLICY));
95
+ if (extra)
96
+ throw new Error(
97
+ `gcf/config.yml: gates.${extra} is not a gate (${Object.keys(GATE_POLICY).join(', ')})`,
98
+ );
99
+
100
+ return Object.fromEntries(
101
+ Object.entries(GATE_POLICY).map(([gate, values]) => {
102
+ const value = v[gate] ?? 'wait';
103
+ if (!values.includes(value))
104
+ throw new Error(
105
+ `gcf/config.yml: gates.${gate} must be ${values.join(' | ')}, got ${value}`,
106
+ );
107
+
108
+ return [gate, value];
109
+ }),
110
+ );
111
+ }
112
+
82
113
  /** @returns {Promise<Record<string, any>>} */
83
114
  export async function readConfig(root) {
84
115
  return configOf(await readRawConfig(root));
@@ -130,7 +161,12 @@ export function configOf(parsed) {
130
161
  `(${handoff + 15}), or the compaction comes before the handoff`,
131
162
  );
132
163
 
133
- return { ...config, run_mode: runModeOf(config.run_mode), chat: chatOf(config.chat) };
164
+ return {
165
+ ...config,
166
+ run_mode: runModeOf(config.run_mode),
167
+ chat: chatOf(config.chat),
168
+ gates: gatesOf(config.gates),
169
+ };
134
170
  }
135
171
 
136
172
  /** Token estimate: ceil(chars/4). Stability over accuracy (GCF-PRD §9.1). */
package/lib/git.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync } from 'node:fs';
2
+ import { existsSync, rmSync } from 'node:fs';
3
3
  import path from 'node:path';
4
+ import { refusal } from './refusal.js';
4
5
 
5
6
  // `git commit --only <paths>` is a partial commit, which git refuses outright while a merge
6
7
  // or a sequencer operation is in progress. Detect it up front so the failure has a reason.
@@ -24,9 +25,17 @@ export function operationInProgress(projectDir) {
24
25
  return IN_PROGRESS.find((name) => existsSync(path.join(dir, name))) ?? null;
25
26
  }
26
27
 
28
+ /**
29
+ * A path as a literal pathspec from the project: git would read `[`, `*` or `?` in a name as a
30
+ * glob and take its siblings too (`a[1].md` matching `a1.md`). An absolute path goes relative.
31
+ */
32
+ export const literal = (projectDir, p) => `:(literal)${relOf(projectDir, p)}`;
33
+
27
34
  const tracked = (projectDir, p) =>
28
- spawnSync('git', ['ls-files', '--error-unmatch', '--', p], { cwd: projectDir, stdio: 'ignore' })
29
- .status === 0;
35
+ spawnSync('git', ['ls-files', '--error-unmatch', '--', literal(projectDir, p)], {
36
+ cwd: projectDir,
37
+ stdio: 'ignore',
38
+ }).status === 0;
30
39
 
31
40
  /** Whether the last commit holds `p`: a file only staged is not in it. */
32
41
  export const inHead = (projectDir, p) =>
@@ -51,24 +60,132 @@ export function dirtyPaths(projectDir, paths) {
51
60
  return res.status === 0 ? res.stdout.split('\n').filter(Boolean) : [];
52
61
  }
53
62
 
54
- const BY = ['run', 'session', 'operator'];
63
+ /**
64
+ * What the commit gate reads (hooks/pre-commit.js), as pathspecs from the project: gcf/ without
65
+ * gcf/.metrics (audit and context append to it on every run) and without an unfinished
66
+ * import's held anchor map (`source/*.import.json`, kept until `gcf anchor --done`).
67
+ */
68
+ export const GATE_SCOPE = [
69
+ 'gcf',
70
+ ':(exclude)gcf/.metrics',
71
+ ':(exclude,glob)gcf/source/*.import.json',
72
+ ];
73
+
74
+ /**
75
+ * Every path under the gate's scope git sees changed, staged or not, or new, from the project
76
+ * with `/`: the whole set a refusal names, so committing it all clears the gate in one go.
77
+ * From git, not a refusal's text: a name may hold `, ` or any letter. `skip`: paths (absolute
78
+ * or from the project) that ride along with a move and stop nothing.
79
+ * @param {string} projectDir
80
+ * @param {Iterable<string>} [skip]
81
+ */
82
+ export function dirtyGcf(projectDir, skip = []) {
83
+ const res = spawnSync(
84
+ 'git',
85
+ ['-c', 'core.quotePath=false', 'status', '--porcelain', '-z', '-uall', '--', ...GATE_SCOPE],
86
+ { cwd: projectDir, encoding: 'utf8' },
87
+ );
88
+ if (res.status !== 0) return [];
89
+ // Porcelain paths are the repository's: a project inside a bigger repository is a prefix in.
90
+ const prefix = spawnSync('git', ['rev-parse', '--show-prefix'], {
91
+ cwd: projectDir,
92
+ encoding: 'utf8',
93
+ }).stdout.trim();
94
+ const recs = res.stdout.split('\0');
95
+ const ours = (file) => (prefix && file.startsWith(prefix) ? file.slice(prefix.length) : file);
96
+ const paths = [];
97
+ for (let i = 0; i < recs.length; i++) {
98
+ const rec = recs[i];
99
+ if (rec.length < 4) continue;
100
+ paths.push(ours(rec.slice(3)));
101
+ // A rename or a copy: its old path is the next record. A rename's is a deletion the gate
102
+ // sees too, so it goes with it (under gcf/); a copy's source is unchanged.
103
+ const xy = rec.slice(0, 2);
104
+ if (!/[RC]/.test(xy)) continue;
105
+ i++;
106
+ const old = ours(recs[i] ?? '');
107
+ if (xy.includes('R') && old.startsWith('gcf/')) paths.push(old);
108
+ }
109
+
110
+ const off = new Set([...skip].map((p) => relOf(projectDir, p)));
111
+
112
+ return [...new Set(paths)].filter((p) => !off.has(p)).sort();
113
+ }
114
+
115
+ /**
116
+ * The refusal of a move that uncommitted gcf/ edits stop: `dirty` with `paths` (dirtyGcf) when
117
+ * there are any, so a board offers to show, commit or discard them; else the words alone.
118
+ * @param {string[]} paths
119
+ * @param {string} message
120
+ */
121
+ export const dirtyRefusal = (paths, message) =>
122
+ paths.length ? refusal('dirty', { paths }, message) : new Error(message);
123
+
124
+ /** A path from the project with `/`, from an absolute one or one already relative. */
125
+ const relOf = (projectDir, p) =>
126
+ path.relative(path.resolve(projectDir), path.resolve(projectDir, p)).replaceAll('\\', '/');
55
127
 
56
128
  /**
57
- * Who makes a move: `GCF_MOVE_BY` when it names one (the harness sets `run` for both run modes),
58
- * else a harness run's owner, else a Claude Code session, else the operator. Inside a run or a
59
- * session `GCF_MOVE_BY` cannot name the operator: an agent would claim the operator's moves.
60
- * shortcut: an agent that unsets its own markers still passes for the operator; a trusted channel
61
- * of who runs a command would close it.
129
+ * Put `files` (from the project) back as the last commit has them, the index too: a tracked one
130
+ * checked out from HEAD, a new one out of the index and off the disk. No lock: the caller holds
131
+ * gcf/ (design discard, edits discard).
132
+ * @param {string} projectDir
133
+ * @param {string[]} files
134
+ */
135
+ export function restoreFromHead(projectDir, files) {
136
+ const git = (...args) => spawnSync('git', args, { cwd: projectDir, encoding: 'utf8' });
137
+ const must = (...args) => {
138
+ const r = git(...args);
139
+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr.trim()}`);
140
+ };
141
+ for (const f of files) {
142
+ if (git('cat-file', '-e', `HEAD:./${f}`).status === 0) {
143
+ must('checkout', 'HEAD', '--', literal(projectDir, f));
144
+ continue;
145
+ }
146
+ must('rm', '--cached', '-q', '--ignore-unmatch', '--', literal(projectDir, f));
147
+ rmSync(path.join(projectDir, f), { force: true });
148
+ }
149
+ }
150
+
151
+ const BY = ['run', 'thread', 'session', 'operator'];
152
+
153
+ /**
154
+ * Who makes a move: `GCF_MOVE_BY` when it names one (the harness sets `run` for both run modes,
155
+ * the board `thread` for its threads), else a harness run's owner, else a Claude Code session,
156
+ * else the operator. Inside a run or a session `GCF_MOVE_BY` cannot name the operator, and
157
+ * inside a run (its owner, or the item a worktree session works) not a session either: an agent
158
+ * would claim the operator's moves.
159
+ * shortcut: an agent that unsets its own markers still passes for the operator, a thread's that
160
+ * names itself a session too; a trusted channel of who runs a command would close it.
62
161
  */
63
162
  export function moveBy(env = process.env) {
163
+ const run = Boolean(env.GCF_RUN_OWNER || env.GCF_RUN_ITEM);
64
164
  const agent = Boolean(env.GCF_RUN_OWNER || env.CLAUDE_CODE_SESSION_ID);
65
165
  const named = env.GCF_MOVE_BY ?? '';
166
+ if (run && ['session', 'operator'].includes(named)) return 'run';
66
167
  if (BY.includes(named) && !(agent && named === 'operator')) return named;
67
168
  if (env.GCF_RUN_OWNER) return 'run';
68
169
 
69
170
  return env.CLAUDE_CODE_SESSION_ID ? 'session' : 'operator';
70
171
  }
71
172
 
173
+ /**
174
+ * Refuse the operator's `move` made by a harness run or a board thread (docs/Autonomy-Plan.md,
175
+ * A). A console session passes: it is the operator's helper (gcf-verdict records the
176
+ * operator's verdict from it). The deny group `human-moves` refuses earlier; this holds a run
177
+ * started with `--agent`, which gets no deny rules.
178
+ * @param {string} move
179
+ */
180
+ export function needOperator(move, env = process.env) {
181
+ const by = moveBy(env);
182
+ if (by !== 'run' && by !== 'thread') return;
183
+ throw new Error(
184
+ `${move} is the operator's: a ${by === 'run' ? 'harness run' : 'board thread'} does not ` +
185
+ 'make it — block the item with the question, or propose the move to the operator',
186
+ );
187
+ }
188
+
72
189
  /**
73
190
  * The trailer paragraph of a move's commit as `git commit`/`git merge` arguments (`gcf item
74
191
  * history` reads it): the items and units it touched, the domain's move key, who made it, and
@@ -101,22 +218,29 @@ export function moveTrailers({ key, items = [], proposal } = {}) {
101
218
  */
102
219
  export function commitPaths(projectDir, message, paths, move = {}) {
103
220
  const staged = paths.filter((p) => existsSync(p) || tracked(projectDir, p));
104
- for (const p of staged) spawnSync('git', ['add', '--', p], { cwd: projectDir, stdio: 'ignore' });
105
- // A file staged but never committed and now deleted is out of the index too: no pathspec.
106
- const real = staged.filter((p) => existsSync(p) || inHead(projectDir, p));
221
+ for (const p of staged)
222
+ spawnSync('git', ['add', '--', literal(projectDir, p)], { cwd: projectDir, stdio: 'ignore' });
223
+ // A staged deletion (`git rm`) is off the disk and out of the index, but HEAD holds it: its
224
+ // path commits the deletion. A file staged but never committed and now deleted matches
225
+ // nothing: no pathspec.
226
+ const real = paths.filter((p) => existsSync(p) || inHead(projectDir, p));
107
227
  const msg = ['-m', message, ...moveTrailers(move)];
108
- const res = spawnSync('git', ['commit', ...msg, '--only', '--', ...real], {
228
+ const only = real.map((p) => literal(projectDir, p));
229
+ const res = spawnSync('git', ['commit', ...msg, '--only', '--', ...only], {
109
230
  cwd: projectDir,
110
231
  encoding: 'utf8',
111
232
  });
112
233
  const out = res.stderr || res.stdout;
113
- // The gate reads the whole gcf/ tree: another file's edit stops the move, in the Operator's words.
114
- const loose = /gcf\/ has changes outside the index \((.*)\) — stage them/.exec(out)?.[1];
115
- if (res.status !== 0 && loose)
116
- throw new Error(
117
- `cannot record ${message} while gcf/ holds uncommitted changes: ${loose} — ` +
234
+ // The gate reads the whole gcf/ tree: another file's edit stops the move, in the Operator's
235
+ // words. Its paths from git: the move's own staged files ride along and stop nothing.
236
+ if (res.status !== 0 && /gcf\/ has changes outside the index/.test(out)) {
237
+ const loose = dirtyGcf(projectDir, real);
238
+ throw dirtyRefusal(
239
+ loose,
240
+ `cannot record ${message} while gcf/ holds uncommitted changes: ${loose.join(', ')} — ` +
118
241
  'commit or discard them, then try again',
119
242
  );
243
+ }
120
244
  if (res.status !== 0) throw new Error(`commit failed: ${out}`);
121
245
 
122
246
  return spawnSync('git', ['rev-parse', 'HEAD'], {
package/lib/history.js CHANGED
@@ -57,7 +57,7 @@ const trailer = (body, key) =>
57
57
  .match(new RegExp(`^${key}: *(.*)$`, 'm'))?.[1]
58
58
  .trim() ?? null;
59
59
 
60
- const BY = ['run', 'session', 'operator'];
60
+ const BY = ['run', 'thread', 'session', 'operator'];
61
61
 
62
62
  /**
63
63
  * What one commit says of item `id`: `{move, by}` when it moved the item, else null. A commit
package/lib/integrate.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // branch is ready once its tip carries the trailer `GCF-Verified: <id>` — readiness lives in git,
3
3
  // not in memory. `integrate` merges such a branch into main and records the item's move there,
4
4
  // under the main lock; without an id it picks up every verified branch a dead run left behind.
5
- import { appendFile, mkdir, readFile } from 'node:fs/promises';
5
+ import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
6
6
  import { existsSync } from 'node:fs';
7
7
  import { spawnSync } from 'node:child_process';
8
8
  import path from 'node:path';
@@ -10,7 +10,9 @@ import { buildLedger } from './ledger.js';
10
10
  import { parse } from './frontmatter.js';
11
11
  import { withMainLock, runHolder, lockedItem, MAIN_RUN } from './main-lock.js';
12
12
  import { verifyItem, deltaProblems } from './verify.js';
13
- import { submitItem, closeItem, blockItem } from './work-ops.js';
13
+ import { submitItem, closeItem, blockItem, decideItem } from './work-ops.js';
14
+ import { readConfig } from './gcf-paths.js';
15
+ import { agentDecideProblem } from './gates.js';
14
16
  import { isValidId } from './id.js';
15
17
  import { writeIndex } from './index-gen.js';
16
18
  import { moveTrailers } from './git.js';
@@ -227,23 +229,85 @@ function movedSinceMerge(projectDir, id) {
227
229
  return after.some((s) => move.test(s));
228
230
  }
229
231
 
232
+ /**
233
+ * What a worktree session left for main in its plan's `## Outcome` (docs/Autonomy-Plan.md, B):
234
+ * `decide: go|no` and `reason:` under `gates.decision: agent`, an `assume:` line per assumption
235
+ * it took. Lines may be bullets. Empty when the plan has none.
236
+ */
237
+ export function planOutcome(text) {
238
+ const out = { decide: null, reason: '', assume: [] };
239
+ const at = String(text ?? '').search(/^## Outcome[ \t]*$/m);
240
+ if (at < 0) return out;
241
+ const block = text.slice(at).split(/\r?\n/).slice(1);
242
+ const end = block.findIndex((l) => /^#{1,2} /.test(l));
243
+ for (const line of end < 0 ? block : block.slice(0, end)) {
244
+ const m = line.match(/^\s*(?:[-*]\s+)?(decide|reason|assume):\s*(.*?)\s*$/);
245
+ if (!m || !m[2]) continue;
246
+ if (m[1] === 'assume') out.assume.push(m[2]);
247
+ else out[m[1]] = m[2];
248
+ }
249
+
250
+ return out;
251
+ }
252
+
253
+ const outcomeOfPlan = async (projectDir, item) => {
254
+ const plan = path.join(projectDir, item.data.plan ?? `.ai-factory/plans/${item.data.id}.md`);
255
+
256
+ return planOutcome(existsSync(plan) ? await readFile(plan, 'utf8') : '');
257
+ };
258
+
230
259
  /**
231
260
  * The move a merged item ends its run with. Its delta is checked against main first — the
232
- * worktree's LIVE.md may be behind. A move the item refuses blocks it with the reason; when even
233
- * the block fails, the error goes up and the next integrate records the move again.
261
+ * worktree's LIVE.md may be behind. The assumptions of its plan's `## Outcome` go in the move's
262
+ * commit; its decision too, when the gates in force now let an agent decide: the submit
263
+ * without a commit, the decide with one, so the move is one commit and a crash before it leaves
264
+ * the item ready for the next integrate. A move the item refuses blocks it with the reason;
265
+ * when even the block fails, the error goes up and the next integrate records the move again.
234
266
  */
235
267
  async function recordMove(projectDir, item) {
236
268
  const { id, gate } = item.data;
237
269
  const stale = await deltaProblems(projectDir, item);
238
270
  try {
239
271
  if (stale.length) throw new Error(stale.join('; '));
240
- if (gate === 'auto') return { move: 'close', ...(await closeItem(projectDir, id)) };
272
+ const { decide, reason, assume } = await outcomeOfPlan(projectDir, item);
273
+ if (gate === 'auto') {
274
+ const r = await closeItem(projectDir, id, { assume, dropOutcome: true });
275
+
276
+ // A4: a delta that changes a capability made the close a submit.
277
+ return { move: r.awaits ? 'submit' : 'close', ...r };
278
+ }
241
279
 
242
- return { move: 'submit', ...(await submitItem(projectDir, id)) };
280
+ const config = await readConfig(path.join(path.resolve(projectDir), 'gcf'));
281
+ const waits = { ...item.data, status: 'awaiting-decision' };
282
+ if (decide && !agentDecideProblem(config, waits, decide, reason)) {
283
+ // The submit writes awaiting-decision with no commit: a decide that fails puts the file
284
+ // back as it was, ready, so the block below and the next integrate both find it there.
285
+ const before = await readFile(item.file, 'utf8');
286
+ try {
287
+ await submitItem(projectDir, id, { commit: false, dropOutcome: false });
288
+ const done = await decideItem(projectDir, id, decide, { reason, assume });
289
+
290
+ return { move: 'decide', ...done };
291
+ } catch (e) {
292
+ await writeFile(item.file, before);
293
+ throw e;
294
+ }
295
+ }
296
+
297
+ // A decision the gates do not give the agent rides in the submit's commit, for the human.
298
+ const said = decide ? `agent: ${decide}${reason ? ` — ${reason}` : ''}` : '';
299
+
300
+ return {
301
+ move: 'submit',
302
+ ...(await submitItem(projectDir, id, { assume, said, dropOutcome: true })),
303
+ };
243
304
  } catch (e) {
244
305
  const reason = `integrate: ${e.message}`;
245
306
 
246
- return { move: 'block', reason, ...(await blockItem(projectDir, id, { reason })) };
307
+ // The block takes the Outcome out too: the rerun writes its own.
308
+ const blocked = await blockItem(projectDir, id, { reason, dropOutcome: true });
309
+
310
+ return { move: 'block', reason, ...blocked };
247
311
  }
248
312
  }
249
313
 
@@ -0,0 +1,118 @@
1
+ // Where each milestone of game.md stands (docs/Autonomy-Plan.md, D): what is left to take,
2
+ // build and play. A milestone is built once nothing of it waits to be taken or built; played
3
+ // once nothing of it waits for play either. The autopilot builds the first milestone not built
4
+ // and stops for the first one built but not played.
5
+ import { spawnSync } from 'node:child_process';
6
+ import path from 'node:path';
7
+ import { gameMilestones } from './design-check.js';
8
+
9
+ /**
10
+ * Whether an item of milestone `name` ever ended: a commit deleted a work file that carried it.
11
+ * Its work is over, not unborn; units moved to another milestone leave it unborn.
12
+ */
13
+ function carriedOnce(projectDir, name) {
14
+ const res = spawnSync(
15
+ 'git',
16
+ [
17
+ 'log',
18
+ '-1',
19
+ '--format=%h',
20
+ '--diff-filter=D',
21
+ `-G^milestone: ${name}[[:space:]]*$`,
22
+ '--',
23
+ 'gcf/work',
24
+ ],
25
+ { cwd: projectDir, encoding: 'utf8' },
26
+ );
27
+
28
+ return res.status === 0 && Boolean(res.stdout.trim());
29
+ }
30
+
31
+ // Statuses that still hold a milestone's build: work to do, a block, a decision owed.
32
+ const BUILDING = ['ready', 'blocked', 'awaiting-decision'];
33
+ // Statuses that wait for the milestone's play.
34
+ const TO_PLAY = ['awaiting-verdict', 'unplayed'];
35
+ // A child no longer holding its feature's build: ended, unplayed, parked, or waiting for play.
36
+ const CHILD_DONE = ['unplayed', 'parked', 'awaiting-verdict'];
37
+
38
+ /**
39
+ * A live feature whose children are all done (or wait for play) holds no build: the harness
40
+ * closes it after a run (Plan, D).
41
+ */
42
+ function holdsBuild(ledger, item) {
43
+ if (!BUILDING.includes(item.data.status)) return false;
44
+ if (item.data.type !== 'feature' || item.data.status !== 'ready') return true;
45
+
46
+ return (item.data.children ?? []).some((c) => {
47
+ const child = ledger.item(c);
48
+
49
+ return child && !CHILD_DONE.includes(child.data.status);
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Each milestone of game.md in order with its units (the design units not taken yet, each with
55
+ * the D1 questions that hold it), its items by status (a release is the operator's and counts
56
+ * for nothing), and `empty`, `built`, `played`; then `build_milestone` (the first not built)
57
+ * and `play_milestone` (the first built and not played) by name, and `milestone_order`: each
58
+ * item of an earlier milestone that depends on an item of a later one. `units` is the design check's unit summaries.
59
+ * @param {string} projectDir
60
+ * @param {any} ledger buildLedger's
61
+ * @param {{id: string, milestone: string, blocked_by: string[]}[]} units
62
+ */
63
+ export async function milestoneState(projectDir, ledger, units) {
64
+ const root = path.join(path.resolve(projectDir), 'gcf');
65
+ const list = (await gameMilestones(root)) ?? [];
66
+ const names = list.map((m) => m.name);
67
+ const items = ledger.items.filter((c) => c.data.type !== 'release');
68
+ const milestones = list.map((m) => {
69
+ const own = items.filter((c) => c.data.milestone === m.name);
70
+ const left = units.filter((u) => u.milestone === m.name);
71
+ const byStatus = {};
72
+ for (const c of own) byStatus[c.data.status] = (byStatus[c.data.status] ?? 0) + 1;
73
+ const empty = !own.length && !left.length;
74
+ const built = !empty && !left.length && !own.some((c) => holdsBuild(ledger, c));
75
+
76
+ return {
77
+ name: m.name,
78
+ goal: m.goal,
79
+ play: m.play,
80
+ units: left.map((u) => ({
81
+ id: u.id,
82
+ blocked_by: u.blocked_by?.length ? u.blocked_by : null,
83
+ })),
84
+ items: byStatus,
85
+ ids: own.map((c) => String(c.data.id)),
86
+ empty,
87
+ built,
88
+ played: built && !own.some((c) => TO_PLAY.includes(c.data.status)),
89
+ };
90
+ });
91
+ const rank = (m) => names.indexOf(m);
92
+ const order = items.flatMap((c) =>
93
+ (c.data.depends ?? [])
94
+ .map((d) => ledger.item(d))
95
+ .filter(
96
+ (d) => d && rank(d.data.milestone) > rank(c.data.milestone) && rank(c.data.milestone) >= 0,
97
+ )
98
+ .map((d) => ({
99
+ id: String(c.data.id),
100
+ milestone: c.data.milestone,
101
+ depends: String(d.data.id),
102
+ on: d.data.milestone,
103
+ })),
104
+ );
105
+
106
+ // An ended item leaves no file: an empty milestone some unit or item once carried is done
107
+ // (built and played), one nothing ever carried is laid out by nobody yet.
108
+ for (const m of milestones)
109
+ if (m.empty && carriedOnce(projectDir, m.name)) Object.assign(m, { built: true, played: true });
110
+ const due = milestones.filter((m) => !m.built);
111
+
112
+ return {
113
+ milestones,
114
+ build_milestone: due[0]?.name ?? null,
115
+ play_milestone: milestones.find((m) => m.built && !m.played)?.name ?? null,
116
+ milestone_order: order,
117
+ };
118
+ }
package/lib/phase.js CHANGED
@@ -9,6 +9,7 @@ import { buildLedger } from './ledger.js';
9
9
  import { ITEM_TYPES } from './validate-item.js';
10
10
  import { commitMove } from './unit-ops.js';
11
11
  import { locked } from './main-lock.js';
12
+ import { gameMilestones } from './design-check.js';
12
13
 
13
14
  const ALL = ITEM_TYPES;
14
15
  const SOFT = ['mechanic', 'resource'];
@@ -47,6 +48,18 @@ export const DEFAULT_PHASES = [
47
48
  const finished = ['unplayed', 'parked'];
48
49
  const milestoneOf = (phase) => phase.milestone ?? phase.name;
49
50
 
51
+ /**
52
+ * The phase's milestone and every one before it in game.md's order (docs/Autonomy-Plan.md, C):
53
+ * a vertical slice is several milestones, an early one left open still holds the phase. One
54
+ * game.md does not list counts alone.
55
+ */
56
+ const throughMilestone = (phase, order) => {
57
+ const m = milestoneOf(phase);
58
+ const at = order.indexOf(m);
59
+
60
+ return at < 0 ? [m] : order.slice(0, at + 1);
61
+ };
62
+
50
63
  /**
51
64
  * Exit criteria: `true` met, `false` not, `null` for one only the operator can see. Each gets
52
65
  * the ledger, LIVE.md and the phase, and returns `[met, detail]`.
@@ -62,12 +75,13 @@ const CRITERIA = {
62
75
  },
63
76
  // An ended item leaves no file, so "nothing open" cannot tell a done milestone from one never
64
77
  // tagged: the operator reads that case, the code only names what is still open.
65
- 'milestone-done': (ledger, live, phase) => {
78
+ 'milestone-done': (ledger, live, phase, order) => {
66
79
  const m = milestoneOf(phase);
80
+ const through = throughMilestone(phase, order);
67
81
  const open = [
68
- ...ledger.design.flatMap((d) => d.units).filter((u) => u.header.milestone === m),
82
+ ...ledger.design.flatMap((d) => d.units).filter((u) => through.includes(u.header.milestone)),
69
83
  ...ledger.items
70
- .filter((c) => c.data.milestone === m && !finished.includes(c.data.status))
84
+ .filter((c) => through.includes(c.data.milestone) && !finished.includes(c.data.status))
71
85
  .map((c) => ({ id: c.data.id })),
72
86
  ].map((x) => x.id);
73
87
 
@@ -76,10 +90,11 @@ const CRITERIA = {
76
90
  : [null, `nothing open carries milestone ${m}: check by hand it is done, not untagged`];
77
91
  },
78
92
  // Feature complete: a live feature of this milestone, or one with no milestone at all, is open.
79
- 'features-done': (ledger, live, phase) => {
93
+ 'features-done': (ledger, live, phase, order) => {
80
94
  const m = milestoneOf(phase);
95
+ const through = [...throughMilestone(phase, order), null, undefined];
81
96
  const open = ledger.items
82
- .filter((c) => c.data.type === 'feature' && [m, null, undefined].includes(c.data.milestone))
97
+ .filter((c) => c.data.type === 'feature' && through.includes(c.data.milestone))
83
98
  .map((c) => c.data.id);
84
99
 
85
100
  return [
@@ -187,8 +202,11 @@ export async function phaseStatus(projectDir) {
187
202
  const { phases, at, live } = await load(projectDir);
188
203
  const phase = phases[at];
189
204
  const ledger = await buildLedger(projectDir);
205
+ const order = ((await gameMilestones(path.join(path.resolve(projectDir), 'gcf'))) ?? []).map(
206
+ (m) => m.name,
207
+ );
190
208
  const criteria = phase.exit.map((name) => {
191
- const [met, detail] = CRITERIA[name](ledger, live, phase);
209
+ const [met, detail] = CRITERIA[name](ledger, live, phase, order);
192
210
 
193
211
  return { name, met, detail };
194
212
  });