gcf-aif-ext 0.25.0 → 0.26.1

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
@@ -338,7 +338,7 @@ The run layer of the methodology. Update both extensions together — `gcf-harne
338
338
  - `gcf phase` and `gcf phase next [--reason]` — the project phase (prototype → vertical-slice → alpha → beta → release → live), kept as `phase:` in the `LIVE.md` frontmatter, with exit criteria checked in code. `item new` and `take` refuse a type the phase does not take. **A project with no phase yet is in prototype, and a prototype takes no `asset` item**: move the phase on (`gcf phase next --reason "…"`) if your game is past it. A `phases:` list in `config.yml` replaces the set.
339
339
  - A release item carries `version:` and `channel:` (`item new <id> --type release --release 1.0.0 --channel steam`); its end writes the `release:` block of `LIVE.md`. `item new --milestone <name>` tags an item with a milestone of `game.md` (any slug without `game.md`); `design check` reports (does not block) an item whose milestone `game.md` does not list, and the board read gives the list as `design.milestones`.
340
340
  - `gcf playtest session` — where main stands and a checklist per item: its build, what to check, how to get there, what to feel.
341
- - `gcf playtest build <id> [--from <worktree>]`, `start <id> --target <name>`, `stop`, `status`, `setup` — a card's own build under `.gcf-session/builds/<id>/` and its player, from `play:` in `gcf/config.yml`; a verdict stops the player and removes the build.
341
+ - `gcf playtest build <id> [--from <worktree>] [--fresh]`, `build --main [--fresh]`, `start <id>|--main --target <name>`, `stop`, `status`, `setup` — one build per code under `.gcf-session/snaps/<key>/`, held by a card's link `.gcf-session/builds/<id>.json` or the checkout's `snaps/main.link.json`, and its player, from `play:` in `gcf/config.yml`; a verdict stops the card's player and removes the build once no other card holds it. `setup` refuses an output git does not ignore. On Windows the project's commands (`play:`, `dod.*`) run with Git's `bin` first in PATH, so `bash` is Git's, not System32's WSL launcher. The deny group `run-play` keeps a run's agent from building; a chat thread may build on the human's ask.
342
342
  - `gcf worktree <id>`, `gcf verify <id> --mark`, `gcf integrate [<id>…]` — an item in its own worktree, the `GCF-Verified` trailer, the merge into main and the item's move. Every committed move now holds `.gcf-session/main.lock`.
343
343
  - `gcf board [--json]` — everything a board shows in one read.
344
344
 
package/commands/gcf.js CHANGED
@@ -467,11 +467,18 @@ function registerPlaytest(gcf) {
467
467
  registerPlay(playtest);
468
468
  }
469
469
 
470
+ /** Whether a play command means the checkout: exactly one of a card's id and `--main`. */
471
+ function oneOf(id, main) {
472
+ if (Boolean(id) === Boolean(main)) throw new Error('name a card or --main, not both or neither');
473
+
474
+ return Boolean(main);
475
+ }
476
+
470
477
  /** What `playtest start` says: the words to open it by, and what is left running. */
471
478
  const startLine = (r) =>
472
479
  r.state === 'running'
473
- ? `playing ${r.id} on ${r.target} (pid ${r.pid}): ${r.open}`
474
- : `launched ${r.id} on ${r.target}: ${r.open}`;
480
+ ? `playing ${r.id ?? 'main'} on ${r.target} (pid ${r.pid}): ${r.open}`
481
+ : `launched ${r.id ?? 'main'} on ${r.target}: ${r.open}`;
475
482
 
476
483
  /** The player's line and the targets of `playtest status`. */
477
484
  function statusText(s) {
@@ -480,46 +487,64 @@ function statusText(s) {
480
487
 
481
488
  return [
482
489
  s.running
483
- ? `playing ${s.running.id} on ${s.running.target}: ${s.running.open}`
490
+ ? `playing ${s.running.id ?? 'main'} on ${s.running.target}: ${s.running.open}`
484
491
  : 'no player is running',
485
492
  `targets: ${s.targets.map((t) => t.name).join(', ') || 'none'}`,
486
493
  ].join('\n');
487
494
  }
488
495
 
489
- /** A card's build to play and its player (docs/Play-Plan.md). */
490
- function registerPlay(playtest) {
491
- const jsonOf = (o) => o.json || playtest.opts().json;
496
+ /** A card's build to play, or the checkout's (docs/Play-Setup-Plan.md). */
497
+ function registerPlayBuild(playtest, jsonOf) {
492
498
  playtest
493
- .command('build <id>')
494
- .description("Build the game into the card's own snapshot; the old one stays if this fails")
499
+ .command('build [id]')
500
+ .description("Build a card's game, or the checkout's (--main); one snapshot per code")
501
+ .option('--main', 'the checkout with its uncommitted edits, not a card')
502
+ .option('--fresh', 'build even when a snapshot of this code is there, and replace it')
495
503
  .option('--from <worktree>', "the card's worktree, for a run whose code is not in main yet")
496
504
  .option('--json', 'machine output')
497
505
  .action(async (id, o) => {
498
- const r = await (await lib('play')).buildItem(process.cwd(), id, { from: o.from ?? null });
506
+ const play = await lib('play');
507
+ const fresh = Boolean(o.fresh);
508
+ const main = oneOf(id, o.main);
509
+ if (main && o.from) throw new Error("--from names a card's worktree: not with --main");
510
+ const r = main
511
+ ? await play.buildMain(process.cwd(), { fresh })
512
+ : await play.buildItem(process.cwd(), id, { from: o.from ?? null, fresh });
513
+ const who = id ?? 'main';
499
514
  out(jsonOf(o), r, (b) =>
500
515
  b.ok
501
- ? `built ${id} at ${b.commit ?? 'no commit'}, ${b.size} bytes` +
516
+ ? `built ${who} at ${b.commit?.slice(0, 7) ?? 'no commit'}, ${b.size} bytes` +
502
517
  (b.dirtied.length ? `\nthe build changed: ${b.dirtied.join(', ')}` : '')
503
- : `build of ${id} failed: ${b.problem}`,
518
+ : `build of ${who} failed: ${b.problem}`,
504
519
  );
505
520
  if (!r.ok) process.exitCode = 1;
506
521
  });
507
522
  playtest
508
- .command('start <id>')
509
- .description("Start the card's snapshot on a target: one player per project")
523
+ .command('start [id]')
524
+ .description("Start a card's snapshot, or the checkout's (--main), on a target: one player")
525
+ .option('--main', "the checkout's snapshot, not a card's")
510
526
  .requiredOption('--target <name>', 'a target of play.targets')
511
527
  .option('--json', 'machine output')
512
528
  .action(async (id, o) => {
513
- const r = await (await lib('play')).startPlay(process.cwd(), id, o.target);
529
+ const main = oneOf(id, o.main);
530
+ const r = await (await lib('play')).startPlay(process.cwd(), main ? null : id, o.target);
514
531
  out(jsonOf(o), r, startLine);
515
532
  });
533
+ }
534
+
535
+ /** The player and the project's play: setup (docs/Play-Plan.md). */
536
+ function registerPlay(playtest) {
537
+ const jsonOf = (o) => o.json || playtest.opts().json;
538
+ registerPlayBuild(playtest, jsonOf);
516
539
  playtest
517
540
  .command('stop')
518
541
  .description('Stop the running player')
519
542
  .option('--json', 'machine output')
520
543
  .action(async (o) => {
521
544
  const r = await (await lib('play')).stopPlayLocked(process.cwd());
522
- out(jsonOf(o), { stopped: r }, () => (r ? `stopped ${r.id}` : 'no player is running'));
545
+ out(jsonOf(o), { stopped: r }, () =>
546
+ r ? `stopped ${r.id ?? 'main'}` : 'no player is running',
547
+ );
523
548
  });
524
549
  playtest
525
550
  .command('status')
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.25.0",
4
+ "version": "0.26.1",
5
5
  "description": "Game Context Framework for AI Factory",
6
6
  "skills": [
7
7
  "skills/gcf-init",
@@ -197,10 +197,6 @@ export const DENY_GROUPS = [
197
197
  'ai-factory gcf permissions*',
198
198
  'ai-factory gcf config set*',
199
199
  'ai-factory gcf playtest setup*',
200
- // A build by an agent would take its unfinished work as a card's; a run's goes by the harness.
201
- 'ai-factory gcf playtest build*',
202
- 'ai-factory gcf playtest start*',
203
- 'ai-factory gcf playtest stop*',
204
200
  'ai-factory gcf hooks-install*',
205
201
  // A human's hand edits under gcf/: their unfinished work, not the agent's to keep or erase.
206
202
  'ai-factory gcf edits commit*',
@@ -220,6 +216,19 @@ export const DENY_GROUPS = [
220
216
  'ai-factory extension*',
221
217
  ),
222
218
  },
219
+ {
220
+ id: 'run-play',
221
+ label: "a run's agent building or starting the game: the harness builds it at the run's end",
222
+ on: true,
223
+ // A build in a run would take its unfinished work as a card's. The project chat's agent builds
224
+ // on the human's ask (docs/Play-Setup-Plan.md d32): its thread leaves these rules out.
225
+ run_only: true,
226
+ rules: shell(
227
+ 'ai-factory gcf playtest build*',
228
+ 'ai-factory gcf playtest start*',
229
+ 'ai-factory gcf playtest stop*',
230
+ ),
231
+ },
223
232
  {
224
233
  id: 'guards',
225
234
  label:
@@ -237,6 +246,7 @@ export const DENY_GROUPS = [
237
246
  '.gcf-session/handoff.json',
238
247
  // A card's build to play and the record of its player: only `gcf playtest` writes them.
239
248
  '.gcf-session/builds/**',
249
+ '.gcf-session/snaps/**',
240
250
  '.gcf-session/play.json',
241
251
  ),
242
252
  },
@@ -347,11 +357,14 @@ export function agentOf(config) {
347
357
  const allowed = rules(agent, 'allow').map(parseRule);
348
358
  const groups = DENY_GROUPS.map((g) => ({ id: g.id, label: g.label, on: chosen[g.id] ?? g.on }));
349
359
  // A group's rule names its group: a refusal in a chat says which group to turn off.
360
+ const own = extra.map(parseRule);
361
+ // A rule the operator also wrote is theirs for every agent: no `run_only` lets a thread past it.
362
+ const runOnly = (g, r) => g.run_only && !own.some((x) => sameRule(x, r));
350
363
  const denied = [
351
364
  ...DENY_GROUPS.filter((g, i) => groups[i].on).flatMap((g) =>
352
- g.rules.map((r) => ({ ...r, group: g.id })),
365
+ g.rules.map((r) => ({ ...r, group: g.id, ...(runOnly(g, r) ? { run_only: true } : {}) })),
353
366
  ),
354
- ...extra.map(parseRule),
367
+ ...own,
355
368
  ].filter((r, i, all) => all.findIndex((x) => sameRule(x, r)) === i);
356
369
 
357
370
  return {
package/lib/board.js CHANGED
@@ -27,7 +27,7 @@ import { designCheck, designUnits } from './design-check.js';
27
27
  import { designState } from './design-parts.js';
28
28
  import { gatePolicy } from './gates.js';
29
29
  import { milestoneState } from './milestone-state.js';
30
- import { buildOf, playFacts } from './play.js';
30
+ import { buildOf, linksOf, playFacts } from './play.js';
31
31
 
32
32
  // The version of the JSON below (Methodology §11): a board refuses one it does not know. Bump it
33
33
  // when a field changes meaning or goes away; a new field does not bump it.
@@ -321,7 +321,8 @@ async function attachmentsOf(projectDir, id) {
321
321
  }
322
322
 
323
323
  /** One item of the board. */
324
- async function itemOf(projectDir, c, { verified, shelved, ledger, harness, config }) {
324
+ async function itemOf(projectDir, c, { verified, shelved, ledger, harness, config, links }) {
325
+ const build = buildOf(projectDir, String(c.data.id), c.data.status, links);
325
326
  const id = String(c.data.id);
326
327
  // A trailer counts only while the item waits on main for its integrate.
327
328
  const ready = c.data.status === 'ready' && verified.has(id);
@@ -363,30 +364,27 @@ async function itemOf(projectDir, c, { verified, shelved, ledger, harness, confi
363
364
  running,
364
365
  verified: ready,
365
366
  harness,
366
- building: Boolean(buildOf(projectDir, id, c.data.status)?.building),
367
+ building: Boolean(build?.building),
367
368
  }),
368
369
  file: `gcf/work/${c.name}`,
369
370
  ...(await attachmentsOf(projectDir, id)),
370
371
  log: logOf(projectDir, id),
371
- // Its own build to play (docs/Play-Plan.md), null while it has none.
372
- build: buildOf(projectDir, id, c.data.status),
372
+ // Its build to play (docs/Play-Setup-Plan.md), null while it has none.
373
+ build,
373
374
  // Filled by board() from the inbox.
374
375
  lessons: 0,
375
376
  ...(await progress(projectDir, c)),
376
377
  };
377
378
  }
378
379
 
379
- export async function board(projectDir) {
380
- const root = path.join(path.resolve(projectDir), 'gcf');
381
- const ledger = await buildLedger(projectDir);
380
+ /** The board's items in run order, each with the time its wait began. */
381
+ async function itemsOf(projectDir, { ledger, harness, config }) {
382
382
  const verified = verifiedOf(projectDir);
383
383
  const shelved = shelvedCards(projectDir);
384
- const { extensions, error: extensionsError } = await extensionsOf(projectDir);
385
- const harness = hasHarness(extensions);
386
- const config = await readConfig(root);
384
+ const links = linksOf(projectDir);
387
385
  const items = [];
388
386
  for (const c of ledger.items)
389
- items.push(await itemOf(projectDir, c, { verified, shelved, ledger, harness, config }));
387
+ items.push(await itemOf(projectDir, c, { verified, shelved, ledger, harness, config, links }));
390
388
  inRunOrder(items);
391
389
  // When the wait began: the time of the commit `since` names (Board-PRD §13).
392
390
  const times = commitTimes(
@@ -394,6 +392,17 @@ export async function board(projectDir) {
394
392
  items.map((i) => i.since),
395
393
  );
396
394
  for (const i of items) i.since_at = times.get(i.since) ?? null;
395
+
396
+ return items;
397
+ }
398
+
399
+ export async function board(projectDir) {
400
+ const root = path.join(path.resolve(projectDir), 'gcf');
401
+ const ledger = await buildLedger(projectDir);
402
+ const { extensions, error: extensionsError } = await extensionsOf(projectDir);
403
+ const harness = hasHarness(extensions);
404
+ const config = await readConfig(root);
405
+ const items = await itemsOf(projectDir, { ledger, harness, config });
397
406
  const inbox = await listInbox(root);
398
407
  // Where agents struggle: the lessons in the inbox each item's sessions left. A request or a
399
408
  // finding about the item names it too: it is no lesson.
package/lib/domain.js CHANGED
@@ -484,6 +484,15 @@ const DESIGN_EDITS = [
484
484
  'gcf/INDEX.md',
485
485
  'gcf/design/**',
486
486
  ];
487
+ // What the agent of a play start does: it never asks the human for the commands.
488
+ const PLAY_SAY =
489
+ 'Set up how this game is played. Find in the project (AGENTS.md, its build and serve scripts) ' +
490
+ 'the one command that builds the game into a folder of the project that git ignores, and the ' +
491
+ 'command that starts it from that folder ({dir}) on a port ({port}); then call ' +
492
+ 'propose_play_setup with them. Do not ask me for the commands. If the project has no such ' +
493
+ 'command, or the folder is not ignored, propose a tech card with propose_item_new instead: one ' +
494
+ 'command builds the game into an ignored folder, one starts it with the folder and a port, ' +
495
+ 'AGENTS.md names both.';
487
496
  const STARTS = {
488
497
  vision: {
489
498
  label: 'Create with agent',
@@ -586,6 +595,22 @@ const STARTS = {
586
595
  say: 'Go through the TBDs of unit {unit} with me; take it into work only when I say so.',
587
596
  edits: DESIGN_EDITS,
588
597
  },
598
+ // How the game is played (docs/Play-Setup-Plan.md d18): the project knows its build and start
599
+ // commands, its agent finds them and proposes; the operator presses Make. No skill: the chat's.
600
+ // No edits: a build script is the project's code, it goes to a card of its own (d20).
601
+ 'play-setup': {
602
+ label: 'Set up with agent',
603
+ help: 'The agent finds how this project builds its game into a folder and starts it',
604
+ say: PLAY_SAY,
605
+ edits: [],
606
+ },
607
+ 'play-fix': {
608
+ label: 'Find again with agent',
609
+ help: 'The agent looks at the setup and its last failure again, and proposes a new one',
610
+ takes: 'text',
611
+ say: `${PLAY_SAY} The setup now and what went wrong: {text}`,
612
+ edits: [],
613
+ },
589
614
  };
590
615
 
591
616
  // The way from an empty project to its first work, in order: the board shows each step done or
@@ -741,9 +766,17 @@ const BLOCK_SPECS = {
741
766
  fields: [text('target', 'Where to play', { required: true })],
742
767
  propose: true,
743
768
  },
769
+ // The checkout as it is, hand edits too (d30): built when its code has no snapshot, then started.
770
+ 'play-main': {
771
+ label: 'play main',
772
+ help: 'Build the checkout as it is, uncommitted edits too, and start it on a target',
773
+ args: ['gcf', 'playtest', 'start', '--main', '--json'],
774
+ fields: [text('target', 'Where to play', { required: true })],
775
+ propose: true,
776
+ },
744
777
  'play-setup': {
745
778
  label: 'set up play',
746
- help: 'How this project builds and starts its game: a card keeps its own build to play',
779
+ help: 'How this project builds and starts its game: cards on the same code share one build',
747
780
  args: ['gcf', 'playtest', 'setup'],
748
781
  fields: [
749
782
  text('build', 'Build command'),
package/lib/play.js CHANGED
@@ -1,8 +1,11 @@
1
- // Playing a finished card (docs/Play-Plan.md): its build as a snapshot of its own under
2
- // `.gcf-session/builds/`, which no later run or build touches, and one running player per
3
- // project. How to build and start the game is the project's (`play:` in gcf/config.yml); the
4
- // commands are opaque here, so a browser, a phone and a desktop differ only by their words.
1
+ // Playing a finished card (docs/Play-Plan.md, docs/Play-Setup-Plan.md): a build is a snapshot of
2
+ // the code under `.gcf-session/snaps/<key>/`, which no later run or build touches; a card holds it
3
+ // by its link `.gcf-session/builds/<id>.json`, the checkout by `snaps/main.link.json`, and cards on
4
+ // the same code share one. One running player per project. How to build and start the game is the
5
+ // project's (`play:` in gcf/config.yml); the commands are opaque here, so a browser, a phone and a
6
+ // desktop differ only by their words.
5
7
  import { spawn, spawnSync } from 'node:child_process';
8
+ import { createHash } from 'node:crypto';
6
9
  import { closeSync, existsSync, openSync, readdirSync, readFileSync } from 'node:fs';
7
10
  import { lstatSync, renameSync, rmSync, writeFileSync } from 'node:fs';
8
11
  import { cp, mkdir, open, rm } from 'node:fs/promises';
@@ -17,6 +20,7 @@ import { buildLedger } from './ledger.js';
17
20
  import { alive, claimMainRun, MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
18
21
  import { atomicWrite, renameRetrying } from './safe-path.js';
19
22
  import { commitMove } from './unit-ops.js';
23
+ import { commandEnv } from './shell-env.js';
20
24
  import { failureOf, killTree, runCommand } from './verify.js';
21
25
 
22
26
  export const NOT_SET_UP =
@@ -30,15 +34,32 @@ const STOP_WAIT_MS = 15000;
30
34
  // A held file on Windows lets go a moment after its process ends.
31
35
  const RM = { recursive: true, force: true, maxRetries: 5, retryDelay: 200 };
32
36
 
37
+ // The checkout as it is ("Play main"): no item id, so no card's files can take its name.
38
+ const MAIN = ':main';
33
39
  const session = (dir) => path.join(dir, '.gcf-session');
34
40
  const buildsOf = (dir) => path.join(session(dir), 'builds');
35
- const snapshotOf = (dir, id) => path.join(buildsOf(dir), id);
36
- const factsOf = (dir, id) => path.join(buildsOf(dir), `${id}.json`);
37
- const attemptOf = (dir, id) => path.join(buildsOf(dir), `${id}.attempt.json`);
38
- const logOf = (dir, id) => path.join(buildsOf(dir), `${id}.log`);
41
+ const snapsOf = (dir) => path.join(session(dir), 'snaps');
42
+ const snapOf = (dir, key) => path.join(snapsOf(dir), key);
43
+ const snapFactsOf = (dir, key) => path.join(snapsOf(dir), `${key}.json`);
44
+ /** A holder's own files: a card's under `builds/`, the checkout's beside the snapshots. */
45
+ const ownOf = (dir, who, ext) =>
46
+ who === MAIN ? path.join(snapsOf(dir), `main.${ext}`) : path.join(buildsOf(dir), `${who}.${ext}`);
47
+ /** A holder as words, and in a file's name. */
48
+ const nameOf = (who) => (who === MAIN ? 'main' : who);
49
+ const linkOf = (dir, who) => ownOf(dir, who, who === MAIN ? 'link.json' : 'json');
50
+ const attemptOf = (dir, who) => ownOf(dir, who, 'attempt.json');
51
+ const logOf = (dir, who) => ownOf(dir, who, 'log');
39
52
  const playerFile = (dir) => path.join(session(dir), 'play.json');
40
53
  const playerLog = (dir) => path.join(session(dir), 'play.log');
41
54
  const leftovers = /^.+\.(?:tmp|old)-(\d+)$/;
55
+ /**
56
+ * A snapshot's name: the code's, and for a dirty tree also its holder's: `-<id>` for a card,
57
+ * `.main` for the checkout, which no card id can spell (a card may be called `main`).
58
+ */
59
+ const KEY_RE = /^[0-9a-f]{16}(?:-[a-z0-9]+(?:-[a-z0-9]+)*|\.main)?$/;
60
+ const CLEAN_KEY = /^[0-9a-f]{16}$/;
61
+ // A link that cannot be read: nobody knows which snapshot it holds, so it holds them all (d24).
62
+ const UNREAD = Object.freeze({ unread: true });
42
63
 
43
64
  function readJson(file) {
44
65
  try {
@@ -48,6 +69,8 @@ function readJson(file) {
48
69
  }
49
70
  }
50
71
 
72
+ const listOf = (folder) => (existsSync(folder) ? readdirSync(folder, { withFileTypes: true }) : []);
73
+
51
74
  /** A rename from a synchronous path: Windows holds a fresh file for a moment (a scanner). */
52
75
  function renameHeld(from, to) {
53
76
  for (let attempt = 1; ; attempt++) {
@@ -163,16 +186,49 @@ function treeOf(dir) {
163
186
  const refreshed = (before, after) => [...after].some(([p, f]) => before.get(p)?.stamp !== f.stamp);
164
187
 
165
188
  const gitOut = (cwd, args) => {
166
- const res = spawnSync('git', args, { cwd, encoding: 'utf8' });
189
+ // A big project lists far past the 1 MB a spawn holds by default; past it git's answer is lost.
190
+ const res = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
167
191
 
168
192
  return res.status === 0 ? res.stdout : null;
169
193
  };
170
194
 
195
+ // The framework's own files: no build's, so neither a change of them nor a commit of them makes
196
+ // another game. One list for the dirty check and the snapshot's key.
197
+ const NOT_CODE = ['gcf', 'GLOSSARY.md', '.gcf-session'];
198
+
199
+ /**
200
+ * The key of the code HEAD holds, the framework's files left out (d29), and of how it is built: a
201
+ * verdict or an inbox commit keeps it, a new `play.build` or `play.output` does not. Null with no
202
+ * commit. 16 hex: a path on Windows stays short. The top level alone: a folder's entry is the hash
203
+ * of all it holds, and every file the key leaves out is at the top.
204
+ */
205
+ function codeOf(cwd, play) {
206
+ const out = gitOut(cwd, ['ls-tree', '-z', 'HEAD']);
207
+ if (out === null) return null;
208
+ const code = out
209
+ .split('\0')
210
+ .filter(Boolean)
211
+ .filter((l) => !NOT_CODE.includes(l.slice(l.indexOf('\t') + 1)));
212
+
213
+ return createHash('sha256')
214
+ .update([...code, play.build, play.output].join('\0'))
215
+ .digest('hex')
216
+ .slice(0, 16);
217
+ }
218
+
219
+ /** The snapshot's key: the code's alone when the tree is clean, else its holder's own too. */
220
+ function keyOf(cwd, who, loose, play) {
221
+ const code = codeOf(cwd, play);
222
+ if (code && !loose.length) return code;
223
+
224
+ return `${code ?? '0'.repeat(16)}${who === MAIN ? '.main' : `-${who}`}`;
225
+ }
226
+
171
227
  /** What git sees changed or new, each path once; gcf/ and the run's own files are no build's. */
172
228
  function looseOf(cwd) {
173
229
  const out = gitOut(cwd, [
174
230
  ...['--no-optional-locks', 'status', '--porcelain', '-z', '-uall', '--', '.'],
175
- ...[':(exclude)gcf', ':(exclude)GLOSSARY.md', ':(exclude).gcf-session'],
231
+ ...NOT_CODE.map((n) => `:(exclude)${n}`),
176
232
  ]);
177
233
  const parts = (out ?? '').split('\0').filter(Boolean);
178
234
  const paths = [];
@@ -235,72 +291,148 @@ async function holdCheckout(dir, id) {
235
291
  }
236
292
 
237
293
  /**
238
- * Remove what no card needs any more: a snapshot marked released, the build of a card off the
239
- * board, leftovers of a dead process. Under the main lock, each `<id>.json` read again: a build
240
- * that published meanwhile wrote a new one. A held file waits for the next sweep; a card file that
241
- * cannot be read says nothing of who left the board, so nothing goes by it.
294
+ * Every holder's link: a card's id, or MAIN, to its link; UNREAD for one that cannot be read. A
295
+ * link of the old layout (a card's facts, no `snap`) holds nothing: a sweep takes it.
296
+ * @returns {Map<string, {snap?: string, released?: boolean, source?: string} | typeof UNREAD>}
242
297
  */
243
- async function sweep(dir) {
244
- const builds = buildsOf(dir);
245
- if (!existsSync(builds)) return;
246
- const ledger = await buildLedger(dir).catch(() => null);
247
- const ids = new Set();
248
- for (const e of readdirSync(builds)) {
249
- const left = leftovers.exec(e);
250
- if (left) {
251
- // Not awaited: the main lock is held here, and every move would wait for a big one.
252
- if (!alive(Number(left[1]))) void rm(path.join(builds, e), RM).catch(() => {});
253
- } else {
254
- const id = e.replace(/(\.attempt)?\.(json|log)$/, '');
255
- // A stray `.log` gives an empty id, whose snapshot path is the whole folder.
256
- if (isValidId(id)) ids.add(id);
257
- }
258
- }
298
+ export function linksOf(projectDir) {
299
+ const dir = path.resolve(projectDir);
300
+ const links = new Map();
301
+ const read = (who, file) => {
302
+ const link = readJson(file);
303
+ // A name that is no snapshot's would point a delete anywhere: such a link holds nothing.
304
+ const bad = link && typeof link.snap === 'string' && !KEY_RE.test(link.snap);
305
+ links.set(who, link === null ? UNREAD : bad ? { ...link, snap: null } : link);
306
+ };
259
307
 
260
- for (const id of ids) {
261
- const released = readJson(factsOf(dir, id))?.released === true;
262
- const gone =
263
- ledger !== null && !ledger.item(id) && !existsSync(path.join(dir, 'gcf', 'work', `${id}.md`));
264
- if (released || gone) removeBuild(dir, id, { all: gone });
308
+ for (const e of listOf(buildsOf(dir))) {
309
+ const id = e.isFile() && !e.name.endsWith('.attempt.json') && /^(.+)\.json$/.exec(e.name)?.[1];
310
+ if (id && isValidId(id)) read(id, path.join(buildsOf(dir), e.name));
265
311
  }
312
+
313
+ if (existsSync(linkOf(dir, MAIN))) read(MAIN, linkOf(dir, MAIN));
314
+
315
+ return links;
266
316
  }
267
317
 
268
- const building = (attempt) => attempt?.building === true && alive(attempt.pid);
318
+ const holds = (link, key) => link === UNREAD || (link.snap === key && link.released !== true);
319
+ /** Whether snapshot `key` has a holder: an unreleased link to it, or a link nobody can read. */
320
+ const held = (links, key) => [...links.values()].some((l) => holds(l, key));
269
321
 
270
322
  /**
271
- * Remove a card's snapshot, its facts last: a removal that failed halfway is repeated by a sweep.
323
+ * Remove snapshot `key`, its facts last: a removal that failed halfway is repeated by a sweep.
272
324
  * Under the main lock it only moves aside: a big one takes long to delete, and every move would
273
- * wait for it. A live attempt keeps its own file; `all` also takes the log of a card that left.
325
+ * wait for it. A player of it stops first: its files are going.
274
326
  */
275
- function removeBuild(dir, id, { all = false } = {}) {
276
- try {
277
- if (playerOf(dir)?.id === id) stopPlay(dir);
278
- const target = snapshotOf(dir, id);
279
- if (existsSync(target)) {
280
- const old = `${target}.old-${process.pid}`;
281
- rmSync(old, RM);
282
- renameHeld(target, old);
283
- // A failure leaves it to a sweep, once this process is gone.
284
- void rm(old, RM).catch(() => {});
327
+ function dropSnap(dir, key) {
328
+ // Only a snapshot's own name: `""` or `..` would take the whole folder or more.
329
+ if (!KEY_RE.test(key)) return;
330
+ if (playerOf(dir)?.snap === key) stopPlay(dir);
331
+ const target = snapOf(dir, key);
332
+ if (existsSync(target)) {
333
+ const old = `${target}.old-${process.pid}`;
334
+ rmSync(old, RM);
335
+ renameHeld(target, old);
336
+ // A failure leaves it to a sweep, once this process is gone.
337
+ void rm(old, RM).catch(() => {});
338
+ }
339
+
340
+ rmSync(snapFactsOf(dir, key), { force: true });
341
+ }
342
+
343
+ /** A holder's attempt goes with it, unless a build for it is under way right now. */
344
+ function dropAttempt(dir, who, { log = false } = {}) {
345
+ if (building(readJson(attemptOf(dir, who)))) return;
346
+ rmSync(attemptOf(dir, who), { force: true });
347
+ if (log) rmSync(logOf(dir, who), { force: true });
348
+ }
349
+
350
+ /**
351
+ * Point `who` at snapshot `key`; the snapshot it held before goes when nobody else holds it.
352
+ * Under the main lock.
353
+ */
354
+ function linkTo(dir, who, key, source) {
355
+ const was = linksOf(dir).get(who);
356
+ writeJsonSync(linkOf(dir, who), {
357
+ id: who === MAIN ? null : who,
358
+ snap: key,
359
+ at: new Date().toISOString(),
360
+ source,
361
+ });
362
+ if (was && was !== UNREAD && was.snap && was.snap !== key && !held(linksOf(dir), was.snap))
363
+ dropSnap(dir, was.snap);
364
+ }
365
+
366
+ /**
367
+ * Remove what nobody needs any more (d24): a released link, the link of a card off the board, a
368
+ * folder of the old layout, a snapshot nobody holds, leftovers of a dead process. Under the main
369
+ * lock. A held file waits for the next sweep; a card file that cannot be read says nothing of who
370
+ * left the board, so nothing goes by it; while a link cannot be read, no snapshot goes.
371
+ */
372
+ async function sweep(dir) {
373
+ const ledger = await buildLedger(dir).catch(() => null);
374
+ const ids = sweepFolders(dir);
375
+ const links = linksOf(dir);
376
+ const gone = (id) =>
377
+ ledger !== null && !ledger.item(id) && !existsSync(path.join(dir, 'gcf', 'work', `${id}.md`));
378
+ for (const id of ids) {
379
+ const link = links.get(id);
380
+ if (link === UNREAD) continue;
381
+ const left = gone(id);
382
+ if (left || (link && (link.released === true || typeof link.snap !== 'string'))) {
383
+ rmSync(linkOf(dir, id), { force: true });
384
+ if (left) dropAttempt(dir, id, { log: true });
285
385
  }
386
+ }
387
+
388
+ const now = linksOf(dir);
389
+ if ([...now.values()].includes(UNREAD)) return;
390
+ const keys = new Set(
391
+ listOf(snapsOf(dir))
392
+ .map((e) => e.name.replace(/\.json$/, ''))
393
+ .filter((k) => KEY_RE.test(k)),
394
+ );
395
+ for (const key of keys) if (!held(now, key)) dropSnap(dir, key);
396
+ }
397
+
398
+ /** A snapshot of the old layout goes; a player an older core started from it stops first. */
399
+ function dropOld(dir, id) {
400
+ const p = playerOf(dir);
401
+ if (p?.id === id && !p.snap) stopPlay(dir);
402
+ void rm(path.join(buildsOf(dir), id), RM).catch(() => {});
403
+ }
286
404
 
287
- rmSync(factsOf(dir, id), { force: true });
288
- if (!building(readJson(attemptOf(dir, id)))) {
289
- rmSync(attemptOf(dir, id), { force: true });
290
- if (all) rmSync(logOf(dir, id), { force: true });
405
+ /**
406
+ * Leftovers of a dead process go, and the folders of the old layout (`builds/<id>/`), which no
407
+ * link reaches. Not awaited: the main lock is held here, and every move would wait for a big one.
408
+ * @returns {Set<string>} the ids that have files under `builds/`
409
+ */
410
+ function sweepFolders(dir) {
411
+ const ids = new Set();
412
+ const drop = (folder, name) => void rm(path.join(folder, name), RM).catch(() => {});
413
+ for (const folder of [buildsOf(dir), snapsOf(dir)])
414
+ for (const e of listOf(folder)) {
415
+ const left = leftovers.exec(e.name);
416
+ if (left && !alive(Number(left[1]))) drop(folder, e.name);
417
+ if (left) continue;
418
+
419
+ if (folder !== buildsOf(dir)) continue;
420
+ if (e.isDirectory()) dropOld(dir, e.name);
421
+ const id = e.name.replace(/(\.attempt)?\.(json|log)$/, '');
422
+ if (e.isFile() && isValidId(id)) ids.add(id);
291
423
  }
292
424
 
293
- return null;
294
- } catch (e) {
295
- return `the build of ${id} stays on the disk for now: ${e.message}`;
296
- }
425
+ return ids;
297
426
  }
298
427
 
428
+ const building = (attempt) => attempt?.building === true && alive(attempt.pid);
429
+
299
430
  /**
300
- * The card's play has ended (a verdict, a drop): its player stops and its snapshot goes. After the
301
- * move's commit, so it never fails the move: the problem comes back as words, and the mark
302
- * `released` makes a later sweep repeat what a held file refused. A card that a tune sends back
303
- * stays on the board, and only the mark tells this snapshot from a fresh one.
431
+ * The card's play has ended (a verdict, a drop): its player stops and its link goes; its snapshot
432
+ * goes too when no other card holds it (d24). After the move's commit, so it never fails the move:
433
+ * the problem comes back as words, and the mark `released` makes a later sweep repeat what a held
434
+ * file refused. A card that a tune sends back stays on the board, and only the mark tells this link
435
+ * from a fresh one.
304
436
  * @returns {string | null}
305
437
  */
306
438
  export function releaseBuild(projectDir, id) {
@@ -308,54 +440,74 @@ export function releaseBuild(projectDir, id) {
308
440
  if (!isValidId(id)) return null;
309
441
  const dir = path.resolve(projectDir);
310
442
  try {
311
- const facts = readJson(factsOf(dir, id));
312
- if (facts) writeJsonSync(factsOf(dir, id), { ...facts, released: true });
313
- else if (existsSync(snapshotOf(dir, id)))
314
- writeJsonSync(factsOf(dir, id), { id, released: true });
443
+ if (playerOf(dir)?.id === id) stopPlay(dir);
444
+ const file = linkOf(dir, id);
445
+ const link = readJson(file);
446
+ if (link) writeJsonSync(file, { ...link, released: true });
447
+ rmSync(file, { force: true });
448
+ dropAttempt(dir, id);
449
+ if (typeof link?.snap === 'string' && !held(linksOf(dir), link.snap)) dropSnap(dir, link.snap);
315
450
  } catch (e) {
316
451
  return `the build of ${id} stays on the disk for now: ${e.message}`;
317
452
  }
318
453
 
319
- return removeBuild(dir, id);
454
+ return null;
320
455
  }
321
456
 
322
457
  /**
323
- * Put a finished build in its card's place, or throw and leave the old one with its facts. A card
324
- * whose status moved on meanwhile (a verdict needs no wait for a build) takes no snapshot.
458
+ * Put a finished build in place of snapshot `key` and point `who` at it, or throw and leave the old
459
+ * one with its facts. A card whose status moved on meanwhile (a verdict needs no wait for a build)
460
+ * takes nothing. `reuse`: a build of the same code that ended meanwhile serves this one, and this
461
+ * one is thrown away (d23).
462
+ * @returns {Promise<{refused: string} | {facts: object}>}
325
463
  */
326
- async function publish(dir, { id, tmp, facts, from }) {
327
- const target = snapshotOf(dir, id);
464
+ async function publish(dir, { who, key, tmp, facts, source, from, reuse }) {
465
+ const target = snapOf(dir, key);
328
466
  const old = `${target}.old-${process.pid}`;
329
- const refused = await withMainLock(dir, async () => {
330
- const problem = await statusProblem(dir, id, from);
331
- if (problem) return problem;
332
- if (playerOf(dir)?.id === id) stopPlay(dir);
467
+ const done = await withMainLock(dir, async () => {
468
+ if (who !== MAIN) {
469
+ const problem = await statusProblem(dir, who, from);
470
+ if (problem) return { refused: problem };
471
+ }
472
+
473
+ const there = reuse && readJson(snapFactsOf(dir, key));
474
+ if (there && existsSync(target) && held(linksOf(dir), key)) {
475
+ linkTo(dir, who, key, source);
476
+
477
+ return { facts: there };
478
+ }
479
+
480
+ if (playerOf(dir)?.snap === key) stopPlay(dir);
333
481
  const had = existsSync(target);
334
482
  if (had) await renameRetrying(target, old);
335
483
  try {
336
484
  await renameRetrying(tmp, target);
337
- await atomicWrite(factsOf(dir, id), `${JSON.stringify(facts, null, 2)}\n`);
485
+ await atomicWrite(snapFactsOf(dir, key), `${JSON.stringify(facts, null, 2)}\n`);
338
486
  } catch (e) {
339
487
  await rm(target, RM).catch(() => {});
340
488
  if (had) await renameRetrying(old, target);
341
489
  throw e;
342
490
  }
343
491
 
344
- return null;
492
+ linkTo(dir, who, key, source);
493
+
494
+ return { facts };
345
495
  });
346
496
  // Out of the lock: a big snapshot takes a while to delete. A failure leaves it to a sweep.
347
497
  await rm(old, RM).catch(() => {});
348
498
 
349
- return refused;
499
+ return done;
350
500
  }
351
501
 
352
502
  /**
353
- * Build card `id` with `play.build` and keep the result as its snapshot; the old snapshot stays
354
- * until a new one has replaced it. `from`: the card's worktree, whose code is still its alone. A
355
- * failed build is no error: it comes back as `problem`, and the card goes on without one.
503
+ * Build card `id` with `play.build`, or link it to the snapshot of the same code another card
504
+ * holds (d23); the old snapshot stays until a new one has replaced it. `from`: the card's worktree,
505
+ * whose code is still its alone. `fresh`: build even when a snapshot of this code is there, and
506
+ * replace it. A failed build is no error: it comes back as `problem`, and the card goes on without
507
+ * one.
356
508
  * @returns {Promise<{id: string, ok: boolean, problem?: string, dirtied?: string[]}>}
357
509
  */
358
- export async function buildItem(projectDir, id, { from = null } = {}) {
510
+ export async function buildItem(projectDir, id, { from = null, fresh = false } = {}) {
359
511
  needId(id);
360
512
  const dir = path.resolve(projectDir);
361
513
  const play = await projectPlay(dir);
@@ -366,7 +518,23 @@ export async function buildItem(projectDir, id, { from = null } = {}) {
366
518
  if (problem) throw new Error(problem);
367
519
  const hold = from ? { own: true, release: null } : await holdCheckout(dir, id);
368
520
  try {
369
- return await runBuild(dir, cwd, play, { id, from, own: hold.own });
521
+ return await runBuild(dir, cwd, play, { who: id, from, own: hold.own, fresh });
522
+ } finally {
523
+ await hold.release?.();
524
+ if (hold.release) await mergeWaiting(dir);
525
+ }
526
+ }
527
+
528
+ /**
529
+ * Build the checkout as it is, uncommitted edits too (d30): "Play main" after the operator's own
530
+ * changes. A clean tree whose code a card's snapshot already holds takes that one, unless `fresh`.
531
+ */
532
+ export async function buildMain(projectDir, { fresh = false } = {}) {
533
+ const dir = path.resolve(projectDir);
534
+ const play = await projectPlay(dir);
535
+ const hold = await holdCheckout(dir, 'main');
536
+ try {
537
+ return await runBuild(dir, dir, play, { who: MAIN, from: null, own: hold.own, fresh });
370
538
  } finally {
371
539
  await hold.release?.();
372
540
  if (hold.release) await mergeWaiting(dir);
@@ -387,27 +555,67 @@ async function mergeWaiting(dir) {
387
555
  }
388
556
  }
389
557
 
390
- async function runBuild(dir, cwd, play, { id, from, own }) {
558
+ /** What a build or a link answers: the holder, the snapshot's facts, and how it came. */
559
+ const answerOf = (who, key, facts, source) => ({
560
+ ...(who === MAIN ? { main: true } : { id: who }),
561
+ ok: true,
562
+ ...facts,
563
+ snap: key,
564
+ source,
565
+ });
566
+
567
+ async function runBuild(dir, cwd, play, { who, from, own, fresh }) {
391
568
  const started = new Date().toISOString();
392
569
  await mkdir(buildsOf(dir), { recursive: true });
393
- await withMainLock(dir, async () => {
570
+ await mkdir(snapsOf(dir), { recursive: true });
571
+ const loose = looseOf(cwd);
572
+ const key = keyOf(cwd, who, loose, play);
573
+ const source = who === MAIN ? 'main' : own ? 'run' : 'click';
574
+ // A dirty tree's snapshot is nobody else's, and not this holder's next time either (d22).
575
+ const reuse = !fresh && CLEAN_KEY.test(key);
576
+ const linked = await withMainLock(dir, async () => {
394
577
  await sweep(dir);
395
- const problem = await statusProblem(dir, id, from);
396
- if (problem) throw new Error(problem);
397
- const was = readJson(attemptOf(dir, id));
578
+ if (who !== MAIN) {
579
+ const problem = await statusProblem(dir, who, from);
580
+ if (problem) throw new Error(problem);
581
+ }
582
+
583
+ const was = readJson(attemptOf(dir, who));
398
584
  if (building(was) && was.pid !== process.pid)
399
- throw new Error(`${id} is being built (pid ${was.pid}): wait until that build ends`);
400
- writeJsonSync(attemptOf(dir, id), { pid: process.pid, building: true, at: started });
585
+ throw new Error(`${nameOf(who)} is being built (pid ${was.pid}): wait until that build ends`);
586
+ const there = reuse && readJson(snapFactsOf(dir, key));
587
+ if (there && existsSync(snapOf(dir, key)) && held(linksOf(dir), key)) {
588
+ linkTo(dir, who, key, source);
589
+ dropAttempt(dir, who);
590
+
591
+ // Nothing ran here: what another build changed is not this one's to report.
592
+ return answerOf(who, key, { ...there, dirtied: [] }, source);
593
+ }
594
+
595
+ writeJsonSync(attemptOf(dir, who), { pid: process.pid, building: true, at: started });
596
+
597
+ return null;
401
598
  });
599
+ if (linked) return linked;
402
600
  const failed = (problem) => {
403
- writeJsonSync(attemptOf(dir, id), { pid: process.pid, problem, at: started });
601
+ writeJsonSync(attemptOf(dir, who), { pid: process.pid, problem, at: started });
404
602
 
405
- return { id, ok: false, problem, log: logOf(dir, id) };
603
+ return {
604
+ ...(who === MAIN ? { main: true } : { id: who }),
605
+ ok: false,
606
+ problem,
607
+ log: logOf(dir, who),
608
+ };
406
609
  };
407
610
 
408
- const tmp = `${snapshotOf(dir, id)}.tmp-${process.pid}`;
611
+ // Its holder in the name too: two holders may build the same code in one process.
612
+ const tmp = path.join(
613
+ snapsOf(dir),
614
+ `${key}.${who === MAIN ? 'checkout' : `card-${who}`}.tmp-${process.pid}`,
615
+ );
616
+ const at = { who, key, source, loose, from, reuse, tmp, failed };
409
617
  try {
410
- return await buildAndPublish(dir, cwd, play, { id, from, own, tmp, failed });
618
+ return await buildAndPublish(dir, cwd, play, at);
411
619
  } catch (e) {
412
620
  return failed(e.message);
413
621
  } finally {
@@ -415,16 +623,20 @@ async function runBuild(dir, cwd, play, { id, from, own }) {
415
623
  }
416
624
  }
417
625
 
418
- async function buildAndPublish(dir, cwd, play, { id, from, own, tmp, failed }) {
419
- const output = path.join(cwd, play.output);
626
+ /** Whether git ignores `output`: a build there must not show up as the project's change. */
627
+ const ignored = (cwd, output) =>
420
628
  // The slash: a rule for folders only must match a folder not built yet.
421
- if (spawnSync('git', ['check-ignore', '-q', `${play.output}/`], { cwd }).status !== 0)
629
+ spawnSync('git', ['check-ignore', '-q', `${output}/`], { cwd }).status === 0;
630
+
631
+ async function buildAndPublish(dir, cwd, play, at) {
632
+ const { who, key, source, loose, from, reuse, tmp, failed } = at;
633
+ const output = path.join(cwd, play.output);
634
+ if (!ignored(cwd, play.output))
422
635
  return failed(`play.output ${play.output} is not ignored by git: add it to .gitignore`);
423
- const loose = looseOf(cwd);
424
636
  const before = treeOf(output);
425
- const commit = gitOut(cwd, ['rev-parse', '--short', 'HEAD'])?.trim() ?? null;
637
+ const commit = gitOut(cwd, ['rev-parse', 'HEAD'])?.trim() ?? null;
426
638
  const minutes = (await readConfig(path.join(dir, 'gcf'))).dod_timeout_min ?? 0;
427
- const log = await open(logOf(dir, id), 'w');
639
+ const log = await open(logOf(dir, who), 'w');
428
640
  let res;
429
641
  try {
430
642
  res = await runCommand(play.build, cwd, ['ignore', log.fd, log.fd], minutes * 60000);
@@ -433,7 +645,7 @@ async function buildAndPublish(dir, cwd, play, { id, from, own, tmp, failed }) {
433
645
  }
434
646
 
435
647
  const why = failureOf('play.build', play.build, minutes, res);
436
- if (why) return failed(withTail(why, logOf(dir, id)));
648
+ if (why) return failed(withTail(why, logOf(dir, who)));
437
649
  const after = treeOf(output);
438
650
  // A build that wrote nothing new must not stand in for this commit.
439
651
  if (!refreshed(before, after))
@@ -442,25 +654,20 @@ async function buildAndPublish(dir, cwd, play, { id, from, own, tmp, failed }) {
442
654
  // Its links as they are: made absolute they would point back into `output`, at a later build.
443
655
  await cp(output, tmp, { recursive: true, verbatimSymlinks: true });
444
656
  const facts = {
445
- id,
657
+ key,
446
658
  commit,
447
659
  built_at: new Date().toISOString(),
448
- source: own ? 'run' : 'click',
449
660
  dirty: loose.length > 0,
450
661
  dirtied,
451
662
  size: [...after.values()].reduce((sum, f) => sum + f.size, 0),
452
663
  };
453
- const refused = await publish(dir, { id, tmp, facts, from });
664
+ const done = await publish(dir, { who, key, tmp, facts, source, from, reuse });
665
+ rmSync(attemptOf(dir, who), { force: true });
454
666
  // Not a failed build: the card has moved on, and nobody waits for this one.
455
- if (refused) {
456
- rmSync(attemptOf(dir, id), { force: true });
457
-
458
- return { id, ok: false, problem: refused, moved_on: true };
459
- }
667
+ if (done.refused) return { id: who, ok: false, problem: done.refused, moved_on: true };
460
668
 
461
- rmSync(attemptOf(dir, id), { force: true });
462
-
463
- return { ok: true, ...facts };
669
+ // What this build changed, even when another one's snapshot serves (a main batch stops on it).
670
+ return answerOf(who, key, { ...done.facts, dirtied }, source);
464
671
  }
465
672
 
466
673
  /** The running player's record as it stands, or null; a dead one reads as none. Reads only. */
@@ -477,6 +684,7 @@ const runStop = (dir, command) =>
477
684
  spawnSync(command, {
478
685
  cwd: dir,
479
686
  shell: true,
687
+ env: commandEnv(),
480
688
  stdio: 'ignore',
481
689
  timeout: STOP_WAIT_MS,
482
690
  windowsHide: true,
@@ -565,6 +773,8 @@ function launch(dir, command) {
565
773
  const child = spawn(process.execPath, ['-e', KEEPER, command], {
566
774
  cwd: dir,
567
775
  detached: true,
776
+ // The keeper's shell takes it: the start finds the `bash` its agent tried.
777
+ env: commandEnv(),
568
778
  stdio: ['ignore', log, log],
569
779
  windowsHide: true,
570
780
  });
@@ -587,12 +797,13 @@ function recordPlayer(dir, record) {
587
797
  }
588
798
 
589
799
  /**
590
- * Play card `id`'s snapshot on `target`. One player per project: the last one stops first. The
591
- * process is cut loose from its caller, so a board's restart does not end the game. A process that
592
- * ends with 0 has launched what it launches: nothing is left to stop.
800
+ * Play the snapshot card `id` holds on `target`; `id` null: the checkout's ("Play main"). One
801
+ * player per project: the last one stops first. The process is cut loose from its caller, so a
802
+ * board's restart does not end the game. A process that ends with 0 has launched what it launches:
803
+ * nothing is left to stop.
593
804
  */
594
805
  export async function startPlay(projectDir, id, targetName) {
595
- needId(id);
806
+ if (id !== null) needId(id);
596
807
  const dir = path.resolve(projectDir);
597
808
  const play = await projectPlay(dir);
598
809
  const target = Object.hasOwn(play.targets, targetName) ? play.targets[targetName] : null;
@@ -604,10 +815,8 @@ export async function startPlay(projectDir, id, targetName) {
604
815
  // Held to the end: a verdict meanwhile waits, or it would miss the player this start records.
605
816
  return withMainLock(dir, async () => {
606
817
  await sweep(dir);
607
- const facts = readJson(factsOf(dir, id));
608
- const snapshot = snapshotOf(dir, id);
609
- if (!facts || facts.released || !existsSync(snapshot))
610
- throw new Error(`${id} has no build: ai-factory gcf playtest build ${id}`);
818
+ const key = heldKey(dir, id);
819
+ const snapshot = snapOf(dir, key);
611
820
  stopPlay(dir);
612
821
  const port = await freePort();
613
822
  const lan = lanAddress();
@@ -624,46 +833,44 @@ export async function startPlay(projectDir, id, targetName) {
624
833
  const url = /^https?:\/\//.test(open) ? open : null;
625
834
  const stop = target.stop ? { stop: inCommand(target.stop) } : {};
626
835
  const started = new Date().toISOString();
627
- const record = { pid: child.pid, id, target: targetName, port, open, url, started, ...stop };
836
+ const main = id === null ? { main: true } : {};
837
+ const record = { pid: child.pid, id, ...main, snap: key, target: targetName, port, open, url };
628
838
  // Before the wait: a starter killed in it must not leave a player nobody can stop.
629
- recordPlayer(dir, record);
630
- const forget = () => rmSync(playerFile(dir), { force: true });
839
+ recordPlayer(dir, { ...record, started, ...stop });
631
840
  const end = await outcomeOf(child, target.start.includes('{port}') ? port : null);
632
841
  const undo = () => target.stop && runStop(dir, inCommand(target.stop));
633
- if (end.state === 'silent') {
634
- killTree(child.pid);
635
- forget();
636
- undo();
637
- throw new Error(
638
- withTail(`play.targets.${targetName}.start did not answer on port ${port}`, playerLog(dir)),
639
- );
640
- }
641
-
642
- if (end.state === 'error') {
643
- forget();
644
- undo();
645
- throw new Error(
646
- withTail(`play.targets.${targetName}.start failed (${end.why})`, playerLog(dir)),
647
- );
648
- }
649
-
650
- if (end.state === 'launched') {
651
- forget();
652
-
653
- return { state: 'launched', id, target: targetName, open, url };
654
- }
655
-
656
- return { state: 'running', ...record };
842
+ if (end.state === 'running') return { state: 'running', ...record, started, ...stop };
843
+ rmSync(playerFile(dir), { force: true });
844
+ if (end.state === 'launched')
845
+ return { state: 'launched', id, ...main, target: targetName, open, url };
846
+ if (end.state === 'silent') killTree(child.pid);
847
+ undo();
848
+ const why = end.state === 'silent' ? `did not answer on port ${port}` : `failed (${end.why})`;
849
+ throw new Error(withTail(`play.targets.${targetName}.start ${why}`, playerLog(dir)));
657
850
  });
658
851
  }
659
852
 
853
+ /** The snapshot card `id` holds, or the checkout's for null; none throws what to do. */
854
+ function heldKey(dir, id) {
855
+ const link = readJson(linkOf(dir, id ?? MAIN));
856
+ const key = KEY_RE.test(link?.snap ?? '') && !link.released ? link.snap : null;
857
+ if (key && existsSync(snapOf(dir, key)) && existsSync(snapFactsOf(dir, key))) return key;
858
+ throw new Error(
859
+ id
860
+ ? `${id} has no build: ai-factory gcf playtest build ${id}`
861
+ : 'main has no build: ai-factory gcf playtest build --main',
862
+ );
863
+ }
864
+
660
865
  const NO_FACTS = {
866
+ key: null,
661
867
  commit: null,
662
868
  built_at: null,
663
869
  source: null,
664
870
  dirty: false,
665
871
  dirtied: [],
666
872
  size: null,
873
+ shared_with: [],
667
874
  };
668
875
 
669
876
  /**
@@ -678,38 +885,84 @@ function attemptProblem(attempt, going) {
678
885
  : (attempt?.problem ?? null);
679
886
  }
680
887
 
681
- /** What a board and a chat show of the card: its snapshot, or the attempt under way or failed. */
682
- export function buildOf(projectDir, id, status) {
683
- const dir = path.resolve(projectDir);
684
- const raw = readJson(factsOf(dir, id));
685
- const facts = raw?.released || !existsSync(snapshotOf(dir, id)) ? null : raw;
686
- const attempt = readJson(attemptOf(dir, id));
888
+ /**
889
+ * A holder's snapshot and its attempt, read only. `shared_with`: the other cards that hold the
890
+ * same snapshot (d27).
891
+ */
892
+ function heldBuild(dir, who, links) {
893
+ const link = links.get(who);
894
+ const key = link && link !== UNREAD && !link.released ? link.snap : null;
895
+ const facts = key && existsSync(snapOf(dir, key)) ? readJson(snapFactsOf(dir, key)) : null;
896
+ const attempt = readJson(attemptOf(dir, who));
687
897
  const going = building(attempt);
688
- // A card back at work has no build to offer, unless one goes for it in its worktree right now.
689
- if (status === 'ready' && !going) return null;
690
898
  const problem = attemptProblem(attempt, going);
691
899
  if (!facts && !going && !problem) return null;
900
+ const shared = [...links]
901
+ .filter(([w, l]) => facts && w !== who && w !== MAIN && l !== UNREAD && holds(l, key))
902
+ .map(([w]) => w)
903
+ .sort();
692
904
 
693
- return { ...NO_FACTS, ...facts, ok: Boolean(facts), building: going, problem };
905
+ return {
906
+ ...NO_FACTS,
907
+ ...facts,
908
+ ...(facts ? { key, source: link.source ?? null, shared_with: shared } : {}),
909
+ ok: Boolean(facts),
910
+ building: going,
911
+ problem,
912
+ };
694
913
  }
695
914
 
696
- /** The project's targets and running player, read only: null with no `play:`. */
915
+ /**
916
+ * What a board and a chat show of the card: its snapshot, or the attempt under way or failed.
917
+ * `links`: linksOf once for a whole board.
918
+ */
919
+ export function buildOf(projectDir, id, status, links = linksOf(projectDir)) {
920
+ const dir = path.resolve(projectDir);
921
+ // A card back at work has no build to offer, unless one goes for it in its worktree right now.
922
+ if (status === 'ready' && !building(readJson(attemptOf(dir, id)))) return null;
923
+
924
+ return heldBuild(dir, id, links);
925
+ }
926
+
927
+ /**
928
+ * How the project plays, read only: its `play:` whole (d26), the checkout's snapshot (d30) and the
929
+ * running player; null with no `play:`.
930
+ */
697
931
  export function playFacts(projectDir, config) {
698
932
  let play;
699
933
  try {
700
934
  play = playOf(config);
701
935
  } catch (e) {
702
- return { problem: e.message, targets: [], running: null };
936
+ const none = { build: null, output: null, targets: [], main: null, running: null };
937
+
938
+ return { problem: e.message, ...none };
703
939
  }
704
940
 
705
941
  if (!play) return null;
706
- const p = playerOf(projectDir);
942
+ const dir = path.resolve(projectDir);
943
+ const p = playerOf(dir);
707
944
 
708
945
  return {
709
946
  problem: null,
710
- targets: Object.entries(play.targets).map(([name, t]) => ({ name, open: t.open })),
947
+ build: play.build,
948
+ output: play.output,
949
+ targets: Object.entries(play.targets).map(([name, t]) => ({
950
+ name,
951
+ start: t.start,
952
+ open: t.open,
953
+ stop: t.stop ?? null,
954
+ })),
955
+ main: heldBuild(dir, MAIN, linksOf(dir)),
711
956
  running: p
712
- ? { id: p.id, target: p.target, open: p.open, url: p.url, started: p.started }
957
+ ? {
958
+ id: p.id,
959
+ main: p.main === true,
960
+ snap: p.snap ?? null,
961
+ target: p.target,
962
+ open: p.open,
963
+ url: p.url,
964
+ started: p.started,
965
+ }
713
966
  : null,
714
967
  };
715
968
  }
@@ -738,6 +991,10 @@ export async function setupPlay(projectDir, opts) {
738
991
  throw new Error(`a target's name is one word: ${target}`);
