gcf-aif-ext 0.29.0 → 0.29.2

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.
Files changed (50) hide show
  1. package/commands/gcf.js +114 -57
  2. package/extension.json +1 -1
  3. package/hooks/pre-commit.js +2 -0
  4. package/lib/agent-permissions.js +7 -4
  5. package/lib/audit-core.js +28 -18
  6. package/lib/board.js +1 -1
  7. package/lib/build-queue.js +5 -2
  8. package/lib/changes.js +1 -0
  9. package/lib/commit-files.js +2 -1
  10. package/lib/commit-move.js +114 -0
  11. package/lib/config-doc.js +22 -0
  12. package/lib/config-set.js +34 -39
  13. package/lib/design-check.js +8 -3
  14. package/lib/design-parts.js +123 -74
  15. package/lib/devices.js +5 -9
  16. package/lib/edits.js +7 -3
  17. package/lib/frozen.js +24 -0
  18. package/lib/gate.js +1 -1
  19. package/lib/gates.js +2 -1
  20. package/lib/gcf-paths.js +13 -10
  21. package/lib/git.js +19 -5
  22. package/lib/handoff.js +6 -1
  23. package/lib/history.js +1 -1
  24. package/lib/inbox-categories.js +37 -35
  25. package/lib/inbox.js +65 -34
  26. package/lib/integrate.js +7 -12
  27. package/lib/ledger.js +1 -1
  28. package/lib/lessons.js +4 -1
  29. package/lib/metrics.js +1 -0
  30. package/lib/migrate.js +1 -1
  31. package/lib/milestone-state.js +1 -1
  32. package/lib/phase.js +1 -1
  33. package/lib/pillars.js +1 -1
  34. package/lib/play-notes.js +4 -0
  35. package/lib/play-on.js +2 -1
  36. package/lib/play.js +36 -9
  37. package/lib/playtest-list.js +1 -1
  38. package/lib/push.js +9 -5
  39. package/lib/questions.js +4 -2
  40. package/lib/session-mark.js +21 -2
  41. package/lib/shelf.js +1 -0
  42. package/lib/systems-doc.js +31 -20
  43. package/lib/unit-ops.js +31 -109
  44. package/lib/validate-item.js +1 -2
  45. package/lib/verdict-fs.js +2 -1
  46. package/lib/verify-stamp.js +6 -1
  47. package/lib/verify.js +6 -2
  48. package/lib/work-ops.js +126 -86
  49. package/package.json +1 -1
  50. package/templates/agents-block.md +3 -0
package/lib/play.js CHANGED
@@ -13,20 +13,20 @@ import net from 'node:net';
13
13
  import os from 'node:os';
14
14
  import path from 'node:path';
15
15
  import YAML from 'yaml';