739
992
  if (target === undefined && [start, words, stop].some((v) => v !== undefined))
740
993
  throw new Error('--start, --open and --stop belong to a --target');
994
+ // Now, not at the first build minutes later (d21).
995
+ if (output !== undefined) needOutput(output);
996
+ if (output !== undefined && !ignored(dir, output))
997
+ throw new Error(`play.output ${output} is not ignored by git: add it to .gitignore`);
741
998
  const file = path.join(dir, 'gcf', 'config.yml');
742
999
  const hash = await commitMove(dir, 'gcf(config): play', {
743
1000
  files: [file],
@@ -4,7 +4,7 @@ import { readFile } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { gameMilestones } from './design-check.js';
6
6
  import { listItems, scalarOf, firstBullet } from './gcf-paths.js';
7
- import { buildOf } from './play.js';
7
+ import { buildOf, linksOf } from './play.js';
8
8
  import { recordsOf } from './verdict-fs.js';
9
9
 
10
10
  const ENVELOPE = /^\S+\.\.\S+ /;
@@ -55,6 +55,7 @@ export async function platformsOf(root) {
55
55
  */
56
56
  export async function playtestList(root) {
57
57
  const platforms = await platformsOf(root);
58
+ const links = linksOf(path.dirname(root));
58
59
 
59
60
  return (await listItems(root))
60
61
  .filter((c) => ['awaiting-verdict', 'unplayed'].includes(c.data.status))
@@ -65,7 +66,7 @@ export async function playtestList(root) {
65
66
  system: c.data.system ?? [],
66
67
  milestone: c.data.milestone ?? null,
67
68
  play_on: c.data.play_on ?? platforms,
68
- build: buildOf(path.dirname(root), String(c.data.id), c.data.status),
69
+ build: buildOf(path.dirname(root), String(c.data.id), c.data.status, links),
69
70
  question: scalarOf(c.body, 'miss_criterion') || '(miss_criterion is empty)',
70
71
  reach: recordsOf(c.body, 'behavior')
71
72
  .map((r) => r.input)
@@ -0,0 +1,33 @@
1
+ // The environment a project's command runs in (`dod.*`, `play.build`, a target's start and stop).
2
+ // On Windows cmd.exe finds `bash` by PATH, and outside Git Bash the first one is System32's WSL
3
+ // launcher, which fails with no distribution. The agent finds and tries the project's commands in
4
+ // Git Bash: Git's own `bin` first in PATH gives them the same `bash` and `sh` from a board started
5
+ // in PowerShell, from a console and from a run. That folder holds bash, sh and git alone, so a
6
+ // command written for cmd.exe finds nothing else in it.
7
+ import { spawnSync } from 'node:child_process';
8
+ import { existsSync } from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ let gitBin;
12
+
13
+ /** Git for Windows' `bin`, found by the git on PATH; null off Windows or with no such Git. */
14
+ export function gitBinDir() {
15
+ if (process.platform !== 'win32') return null;
16
+ if (gitBin !== undefined) return gitBin;
17
+ const res = spawnSync('git', ['--exec-path'], { encoding: 'utf8', windowsHide: true });
18
+ // `<git>/mingw64/libexec/git-core`: its `bin` is three folders up.
19
+ const exec = res.status === 0 ? res.stdout.trim() : '';
20
+ const bin = exec ? path.resolve(exec, '..', '..', '..', 'bin') : null;
21
+ gitBin = bin && existsSync(path.join(bin, 'bash.exe')) ? bin : null;
22
+
23
+ return gitBin;
24
+ }
25
+
26
+ /** `env` with Git's `bin` first in its PATH on Windows; as it is elsewhere. */
27
+ export function commandEnv(env = process.env) {
28
+ const bin = gitBinDir();
29
+ if (!bin) return env;
30
+ const key = Object.keys(env).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH';
31
+
32
+ return { ...env, [key]: `${bin}${path.delimiter}${env[key] ?? ''}` };
33
+ }
package/lib/verify.js CHANGED
@@ -7,6 +7,7 @@ import path from 'node:path';
7
7
  import { readConfig } from './gcf-paths.js';
8
8
  import { readLive, applyDelta } from './live.js';
9
9
  import { gateProblems } from './gate.js';
10
+ import { commandEnv } from './shell-env.js';
10
11
 
11
12
  /**
12
13
  * Every process's parent, `[pid, ppid]` (POSIX): from /proc on Linux, which a slim image has
@@ -83,7 +84,7 @@ function stopChildren(doomed) {
83
84
  */
84
85
  export function runCommand(cmd, cwd, stdio, ms) {
85
86
  return new Promise((resolve) => {
86
- const child = spawn(cmd, { cwd, shell: true, stdio });
87
+ const child = spawn(cmd, { cwd, shell: true, stdio, env: commandEnv() });
87
88
  let timedOut = false;
88
89
  const timer =
89
90
  ms > 0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-aif-ext",
3
- "version": "0.25.0",
3
+ "version": "0.26.1",
4
4
  "description": "Game Context Framework for AI Factory",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -21,7 +21,10 @@ forbidden_behaviors:
21
21
  - do not run `keep` when the human has not answered the item's miss_criterion question
22
22
  - do not hold a keep for a play condition: the human decides where to play; remind once of a line of `platforms` not played, then take the answer
23
23
  - do not edit systems docs, `LIVE.md`, history or graveyard by hand: the commands own them
24
- - do not stop the player or delete the card's build: the verdict does both; `build_left` in its report names a build a held file kept, and a later `ai-factory gcf playtest status` removes it
24
+ - do not stop the player or delete the card's build: the verdict does both, and a build other cards on the same code hold stays for them
25
+ - `build_left` in the verdict's report names a build a held file kept; a later `ai-factory gcf playtest status` removes it
26
+ - do not answer that the human cannot play for want of a build: the card's Play button builds it first
27
+ - when the human asks for a build, run `ai-factory gcf playtest build <id>`, or `--main` for the checkout as it is
25
28
  - a tune note triage left in the inbox for the item goes into `--note`; after the verdict run `ai-factory gcf inbox drop <in-id>`, not before
26
29
 
27
30
  workflow:
@@ -40,9 +40,14 @@ gcf_work:
40
40
  - `ai-factory gcf design check` names each hit of an avoided word in design and items as M4, `npx --yes cnlp-kit check` the rest
41
41
  - an `avoid:` lists only a word wrong in every document: a word with another use stays out, a phrase ("tile hand") beats a bare word
42
42
  - the human plays from `ai-factory gcf playtest session`; each free note from that play goes to `ai-factory gcf inbox add --category playtest "<note>"`, in the human's words
43
- - with `play:` in `gcf/config.yml` the harness builds a card that waits for its verdict at the end of its run; that build stays apart in `.gcf-session/builds/<id>/`, and later work does not touch it
44
- - the board's Play button starts that build on a target of `play:`, and the card's verdict stops it and removes the build; `ai-factory gcf playtest status` names the targets and the running player
45
- - how the game builds and starts is the human's: `ai-factory gcf playtest setup`; in the project chat propose it with `propose_play_setup`, and the button with `propose_play`
43
+ - with `play:` in `gcf/config.yml` the harness builds a card that waits for its verdict at the end of its run, into `.gcf-session/snaps/`, where later work does not touch it
44
+ - a build is one per code: cards on the same code share it, and a verdict removes it only when no other card holds it
45
+ - the board's Play button builds the card when it has no build yet, then starts it on a target of `play:`; the card's verdict stops its player
46
+ - Play main does the same for the checkout as it is, hand edits too; `ai-factory gcf playtest status` names the targets and the running player
47
+ - how the game builds and starts is the human's to accept: find it in the project (this file, its build and serve scripts) and propose it with `propose_play_setup`
48
+ - do not ask the human for the build or start commands: the project holds them
49
+ - a project with no command that builds into a folder git ignores, or none that starts it from there, gets a tech card from you that adds both and names them here
50
+ - do not answer that the game cannot be built: offer the card's button with `propose_play`, or the checkout's with `propose_play_main`
46
51
  - a release item carries `version:` and `channel:` (`item new --title "<title>" --type release --release <v> --channel <c>`): its end writes the `release:` block of `gcf/LIVE.md`
47
52
  - `item new` and `take` refuse a type the current phase does not take: run `ai-factory gcf phase` and bring the refusal to the human
48
53
  - an item's milestone (`item new --milestone <name>`) is a `name` of the `milestones` in `gcf/game.md`, as a unit's: `item new` refuses another; a new milestone is a change of the vision, for the human (the gcf-vision skill)
@@ -106,7 +111,8 @@ gcf_forbidden:
106
111
  - do not give a verdict: `verdict` belongs to the human, through the gcf-verdict skill; nor a decision, but `go` or `no` of the spike you drive when the gates say `decision: agent`
107
112
  - the core refuses the human's moves to a harness run and a board chat: bring the move to the human, or block the item with the question
108
113
  - those moves are `verdict`, `decide`, `drop` of a work item, `unblock`, `item amend`, `question answer`, `config set`, `playtest setup`, `permissions`, `phase next`, `pillar`, `hooks-install`, `edits commit`, `edits discard`, `changes commit`
109
- - do not build the game to play nor start a player yourself: the harness builds it, the human's Play button starts it, and `dod.build` only checks the code
114
+ - a run's agent does not build the game to play nor start a player: the harness builds it at the run's end, and `dod.build` only checks the code
115
+ - in the project chat, when the human asks for a build, run `ai-factory gcf playtest build <id>` or `ai-factory gcf playtest build --main` yourself
110
116
  - do not answer a `TBD` of a design unit yourself: ask the human and offer your draft as the proposed answer
111
117
  - do not run `ai-factory gcf phase next`: the phase moves on the human's word only
112
118
  - do not change what agent runs may do: `ai-factory gcf permissions`, its deny groups and the board's YOLO belong to the human