16
- import { configDoc } from './config-set.js';
16
+ 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
20
  import { alive, claimMainRun, MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
21
21
  import { atomicWrite, renameRetrying } from './safe-path.js';
22
- import { commitMove } from './unit-ops.js';
22
+ import { commitMove } from './commit-move.js';
23
23
  import { commandEnv } from './shell-env.js';
24
24
  import { failureOf, killTree, runCommand } from './verify.js';
25
25
  import { unplayedCloseCommit } from './verdict-fs.js';
26
26
  import { CANCELLED, cancelled, sweepTickets, ticketClose, ticketOpen } from './build-queue.js';
27
27
  import { readTicket, ticketSet, ticketsOf, waitTurn } from './build-queue.js';
28
28
  import { fileURLToPath } from 'node:url';
29
- import { DEVICE_ID_RE, devicesOf } from './devices.js';
29
+ import { DEVICE_ID_RE, targetDevices } from './devices.js';
30
30
 
31
31
  export const NOT_SET_UP =
32
32
  'how to play is not set up: ai-factory gcf playtest setup --build <cmd> --output <folder> ' +
@@ -101,6 +101,7 @@ const leftovers = /^.+\.(?:tmp|old)-(\d+)$/;
101
101
  const KEY_RE = /^[0-9a-f]{16}(?:-[a-z0-9]+(?:-[a-z0-9]+)*|\.main)?$/;
102
102
  const CLEAN_KEY = /^[0-9a-f]{16}$/;
103
103
  // A link that cannot be read: nobody knows which snapshot it holds, so it holds them all (d24).
104
+ /** @type {Readonly<{unread: true, snap?: undefined, released?: undefined, source?: undefined}>} */
104
105
  const UNREAD = Object.freeze({ unread: true });
105
106
 
106
107
  function readJson(file) {
@@ -380,7 +381,12 @@ const refreshed = (before, after) => [...after].some(([p, f]) => before.get(p)?.
380
381
 
381
382
  const gitOut = (cwd, args) => {
382
383
  // A big project lists far past the 1 MB a spawn holds by default; past it git's answer is lost.
383
- const res = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
384
+ const res = spawnSync('git', args, {
385
+ windowsHide: true,
386
+ cwd,
387
+ encoding: 'utf8',
388
+ maxBuffer: 256 * 1024 * 1024,
389
+ });
384
390
 
385
391
  return res.status === 0 ? res.stdout : null;
386
392
  };
@@ -497,10 +503,10 @@ async function holdCheckout(dir, id) {
497
503
  export function linksOf(projectDir) {
498
504
  const dir = path.resolve(projectDir);
499
505
  const links = new Map();
500
- for (const [folder, snaps] of [
506
+ for (const [folder, snaps] of /** @type {[string, boolean][]} */ ([
501
507
  [buildsOf(dir), false],
502
508
  [snapsOf(dir), true],
503
- ])
509
+ ]))
504
510
  for (const e of listOf(folder)) {
505
511
  const f = e.isFile() && slotOfFile(e.name, snaps);
506
512
  if (!f || f.ext !== (snaps ? 'link.json' : 'json')) continue;
@@ -699,7 +705,7 @@ async function refusedNow(dir, who, from, ticket) {
699
705
  * old one with its facts. A card whose status moved on meanwhile (a verdict needs no wait for a
700
706
  * build) takes nothing. `reuse`: a build of the same code that ended meanwhile serves this one, and
701
707
  * this one is thrown away (d23).
702
- * @returns {Promise<{refused: string} | {facts: object}>}
708
+ * @returns {Promise<{refused?: string, stopped?: boolean, facts?: Record<string, any>}>}
703
709
  */
704
710
  async function publish(dir, { slot, key, tmp, facts, source, from, reuse, ticket }) {
705
711
  const target = snapOf(dir, key);
@@ -958,7 +964,13 @@ async function claimTree(dir, ticket = null) {
958
964
  function gitMust(cwd, args) {
959
965
  // A caller's GIT_DIR or GIT_WORK_TREE (a hook) would point a clean at its own folder.
960
966
  const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^GIT_/.test(k)));
961
- const res = spawnSync('git', args, { cwd, env, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
967
+ const res = spawnSync('git', args, {
968
+ windowsHide: true,
969
+ cwd,
970
+ env,
971
+ encoding: 'utf8',
972
+ maxBuffer: 64 * 1024 * 1024,
973
+ });
962
974
  if (res.status !== 0)
963
975
  throw new Error(`git ${args[0]} in the build folder failed: ${(res.stderr || '').trim()}`);
964
976
  }
@@ -1330,6 +1342,21 @@ async function buildThenStart(dir, id, how, n) {
1330
1342
  return startNow(dir, id, how);
1331
1343
  }
1332
1344
 
1345
+ /**
1346
+ * `gcf playtest devices <target>`: what the target's script finds, each device placed under a row
1347
+ * of `plays_on` it fits, or why not (targetDevices).
1348
+ * @param {string} projectDir
1349
+ * @param {string} targetName
1350
+ * @param {{ ms?: number }} [opts]
1351
+ */
1352
+ export async function devicesOf(projectDir, targetName, opts) {
1353
+ const dir = path.resolve(projectDir);
1354
+ const play = playOf(await readConfig(path.join(dir, 'gcf')));
1355
+ if (!play) throw new Error(NOT_SET_UP);
1356
+
1357
+ return targetDevices(dir, play, targetName, opts);
1358
+ }
1359
+
1333
1360
  /**
1334
1361
  * The device a start plays on (docs/Handoff-Plan.md t8): an id of the target's `devices` answer
1335
1362
  * that fits a row and is ready. A target whose commands name `{device}` plays on none without one.
@@ -1576,7 +1603,7 @@ function heldBuild(dir, slot, links) {
1576
1603
  * a snapshot or an attempt of, by build then profile (docs/Handoff-Plan.md t17). A card back at
1577
1604
  * work has none to offer, unless one goes for it in its worktree right now. `links`: linksOf once
1578
1605
  * for a whole board.
1579
- * @returns {object[]}
1606
+ * @returns {Array<Record<string, any>>}
1580
1607
  */
1581
1608
  export function itemBuilds(projectDir, id, status, links = linksOf(projectDir)) {
1582
1609
  const dir = path.resolve(projectDir);
@@ -105,7 +105,7 @@ async function decisionList(root) {
105
105
  }
106
106
 
107
107
  const git = (projectDir, args) => {
108
- const res = spawnSync('git', args, { cwd: projectDir, encoding: 'utf8' });
108
+ const res = spawnSync('git', args, { windowsHide: true, cwd: projectDir, encoding: 'utf8' });
109
109
 
110
110
  return res.status === 0 ? res.stdout.trim() : null;
111
111
  };
package/lib/push.js CHANGED
@@ -5,7 +5,7 @@ import { spawn, spawnSync } from 'node:child_process';
5
5
  import { operationInProgress } from './git.js';
6
6
  import { claimMainRun, MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
7
7
  import { refusal } from './refusal.js';
8
- import { onWorkBranch } from './unit-ops.js';
8
+ import { onWorkBranch } from './commit-move.js';
9
9
  import { killTree } from './verify.js';
10
10
 
11
11
  export const NET_TIMEOUT_MS = 90_000;
@@ -16,6 +16,7 @@ const RS = '\x1e';
16
16
 
17
17
  const git = (dir, args, opts = {}) =>
18
18
  spawnSync('git', ['-c', 'core.quotePath=false', ...args], {
19
+ windowsHide: true,
19
20
  cwd: dir,
20
21
  encoding: 'utf8',
21
22
  ...opts,
@@ -146,7 +147,8 @@ function outOf(dir, range) {
146
147
  .filter(Boolean)
147
148
  .map((rec) => {
148
149
  const [hash, subject, by = ''] = rec.split(FS);
149
- const named = by.trim().split(',').at(-1);
150
+ // A split gives one part at least.
151
+ const named = /** @type {string} */ (by.trim().split(',').at(-1));
150
152
 
151
153
  return { hash, subject, by: BY.includes(named) ? named : 'operator' };
152
154
  });
@@ -301,7 +303,8 @@ export async function pushBranch(dir, { remote, timeoutMs = NET_TIMEOUT_MS } = {
301
303
  const branch = refuseWhereNoPush(dir, 'push');
302
304
  const t = targetOf(dir, branch, remote);
303
305
  const before = hashOf(dir, t.track);
304
- const to = hashOf(dir, 'HEAD');
306
+ // refuseWhereNoPush refused a branch with no commit.
307
+ const to = /** @type {string} */ (hashOf(dir, 'HEAD'));
305
308
  const pushed = count(
306
309
  dir,
307
310
  before ? ['HEAD', `^${before}`] : ['HEAD', '--not', `--remotes=${t.remote}`],
@@ -362,8 +365,9 @@ export async function pullBranch(dir, { remote, timeoutMs = NET_TIMEOUT_MS } = {
362
365
  timeoutMs,
363
366
  );
364
367
  if (f.status !== 0) throw netFailure(f, t, 'pull', timeoutMs);
365
- const theirs = hashOf(dir, t.track);
366
- const head = hashOf(dir, 'HEAD');
368
+ // The fetch wrote the tracking ref; refuseWhereNoPush refused a branch with no commit.
369
+ const theirs = /** @type {string} */ (hashOf(dir, t.track));
370
+ const head = /** @type {string} */ (hashOf(dir, 'HEAD'));
367
371
  const base = { remote: t.remote, branch, upstream: t.short, from: head.slice(0, 7) };
368
372
  const ancestor = (a, b) => git(dir, ['merge-base', '--is-ancestor', a, b]).status === 0;
369
373
  if (ancestor(theirs, head)) return { ...base, to: head.slice(0, 7), pulled: 0 };
package/lib/questions.js CHANGED
@@ -6,7 +6,7 @@ import { readFile } from 'node:fs/promises';
6
6
  import { existsSync } from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { atomicWrite } from './safe-path.js';
9
- import { commitMove } from './unit-ops.js';
9
+ import { commitMove } from './commit-move.js';
10
10
  import { locked } from './main-lock.js';
11
11
  import { blockEnd, fieldOf, indentOf } from './question-fields.js';
12
12
 
@@ -58,6 +58,7 @@ function recordsOf(text) {
58
58
  /**
59
59
  * Every question: id, class, the question, the proposed answer, the ids it blocks and the
60
60
  * human's answer, each null when the record has none.
61
+ * @returns {Promise<Array<{id: string} & Record<string, string | null>>>}
61
62
  */
62
63
  export async function listQuestions(root) {
63
64
  const file = fileOf(root);
@@ -164,7 +165,8 @@ export async function appendQuestions(root, records) {
164
165
  let text = existsSync(file) ? await readFile(file, 'utf8') : '';
165
166
  const ids = [];
166
167
  for (const r of records) {
167
- if (!['D1', 'D2'].includes(r.class)) throw new Error('a question record is class D1 or D2');
168
+ if (!(/** @type {unknown[]} */ (['D1', 'D2']).includes(r.class)))
169
+ throw new Error('a question record is class D1 or D2');
168
170
  if (!oneLine(r.question)) throw new Error('a question record needs its question');
169
171
  const next = withRecord(text, r);
170
172
  ids.push(next.id);
@@ -6,9 +6,9 @@
6
6
  // session that stopped: the item reads as not running again. The mark names its owner, so a
7
7
  // second session cannot take an item the first one works.
8
8
  import { existsSync, readdirSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs';
9
- import { mkdir, writeFile } from 'node:fs/promises';
9
+ import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
10
+ import { spawnSync } from 'node:child_process';
10
11
  import path from 'node:path';
11
- import { excludeSession } from './integrate.js';
12
12
  import { alive, withMainLock } from './main-lock.js';
13
13
  import { enterFolder } from './shelf.js';
14
14
 
@@ -19,6 +19,25 @@ export const SESSION_TTL_MS = 120 * 60_000;
19
19
  const markOf = (projectDir, id) =>
20
20
  path.join(path.resolve(projectDir), '.gcf-session', 'runs', `${id}.session`);
21
21
 
22
+ /** `.gcf-session/` stays out of `git status` without a tracked .gitignore change. */
23
+ export async function excludeSession(projectDir) {
24
+ const res = spawnSync('git', ['rev-parse', '--git-common-dir'], {
25
+ windowsHide: true,
26
+ cwd: projectDir,
27
+ encoding: 'utf8',
28
+ });
29
+ if (res.status !== 0)
30
+ throw new Error(
31
+ `git rev-parse --git-common-dir failed: ${(res.stderr || res.stdout || '').trim()}`,
32
+ );
33
+ const common = path.resolve(projectDir, res.stdout.trim());
34
+ const file = path.join(common, 'info', 'exclude');
35
+ const text = existsSync(file) ? await readFile(file, 'utf8') : '';
36
+ if (text.split(/\r?\n/).includes('/.gcf-session/')) return;
37
+ await mkdir(path.dirname(file), { recursive: true });
38
+ await appendFile(file, `${text && !text.endsWith('\n') ? '\n' : ''}/.gcf-session/\n`);
39
+ }
40
+
22
41
  /**
23
42
  * Who works an item: a harness run (`GCF_RUN_OWNER`, which its agent sessions inherit, a fresh
24
43
  * one after a handoff included), else the Claude Code session; null when neither is known.
package/lib/shelf.js CHANGED
@@ -41,6 +41,7 @@ const IDENT = { name: 'gcf', email: 'gcf@localhost' };
41
41
  */
42
42
  function git(dir, args, { env = {}, input } = {}) {
43
43
  const r = spawnSync('git', args, {
44
+ windowsHide: true,
44
45
  cwd: dir,
45
46
  encoding: 'utf8',
46
47
  input,
@@ -39,33 +39,38 @@ export function blocksOf(text, { raw = false } = {}) {
39
39
  });
40
40
  }
41
41
 
42
+ /** Block `at` of `lines` set to `rendered` in place. */
43
+ function setBlockAt(lines, at, rendered) {
44
+ // A dropped block takes one of the blank lines around it along.
45
+ const drop = !rendered.length && !lines[at.start - 2]?.trim() && !lines[at.end]?.trim();
46
+
47
+ return [...lines.slice(0, at.start - 1), ...rendered, ...lines.slice(at.end + (drop ? 1 : 0))];
48
+ }
49
+
50
+ /** `rendered` as the first block of `lines`, the blocks there after it. */
51
+ function firstBlock(lines, blocks, rendered, tight) {
52
+ if (blocks.length) return [...rendered, ...(tight(blocks[0]) ? [] : ['']), ...lines];
53
+ // A body of words with no block keeps them, over the new one.
54
+ const last = lines.findLastIndex((l) => l.trim());
55
+
56
+ return last < 0 ? rendered : [...lines.slice(0, last + 1), '', ...rendered, ''];
57
+ }
58
+
42
59
  /**
43
60
  * `lines` with block `spec` set to `rendered`: in place, or where the field order puts it.
44
61
  * `raw`: as blocksOf's, a comment or fence closing the block before stays above the new one.
45
62
  */
46
- export function putBlock(lines, specs, spec, rendered, { raw = false } = {}) {
63
+ export function putBlock(lines, specs, spec, { rendered, raw = false }) {
47
64
  const blocks = blocksOf(lines.join('\n'), { raw });
48
65
  const at = blocks.find((b) => b.key === spec.key);
49
- if (at) {
50
- // A dropped block takes one of the blank lines around it along.
51
- const drop = !rendered.length && !lines[at.start - 2]?.trim() && !lines[at.end]?.trim();
52
-
53
- return [...lines.slice(0, at.start - 1), ...rendered, ...lines.slice(at.end + (drop ? 1 : 0))];
54
- }
55
-
66
+ if (at) return setBlockAt(lines, at, rendered);
56
67
  if (!rendered.length) return lines;
57
68
  const order = specs.map((s) => s.key);
58
69
  const header = (b) => Boolean(specs.find((s) => s.key === b?.key)?.header);
59
70
  // Header fields stand line under line; a block stands apart from its neighbours.
60
71
  const tight = (b) => Boolean(spec.header && header(b));
61
72
  const prev = blocks.filter((b) => order.indexOf(b.key) < order.indexOf(spec.key)).at(-1);
62
- if (!prev && blocks.length) return [...rendered, ...(tight(blocks[0]) ? [] : ['']), ...lines];
63
- if (!prev) {
64
- // A body of words with no block keeps them, over the new one.
65
- const last = lines.findLastIndex((l) => l.trim());
66
-
67
- return last < 0 ? rendered : [...lines.slice(0, last + 1), '', ...rendered, ''];
68
- }
73
+ if (!prev) return firstBlock(lines, blocks, rendered, tight);
69
74
 
70
75
  const tail = lines.slice(prev.end);
71
76
  const gap = tight(prev) ? [] : [''];
@@ -90,7 +95,7 @@ export function upsertBlock(rawBody, key, addLines, order) {
90
95
  const kept = existing.filter((l) => !/^- none\b/.test(l));
91
96
  // A key the profile does not know goes last, after every block it does.
92
97
  const specs = (order.includes(key) ? order : [...order, key]).map((k) => ({ key: k }));
93
- const lead = body.match(/^\n*/)[0];
98
+ const lead = /** @type {RegExpMatchArray} */ (body.match(/^\n*/))[0];
94
99
  const text = body.slice(lead.length);
95
100
  let lines = text.split('\n');
96
101
  // Out and back in: a block a hand left out of the profile's order moves to its place.
@@ -101,10 +106,16 @@ export function upsertBlock(rawBody, key, addLines, order) {
101
106
  const end = Math.max(at.end, ...itemsOf(prose, at.start).map((i) => i.line));
102
107
  lines = [...lines.slice(0, at.start - 1), ...lines.slice(end)];
103
108
  while (lines.length > 1 && !lines[0].trim()) lines.shift();
104
- while (lines.length > 1 && !lines.at(-1).trim() && !lines.at(-2).trim()) lines.pop();
109
+ while (lines.length > 1 && !lines[lines.length - 1].trim() && !lines[lines.length - 2].trim())
110
+ lines.pop();
105
111
  }
106
112
 
107
- const put = putBlock(lines, specs, { key }, [`${key}:`, ...kept, ...fresh], { raw: true });
113
+ const put = putBlock(
114
+ lines,
115
+ specs,
116
+ { key },
117
+ { rendered: [`${key}:`, ...kept, ...fresh], raw: true },
118
+ );
108
119
 
109
120
  return `${lead}${put.join('\n')}`.replace(/\n{3,}/g, '\n\n');
110
121
  }
@@ -143,9 +154,9 @@ export function blocksNamed(rawText) {
143
154
  export function replaceBlock(rawBody, key, rendered, order) {
144
155
  const body = lf(rawBody);
145
156
  const specs = (order.includes(key) ? order : [...order, key]).map((k) => ({ key: k }));
146
- const lead = body.match(/^\n*/)[0];
157
+ const lead = /** @type {RegExpMatchArray} */ (body.match(/^\n*/))[0];
147
158
  const lines = body.slice(lead.length).split('\n');
148
- const put = putBlock(lines, specs, { key }, rendered, { raw: true });
159
+ const put = putBlock(lines, specs, { key }, { rendered, raw: true });
149
160
 
150
161
  return `${lead}${put.join('\n')}`.replace(/\n{3,}/g, '\n\n');
151
162
  }
package/lib/unit-ops.js CHANGED
@@ -2,8 +2,7 @@
2
2
  // straight into tests and code, `drop` into the graveyard. Each one removes the section and its
3
3
  // backlog line in the same step, so an id never lives in two places (M12).
4
4
  import { readFile } from 'node:fs/promises';
5
- import { existsSync, readFileSync } from 'node:fs';
6
- import { spawnSync } from 'node:child_process';
5
+ import { existsSync } from 'node:fs';
7
6
  import path from 'node:path';
8
7
  import { serialize } from './frontmatter.js';
9
8
  import { CARD_TYPES, SLUG_RE, blockOrder, listOf } from './design.js';
@@ -11,12 +10,12 @@ import { buildLedger } from './ledger.js';
11
10
  import { cycleMessage, designCheck, dependsGraph, gameMilestones, pathTo } from './design-check.js';
12
11
  import { atomicWrite, withFileRollback } from './safe-path.js';
13
12
  import { writeIndex } from './index-gen.js';
14
- import { operationInProgress, commitPaths, dirtyGcf, dirtyRefusal } from './git.js';
15
13
  import { upsertBlock, openSystemDoc } from './systems-doc.js';
16
14
  import { buryLine, recordLine } from './verdict-fs.js';
17
15
  import { defaultGate } from './validate-item.js';
18
16
  import { refuseByPhase } from './phase.js';
19
- import { locked, withMainLock } from './main-lock.js';
17
+ import { locked } from './main-lock.js';
18
+ import { commitMove } from './commit-move.js';
20
19
 
21
20
  /** A design file's text without the `## <id>` section. */
22
21
  export function removeUnit(text, id) {
@@ -183,6 +182,27 @@ function refuseUnready(units, summaries) {
183
182
  }
184
183
  }
185
184
 
185
+ // A child of a live feature is played with the feature's milestone unless told otherwise.
186
+ const givenMilestone = (ledger, feature, milestone) =>
187
+ milestone ?? (feature ? ledger.item(feature)?.data.milestone : null) ?? null;
188
+
189
+ /** The feature item `units` go under, new or live, refused when one of them waits for it. */
190
+ function featureWrite(ledger, root, units, { feature, ids, names, milestone, today }) {
191
+ const systems = units.flatMap((u) => listOf(u.header.system)).filter((s) => s !== 'TBD');
192
+ // A new feature gets the milestone its units are played with: the given one, else theirs.
193
+ const own = milestone ?? [...new Set(names.values())].find(Boolean) ?? null;
194
+ const write = featureFor(ledger, root, {
195
+ id: feature,
196
+ unitIds: ids,
197
+ systems,
198
+ today,
199
+ milestone: own,
200
+ });
201
+ refuseFeatureCycle(ledger, feature, units);
202
+
203
+ return write;
204
+ }
205
+
186
206
  /**
187
207
  * Take ready design units into work: each section becomes gcf/work/<id>.md with the same body.
188
208
  * One unit stands alone; `feature` groups them under a feature item, new or live. No commit —
@@ -198,9 +218,11 @@ export async function takeUnits(
198
218
  const ledger = await buildLedger(projectDir);
199
219
  const units = ids.map((id) => designUnitOf(ledger, id));
200
220
  refuseUnready(units, (await designCheck(projectDir)).units);
201
- // A child of a live feature is played with the feature's milestone unless told otherwise.
202
- const given = milestone ?? (feature ? ledger.item(feature)?.data.milestone : null) ?? null;
203
- const names = milestonesOf(units, given, await gameMilestones(root));
221
+ const names = milestonesOf(
222
+ units,
223
+ givenMilestone(ledger, feature, milestone),
224
+ await gameMilestones(root),
225
+ );
204
226
  for (const u of units) await refuseByPhase(projectDir, u.header.type, u.header.reopens ?? null);
205
227
  if (feature && !ledger.item(feature)) await refuseByPhase(projectDir, 'feature');
206
228
  const writes = units.map((unit) => ({
@@ -212,15 +234,8 @@ export async function takeUnits(
212
234
  }));
213
235
  for (const w of writes)
214
236
  if (existsSync(w.file)) throw new Error(`gcf/work/${path.basename(w.file)} already exists`);
215
- if (feature) {
216
- const systems = units.flatMap((u) => listOf(u.header.system)).filter((s) => s !== 'TBD');
217
- // A new feature gets the milestone its units are played with: the given one, else theirs.
218
- const own = milestone ?? [...new Set(names.values())].find(Boolean) ?? null;
219
- writes.push(
220
- featureFor(ledger, root, { id: feature, unitIds: ids, systems, today, milestone: own }),
221
- );
222
- refuseFeatureCycle(ledger, feature, units);
223
- }
237
+ if (feature)
238
+ writes.push(featureWrite(ledger, root, units, { feature, ids, names, milestone, today }));
224
239
 
225
240
  const paths = units.map((u) => basePaths(root, u));
226
241
  const touched = [
@@ -237,99 +252,6 @@ export async function takeUnits(
237
252
  return { items: writes.map((w) => `gcf/work/${path.basename(w.file)}`) };
238
253
  }
239
254
 
240
- /** A file's text at a git revision spec (`HEAD:./x`, `:./x` for the index), '' when absent. */
241
- export function gitText(projectDir, spec) {
242
- const res = spawnSync('git', ['show', spec], { cwd: projectDir, encoding: 'utf8' });
243
-
244
- return res.status === 0 ? res.stdout : '';
245
- }
246
-
247
- /**
248
- * True when `file` differs from HEAD in the index or on disk. Line endings do not count: a file
249
- * stored with CRLF and checked out with LF is not an edit.
250
- */
251
- function uncommitted(projectDir, file) {
252
- const rel = `./${path.relative(projectDir, file).replaceAll('\\', '/')}`;
253
- const norm = (t) => String(t).replace(/\r\n/g, '\n').trimEnd();
254
- const head = norm(gitText(projectDir, `HEAD:${rel}`));
255
- const disk = norm(existsSync(file) ? readFileSync(file, 'utf8') : '');
256
-
257
- return head !== norm(gitText(projectDir, `:${rel}`)) || head !== disk;
258
- }
259
-
260
- /**
261
- * Run a move that ends with its fixed-format commit, all of it or none of it. The commit takes
262
- * whole files and deletes the unit's section, so any uncommitted edit in them refuses the move
263
- * up front — an answer in the unit itself included: it would leave in a commit that never held
264
- * it, and no history would keep it. `inputs` are the item files the move reads and rewrites:
265
- * their own uncommitted edits (an answer, a live: delta) ride along on purpose.
266
- * @param {string} projectDir
267
- * @param {string} message
268
- * `key` is the domain's move key and `items` the ids it touched: the commit's trailers.
269
- * @param {{files: string[], mutate: () => Promise<void>, commit: boolean, inputs?: string[],
270
- * key?: string, items?: string[]}} move
271
- */
272
- /** A worktree of the integrator (Methodology §7): its gcf/ state is main's to move. */
273
- export const onWorkBranch = (projectDir) =>
274
- /^work\//.test(
275
- spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
276
- cwd: projectDir,
277
- encoding: 'utf8',
278
- }).stdout?.trim() ?? '',
279
- );
280
-
281
- export async function commitMove(projectDir, message, move) {
282
- // A move that commits holds the main lock while it writes and commits (Methodology §7).
283
- return move.commit
284
- ? withMainLock(projectDir, () => record(projectDir, message, move))
285
- : record(projectDir, message, move);
286
- }
287
-
288
- async function record(
289
- projectDir,
290
- message,
291
- { files, mutate, commit, inputs = [], key, items, proposal },
292
- ) {
293
- if (commit && onWorkBranch(projectDir))
294
- throw new Error(
295
- `cannot record ${message} on a work/ branch: a worktree records no move — the run ` +
296
- 'leaves .gcf-session/outcome.json, and the main checkout records it',
297
- );
298
- const busy = commit ? operationInProgress(projectDir) : null;
299
- if (busy) throw new Error(`cannot record ${message} while ${busy} is in progress`);
300
- const dirty = commit
301
- ? files.filter((f) => !inputs.includes(f) && uncommitted(projectDir, f))
302
- : [];
303
- if (dirty.length) {
304
- const rels = dirty.map((f) => path.relative(projectDir, f).replaceAll('\\', '/'));
305
- // The whole of gcf/'s edits, not only these: the gate would refuse the next one at once.
306
- // Only when that set holds them all: a move's own file outside it (an archived plan) is no
307
- // edit `gcf edits` takes, and a Commit of the rest would be refused again.
308
- const all = dirtyGcf(projectDir, inputs);
309
- throw dirtyRefusal(
310
- rels.every((r) => all.includes(r)) ? all : [],
311
- `commit or stash these first (an answered unit is committed before its move), ` +
312
- `${message} would carry them: ${rels.join(', ')}`,
313
- );
314
- }
315
-
316
- const root = path.join(path.resolve(projectDir), 'gcf');
317
- const touched = [...files, path.join(root, 'INDEX.md')];
318
- /** @type {string | null} */
319
- let hash = null;
320
- await withFileRollback(
321
- touched,
322
- async () => {
323
- await mutate();
324
- await writeIndex(root);
325
- if (commit) hash = commitPaths(projectDir, message, touched, { key, items, proposal });
326
- },
327
- { gitCwd: commit ? path.resolve(projectDir) : null },
328
- );
329
-
330
- return hash;
331
- }
332
-
333
255
  /**
334
256
  * A hard unit is built and its tests are green: it leaves design/ without a work item. A line
335
257
  * every future reader of the subsystem must remember goes to the systems doc's `constraints:`.
@@ -207,8 +207,7 @@ const RULES = {
207
207
  nullable((x) => ['main', 'worktree'].includes(x))(v) || 'run_mode must be main | worktree',
208
208
  skip_gates: (v) => typeof v === 'boolean' || 'skip_gates must be true or false',
209
209
  gate_why: (v) => nullable(isText)(v) || 'gate_why must be text or null',
210
- play_on: (v) =>
211
- (Array.isArray(v) && v.every(isText)) || 'play_on must list names of play.builds',
210
+ play_on: (v) => (Array.isArray(v) && v.every(isText)) || 'play_on must list names of play.builds',
212
211
  version: (v) =>
213
212
  nullable((x) => typeof x === 'string' && /^\S+$/.test(x))(v) ||
214
213
  'version must be one word of text (quote a number: "1.0")',
package/lib/verdict-fs.js CHANGED
@@ -103,7 +103,7 @@ export function unplayedCloseCommit(projectDir, id) {
103
103
  const log = spawnSync(
104
104
  'git',
105
105
  ['log', '-1', '--format=%H', '--fixed-strings', `--grep=gcf(close): ${id} → unplayed`],
106
- { cwd: projectDir, encoding: 'utf8' },
106
+ { windowsHide: true, cwd: projectDir, encoding: 'utf8' },
107
107
  );
108
108
 
109
109
  return (log.status === 0 && log.stdout.trim()) || null;
@@ -113,6 +113,7 @@ export function unplayedCloseCommit(projectDir, id) {
113
113
  export function fileAt(projectDir, rev, file) {
114
114
  const rel = path.relative(projectDir, file).replace(/\\/g, '/');
115
115
  const show = spawnSync('git', ['show', `${rev}:${rel}`], {
116
+ windowsHide: true,
116
117
  cwd: projectDir,
117
118
  encoding: 'utf8',
118
119
  maxBuffer: 64 * 1024 * 1024,
@@ -16,7 +16,12 @@ const stampFile = (projectDir, id) =>
16
16
  path.join(path.resolve(projectDir), '.gcf-session', 'runs', `${id}.verified`);
17
17
 
18
18
  const git = (projectDir, args, env = {}) =>
19
- spawnSync('git', args, { cwd: projectDir, encoding: 'utf8', env: { ...process.env, ...env } });
19
+ spawnSync('git', args, {
20
+ windowsHide: true,
21
+ cwd: projectDir,
22
+ encoding: 'utf8',
23
+ env: { ...process.env, ...env },
24
+ });
20
25
 
21
26
  /**
22
27
  * The git tree of the project's code as it is on disk, committed or not, new files included
package/lib/verify.js CHANGED
@@ -27,7 +27,7 @@ function parents() {
27
27
  return [];
28
28
  }
29
29
  });
30
- const res = spawnSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8' });
30
+ const res = spawnSync('ps', ['-A', '-o', 'pid=,ppid='], { windowsHide: true, encoding: 'utf8' });
31
31
 
32
32
  return (res.stdout ?? '')
33
33
  .split('\n')
@@ -54,7 +54,10 @@ const signal = (p, sig) => {
54
54
  */
55
55
  export function killTree(pid) {
56
56
  if (process.platform === 'win32') {
57
- spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
57
+ spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], {
58
+ windowsHide: true,
59
+ stdio: 'ignore',
60
+ });
58
61
 
59
62
  return;
60
63
  }
@@ -87,6 +90,7 @@ function stopChildren(doomed) {
87
90
  export function runCommand(cmd, cwd, stdio, ms) {
88
91
  let child;
89
92
  const done = new Promise((resolve) => {
93
+ // No windowsHide: the DoD's output goes to the operator's stderr; a hidden console loses it.
90
94
  child = spawn(cmd, { cwd, shell: true, stdio, env: commandEnv() });
91
95
  let timedOut = false;
92
96
  const timer =