gcf-aif-ext 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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. 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.0",
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';
@@ -30,15 +33,32 @@ const STOP_WAIT_MS = 15000;
30
33
  // A held file on Windows lets go a moment after its process ends.
31
34
  const RM = { recursive: true, force: true, maxRetries: 5, retryDelay: 200 };
32
35
 
36
+ // The checkout as it is ("Play main"): no item id, so no card's files can take its name.
37
+ const MAIN = ':main';
33
38
  const session = (dir) => path.join(dir, '.gcf-session');
34
39
  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`);
40
+ const snapsOf = (dir) => path.join(session(dir), 'snaps');
41
+ const snapOf = (dir, key) => path.join(snapsOf(dir), key);
42
+ const snapFactsOf = (dir, key) => path.join(snapsOf(dir), `${key}.json`);
43
+ /** A holder's own files: a card's under `builds/`, the checkout's beside the snapshots. */
44
+ const ownOf = (dir, who, ext) =>
45
+ who === MAIN ? path.join(snapsOf(dir), `main.${ext}`) : path.join(buildsOf(dir), `${who}.${ext}`);
46
+ /** A holder as words, and in a file's name. */
47
+ const nameOf = (who) => (who === MAIN ? 'main' : who);
48
+ const linkOf = (dir, who) => ownOf(dir, who, who === MAIN ? 'link.json' : 'json');
49
+ const attemptOf = (dir, who) => ownOf(dir, who, 'attempt.json');
50
+ const logOf = (dir, who) => ownOf(dir, who, 'log');
39
51
  const playerFile = (dir) => path.join(session(dir), 'play.json');
40
52
  const playerLog = (dir) => path.join(session(dir), 'play.log');
41
53
  const leftovers = /^.+\.(?:tmp|old)-(\d+)$/;
54
+ /**
55
+ * A snapshot's name: the code's, and for a dirty tree also its holder's: `-<id>` for a card,
56
+ * `.main` for the checkout, which no card id can spell (a card may be called `main`).
57
+ */
58
+ const KEY_RE = /^[0-9a-f]{16}(?:-[a-z0-9]+(?:-[a-z0-9]+)*|\.main)?$/;
59
+ const CLEAN_KEY = /^[0-9a-f]{16}$/;
60
+ // A link that cannot be read: nobody knows which snapshot it holds, so it holds them all (d24).
61
+ const UNREAD = Object.freeze({ unread: true });
42
62
 
43
63
  function readJson(file) {
44
64
  try {
@@ -48,6 +68,8 @@ function readJson(file) {
48
68
  }
49
69
  }
50
70
 
71
+ const listOf = (folder) => (existsSync(folder) ? readdirSync(folder, { withFileTypes: true }) : []);
72
+
51
73
  /** A rename from a synchronous path: Windows holds a fresh file for a moment (a scanner). */
52
74
  function renameHeld(from, to) {
53
75
  for (let attempt = 1; ; attempt++) {
@@ -163,16 +185,49 @@ function treeOf(dir) {
163
185
  const refreshed = (before, after) => [...after].some(([p, f]) => before.get(p)?.stamp !== f.stamp);
164
186
 
165
187
  const gitOut = (cwd, args) => {
166
- const res = spawnSync('git', args, { cwd, encoding: 'utf8' });
188
+ // A big project lists far past the 1 MB a spawn holds by default; past it git's answer is lost.
189
+ const res = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
167
190
 
168
191
  return res.status === 0 ? res.stdout : null;
169
192
  };
170
193
 
194
+ // The framework's own files: no build's, so neither a change of them nor a commit of them makes
195
+ // another game. One list for the dirty check and the snapshot's key.
196
+ const NOT_CODE = ['gcf', 'GLOSSARY.md', '.gcf-session'];
197
+
198
+ /**
199
+ * The key of the code HEAD holds, the framework's files left out (d29), and of how it is built: a
200
+ * verdict or an inbox commit keeps it, a new `play.build` or `play.output` does not. Null with no
201
+ * commit. 16 hex: a path on Windows stays short. The top level alone: a folder's entry is the hash
202
+ * of all it holds, and every file the key leaves out is at the top.
203
+ */
204
+ function codeOf(cwd, play) {
205
+ const out = gitOut(cwd, ['ls-tree', '-z', 'HEAD']);
206
+ if (out === null) return null;
207
+ const code = out
208
+ .split('\0')
209
+ .filter(Boolean)
210
+ .filter((l) => !NOT_CODE.includes(l.slice(l.indexOf('\t') + 1)));
211
+
212
+ return createHash('sha256')
213
+ .update([...code, play.build, play.output].join('\0'))
214
+ .digest('hex')
215
+ .slice(0, 16);
216
+ }
217
+
218
+ /** The snapshot's key: the code's alone when the tree is clean, else its holder's own too. */
219
+ function keyOf(cwd, who, loose, play) {
220
+ const code = codeOf(cwd, play);
221
+ if (code && !loose.length) return code;
222
+
223
+ return `${code ?? '0'.repeat(16)}${who === MAIN ? '.main' : `-${who}`}`;
224
+ }
225
+
171
226
  /** What git sees changed or new, each path once; gcf/ and the run's own files are no build's. */
172
227
  function looseOf(cwd) {
173
228
  const out = gitOut(cwd, [
174
229
  ...['--no-optional-locks', 'status', '--porcelain', '-z', '-uall', '--', '.'],
175
- ...[':(exclude)gcf', ':(exclude)GLOSSARY.md', ':(exclude).gcf-session'],
230
+ ...NOT_CODE.map((n) => `:(exclude)${n}`),
176
231
  ]);
177
232
  const parts = (out ?? '').split('\0').filter(Boolean);
178
233
  const paths = [];
@@ -235,72 +290,148 @@ async function holdCheckout(dir, id) {
235
290
  }
236
291
 
237
292
  /**
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.
293
+ * Every holder's link: a card's id, or MAIN, to its link; UNREAD for one that cannot be read. A
294
+ * link of the old layout (a card's facts, no `snap`) holds nothing: a sweep takes it.
295
+ * @returns {Map<string, {snap?: string, released?: boolean, source?: string} | typeof UNREAD>}
242
296
  */
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
- }
297
+ export function linksOf(projectDir) {
298
+ const dir = path.resolve(projectDir);
299
+ const links = new Map();
300
+ const read = (who, file) => {
301
+ const link = readJson(file);
302
+ // A name that is no snapshot's would point a delete anywhere: such a link holds nothing.
303
+ const bad = link && typeof link.snap === 'string' && !KEY_RE.test(link.snap);
304
+ links.set(who, link === null ? UNREAD : bad ? { ...link, snap: null } : link);
305
+ };
259
306
 
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 });
307
+ for (const e of listOf(buildsOf(dir))) {
308
+ const id = e.isFile() && !e.name.endsWith('.attempt.json') && /^(.+)\.json$/.exec(e.name)?.[1];
309
+ if (id && isValidId(id)) read(id, path.join(buildsOf(dir), e.name));
265
310
  }
311
+
312
+ if (existsSync(linkOf(dir, MAIN))) read(MAIN, linkOf(dir, MAIN));
313
+
314
+ return links;
266
315
  }
267
316
 
268
- const building = (attempt) => attempt?.building === true && alive(attempt.pid);
317
+ const holds = (link, key) => link === UNREAD || (link.snap === key && link.released !== true);
318
+ /** Whether snapshot `key` has a holder: an unreleased link to it, or a link nobody can read. */
319
+ const held = (links, key) => [...links.values()].some((l) => holds(l, key));
269
320
 
270
321
  /**
271
- * Remove a card's snapshot, its facts last: a removal that failed halfway is repeated by a sweep.
322
+ * Remove snapshot `key`, its facts last: a removal that failed halfway is repeated by a sweep.
272
323
  * 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.
324
+ * wait for it. A player of it stops first: its files are going.
274
325
  */
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(() => {});
326
+ function dropSnap(dir, key) {
327
+ // Only a snapshot's own name: `""` or `..` would take the whole folder or more.
328
+ if (!KEY_RE.test(key)) return;
329
+ if (playerOf(dir)?.snap === key) stopPlay(dir);
330
+ const target = snapOf(dir, key);
331
+ if (existsSync(target)) {
332
+ const old = `${target}.old-${process.pid}`;
333
+ rmSync(old, RM);
334
+ renameHeld(target, old);
335
+ // A failure leaves it to a sweep, once this process is gone.
336
+ void rm(old, RM).catch(() => {});
337
+ }
338
+
339
+ rmSync(snapFactsOf(dir, key), { force: true });
340
+ }
341
+
342
+ /** A holder's attempt goes with it, unless a build for it is under way right now. */
343
+ function dropAttempt(dir, who, { log = false } = {}) {
344
+ if (building(readJson(attemptOf(dir, who)))) return;
345
+ rmSync(attemptOf(dir, who), { force: true });
346
+ if (log) rmSync(logOf(dir, who), { force: true });
347
+ }
348
+
349
+ /**
350
+ * Point `who` at snapshot `key`; the snapshot it held before goes when nobody else holds it.
351
+ * Under the main lock.
352
+ */
353
+ function linkTo(dir, who, key, source) {
354
+ const was = linksOf(dir).get(who);
355
+ writeJsonSync(linkOf(dir, who), {
356
+ id: who === MAIN ? null : who,
357
+ snap: key,
358
+ at: new Date().toISOString(),
359
+ source,
360
+ });
361
+ if (was && was !== UNREAD && was.snap && was.snap !== key && !held(linksOf(dir), was.snap))
362
+ dropSnap(dir, was.snap);
363
+ }
364
+
365
+ /**
366
+ * Remove what nobody needs any more (d24): a released link, the link of a card off the board, a
367
+ * folder of the old layout, a snapshot nobody holds, leftovers of a dead process. Under the main
368
+ * lock. A held file waits for the next sweep; a card file that cannot be read says nothing of who
369
+ * left the board, so nothing goes by it; while a link cannot be read, no snapshot goes.
370
+ */
371
+ async function sweep(dir) {
372
+ const ledger = await buildLedger(dir).catch(() => null);
373
+ const ids = sweepFolders(dir);
374
+ const links = linksOf(dir);
375
+ const gone = (id) =>
376
+ ledger !== null && !ledger.item(id) && !existsSync(path.join(dir, 'gcf', 'work', `${id}.md`));
377
+ for (const id of ids) {
378
+ const link = links.get(id);
379
+ if (link === UNREAD) continue;
380
+ const left = gone(id);
381
+ if (left || (link && (link.released === true || typeof link.snap !== 'string'))) {
382
+ rmSync(linkOf(dir, id), { force: true });
383
+ if (left) dropAttempt(dir, id, { log: true });
285
384
  }
385
+ }
386
+
387
+ const now = linksOf(dir);
388
+ if ([...now.values()].includes(UNREAD)) return;
389
+ const keys = new Set(
390
+ listOf(snapsOf(dir))
391
+ .map((e) => e.name.replace(/\.json$/, ''))
392
+ .filter((k) => KEY_RE.test(k)),
393
+ );
394
+ for (const key of keys) if (!held(now, key)) dropSnap(dir, key);
395
+ }
396
+
397
+ /** A snapshot of the old layout goes; a player an older core started from it stops first. */
398
+ function dropOld(dir, id) {
399
+ const p = playerOf(dir);
400
+ if (p?.id === id && !p.snap) stopPlay(dir);
401
+ void rm(path.join(buildsOf(dir), id), RM).catch(() => {});
402
+ }
286
403
 
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 });
404
+ /**
405
+ * Leftovers of a dead process go, and the folders of the old layout (`builds/<id>/`), which no
406
+ * link reaches. Not awaited: the main lock is held here, and every move would wait for a big one.
407
+ * @returns {Set<string>} the ids that have files under `builds/`
408
+ */
409
+ function sweepFolders(dir) {
410
+ const ids = new Set();
411
+ const drop = (folder, name) => void rm(path.join(folder, name), RM).catch(() => {});
412
+ for (const folder of [buildsOf(dir), snapsOf(dir)])
413
+ for (const e of listOf(folder)) {
414
+ const left = leftovers.exec(e.name);
415
+ if (left && !alive(Number(left[1]))) drop(folder, e.name);
416
+ if (left) continue;
417
+
418
+ if (folder !== buildsOf(dir)) continue;
419
+ if (e.isDirectory()) dropOld(dir, e.name);
420
+ const id = e.name.replace(/(\.attempt)?\.(json|log)$/, '');
421
+ if (e.isFile() && isValidId(id)) ids.add(id);
291
422
  }
292
423
 
293
- return null;
294
- } catch (e) {
295
- return `the build of ${id} stays on the disk for now: ${e.message}`;
296
- }
424
+ return ids;
297
425
  }
298
426
 
427
+ const building = (attempt) => attempt?.building === true && alive(attempt.pid);
428
+
299
429
  /**
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.
430
+ * The card's play has ended (a verdict, a drop): its player stops and its link goes; its snapshot
431
+ * goes too when no other card holds it (d24). After the move's commit, so it never fails the move:
432
+ * the problem comes back as words, and the mark `released` makes a later sweep repeat what a held
433
+ * file refused. A card that a tune sends back stays on the board, and only the mark tells this link
434
+ * from a fresh one.
304
435
  * @returns {string | null}
305
436
  */
306
437
  export function releaseBuild(projectDir, id) {
@@ -308,54 +439,74 @@ export function releaseBuild(projectDir, id) {
308
439
  if (!isValidId(id)) return null;
309
440
  const dir = path.resolve(projectDir);
310
441
  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 });
442
+ if (playerOf(dir)?.id === id) stopPlay(dir);
443
+ const file = linkOf(dir, id);
444
+ const link = readJson(file);
445
+ if (link) writeJsonSync(file, { ...link, released: true });
446
+ rmSync(file, { force: true });
447
+ dropAttempt(dir, id);
448
+ if (typeof link?.snap === 'string' && !held(linksOf(dir), link.snap)) dropSnap(dir, link.snap);
315
449
  } catch (e) {
316
450
  return `the build of ${id} stays on the disk for now: ${e.message}`;
317
451
  }
318
452
 
319
- return removeBuild(dir, id);
453
+ return null;
320
454
  }
321
455
 
322
456
  /**
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.
457
+ * Put a finished build in place of snapshot `key` and point `who` at it, or throw and leave the old
458
+ * one with its facts. A card whose status moved on meanwhile (a verdict needs no wait for a build)
459
+ * takes nothing. `reuse`: a build of the same code that ended meanwhile serves this one, and this
460
+ * one is thrown away (d23).
461
+ * @returns {Promise<{refused: string} | {facts: object}>}
325
462
  */
326
- async function publish(dir, { id, tmp, facts, from }) {
327
- const target = snapshotOf(dir, id);
463
+ async function publish(dir, { who, key, tmp, facts, source, from, reuse }) {
464
+ const target = snapOf(dir, key);
328
465
  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);
466
+ const done = await withMainLock(dir, async () => {
467
+ if (who !== MAIN) {
468
+ const problem = await statusProblem(dir, who, from);
469
+ if (problem) return { refused: problem };
470
+ }
471
+
472
+ const there = reuse && readJson(snapFactsOf(dir, key));
473
+ if (there && existsSync(target) && held(linksOf(dir), key)) {
474
+ linkTo(dir, who, key, source);
475
+
476
+ return { facts: there };
477
+ }
478
+
479
+ if (playerOf(dir)?.snap === key) stopPlay(dir);
333
480
  const had = existsSync(target);
334
481
  if (had) await renameRetrying(target, old);
335
482
  try {
336
483
  await renameRetrying(tmp, target);
337
- await atomicWrite(factsOf(dir, id), `${JSON.stringify(facts, null, 2)}\n`);
484
+ await atomicWrite(snapFactsOf(dir, key), `${JSON.stringify(facts, null, 2)}\n`);
338
485
  } catch (e) {
339
486
  await rm(target, RM).catch(() => {});
340
487
  if (had) await renameRetrying(old, target);
341
488
  throw e;
342
489
  }
343
490
 
344
- return null;
491
+ linkTo(dir, who, key, source);
492
+
493
+ return { facts };
345
494
  });
346
495
  // Out of the lock: a big snapshot takes a while to delete. A failure leaves it to a sweep.
347
496
  await rm(old, RM).catch(() => {});
348
497
 
349
- return refused;
498
+ return done;
350
499
  }
351
500
 
352
501
  /**
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.
502
+ * Build card `id` with `play.build`, or link it to the snapshot of the same code another card
503
+ * holds (d23); the old snapshot stays until a new one has replaced it. `from`: the card's worktree,
504
+ * whose code is still its alone. `fresh`: build even when a snapshot of this code is there, and
505
+ * replace it. A failed build is no error: it comes back as `problem`, and the card goes on without
506
+ * one.
356
507
  * @returns {Promise<{id: string, ok: boolean, problem?: string, dirtied?: string[]}>}
357
508
  */
358
- export async function buildItem(projectDir, id, { from = null } = {}) {
509
+ export async function buildItem(projectDir, id, { from = null, fresh = false } = {}) {
359
510
  needId(id);
360
511
  const dir = path.resolve(projectDir);
361
512
  const play = await projectPlay(dir);
@@ -366,7 +517,23 @@ export async function buildItem(projectDir, id, { from = null } = {}) {
366
517
  if (problem) throw new Error(problem);
367
518
  const hold = from ? { own: true, release: null } : await holdCheckout(dir, id);
368
519
  try {
369
- return await runBuild(dir, cwd, play, { id, from, own: hold.own });
520
+ return await runBuild(dir, cwd, play, { who: id, from, own: hold.own, fresh });
521
+ } finally {
522
+ await hold.release?.();
523
+ if (hold.release) await mergeWaiting(dir);
524
+ }
525
+ }
526
+
527
+ /**
528
+ * Build the checkout as it is, uncommitted edits too (d30): "Play main" after the operator's own
529
+ * changes. A clean tree whose code a card's snapshot already holds takes that one, unless `fresh`.
530
+ */
531
+ export async function buildMain(projectDir, { fresh = false } = {}) {
532
+ const dir = path.resolve(projectDir);
533
+ const play = await projectPlay(dir);
534
+ const hold = await holdCheckout(dir, 'main');
535
+ try {
536
+ return await runBuild(dir, dir, play, { who: MAIN, from: null, own: hold.own, fresh });
370
537
  } finally {
371
538
  await hold.release?.();
372
539
  if (hold.release) await mergeWaiting(dir);
@@ -387,27 +554,67 @@ async function mergeWaiting(dir) {
387
554
  }
388
555
  }
389
556
 
390
- async function runBuild(dir, cwd, play, { id, from, own }) {
557
+ /** What a build or a link answers: the holder, the snapshot's facts, and how it came. */
558
+ const answerOf = (who, key, facts, source) => ({
559
+ ...(who === MAIN ? { main: true } : { id: who }),
560
+ ok: true,
561
+ ...facts,
562
+ snap: key,
563
+ source,
564
+ });
565
+
566
+ async function runBuild(dir, cwd, play, { who, from, own, fresh }) {
391
567
  const started = new Date().toISOString();
392
568
  await mkdir(buildsOf(dir), { recursive: true });
393
- await withMainLock(dir, async () => {
569
+ await mkdir(snapsOf(dir), { recursive: true });
570
+ const loose = looseOf(cwd);
571
+ const key = keyOf(cwd, who, loose, play);
572
+ const source = who === MAIN ? 'main' : own ? 'run' : 'click';
573
+ // A dirty tree's snapshot is nobody else's, and not this holder's next time either (d22).
574
+ const reuse = !fresh && CLEAN_KEY.test(key);
575
+ const linked = await withMainLock(dir, async () => {
394
576
  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));
577
+ if (who !== MAIN) {
578
+ const problem = await statusProblem(dir, who, from);
579
+ if (problem) throw new Error(problem);
580
+ }
581
+
582
+ const was = readJson(attemptOf(dir, who));
398
583
  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 });
584
+ throw new Error(`${nameOf(who)} is being built (pid ${was.pid}): wait until that build ends`);
585
+ const there = reuse && readJson(snapFactsOf(dir, key));
586
+ if (there && existsSync(snapOf(dir, key)) && held(linksOf(dir), key)) {
587
+ linkTo(dir, who, key, source);
588
+ dropAttempt(dir, who);
589
+
590
+ // Nothing ran here: what another build changed is not this one's to report.
591
+ return answerOf(who, key, { ...there, dirtied: [] }, source);
592
+ }
593
+
594
+ writeJsonSync(attemptOf(dir, who), { pid: process.pid, building: true, at: started });
595
+
596
+ return null;
401
597
  });
598
+ if (linked) return linked;
402
599
  const failed = (problem) => {
403
- writeJsonSync(attemptOf(dir, id), { pid: process.pid, problem, at: started });
600
+ writeJsonSync(attemptOf(dir, who), { pid: process.pid, problem, at: started });
404
601
 
405
- return { id, ok: false, problem, log: logOf(dir, id) };
602
+ return {
603
+ ...(who === MAIN ? { main: true } : { id: who }),
604
+ ok: false,
605
+ problem,
606
+ log: logOf(dir, who),
607
+ };
406
608
  };
407
609
 
408
- const tmp = `${snapshotOf(dir, id)}.tmp-${process.pid}`;
610
+ // Its holder in the name too: two holders may build the same code in one process.
611
+ const tmp = path.join(
612
+ snapsOf(dir),
613
+ `${key}.${who === MAIN ? 'checkout' : `card-${who}`}.tmp-${process.pid}`,
614
+ );
615
+ const at = { who, key, source, loose, from, reuse, tmp, failed };
409
616
  try {
410
- return await buildAndPublish(dir, cwd, play, { id, from, own, tmp, failed });
617
+ return await buildAndPublish(dir, cwd, play, at);
411
618
  } catch (e) {
412
619
  return failed(e.message);
413
620
  } finally {
@@ -415,16 +622,20 @@ async function runBuild(dir, cwd, play, { id, from, own }) {
415
622
  }
416
623
  }
417
624
 
418
- async function buildAndPublish(dir, cwd, play, { id, from, own, tmp, failed }) {
419
- const output = path.join(cwd, play.output);
625
+ /** Whether git ignores `output`: a build there must not show up as the project's change. */
626
+ const ignored = (cwd, output) =>
420
627
  // 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)
628
+ spawnSync('git', ['check-ignore', '-q', `${output}/`], { cwd }).status === 0;
629
+
630
+ async function buildAndPublish(dir, cwd, play, at) {
631
+ const { who, key, source, loose, from, reuse, tmp, failed } = at;
632
+ const output = path.join(cwd, play.output);
633
+ if (!ignored(cwd, play.output))
422
634
  return failed(`play.output ${play.output} is not ignored by git: add it to .gitignore`);
423
- const loose = looseOf(cwd);
424
635
  const before = treeOf(output);
425
- const commit = gitOut(cwd, ['rev-parse', '--short', 'HEAD'])?.trim() ?? null;
636
+ const commit = gitOut(cwd, ['rev-parse', 'HEAD'])?.trim() ?? null;
426
637
  const minutes = (await readConfig(path.join(dir, 'gcf'))).dod_timeout_min ?? 0;
427
- const log = await open(logOf(dir, id), 'w');
638
+ const log = await open(logOf(dir, who), 'w');
428
639
  let res;
429
640
  try {
430
641
  res = await runCommand(play.build, cwd, ['ignore', log.fd, log.fd], minutes * 60000);
@@ -433,7 +644,7 @@ async function buildAndPublish(dir, cwd, play, { id, from, own, tmp, failed }) {
433
644
  }
434
645
 
435
646
  const why = failureOf('play.build', play.build, minutes, res);
436
- if (why) return failed(withTail(why, logOf(dir, id)));
647
+ if (why) return failed(withTail(why, logOf(dir, who)));
437
648
  const after = treeOf(output);
438
649
  // A build that wrote nothing new must not stand in for this commit.
439
650
  if (!refreshed(before, after))
@@ -442,25 +653,20 @@ async function buildAndPublish(dir, cwd, play, { id, from, own, tmp, failed }) {
442
653
  // Its links as they are: made absolute they would point back into `output`, at a later build.
443
654
  await cp(output, tmp, { recursive: true, verbatimSymlinks: true });
444
655
  const facts = {
445
- id,
656
+ key,
446
657
  commit,
447
658
  built_at: new Date().toISOString(),
448
- source: own ? 'run' : 'click',
449
659
  dirty: loose.length > 0,
450
660
  dirtied,
451
661
  size: [...after.values()].reduce((sum, f) => sum + f.size, 0),
452
662
  };
453
- const refused = await publish(dir, { id, tmp, facts, from });
663
+ const done = await publish(dir, { who, key, tmp, facts, source, from, reuse });
664
+ rmSync(attemptOf(dir, who), { force: true });
454
665
  // 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
- }
666
+ if (done.refused) return { id: who, ok: false, problem: done.refused, moved_on: true };
460
667
 
461
- rmSync(attemptOf(dir, id), { force: true });
462
-
463
- return { ok: true, ...facts };
668
+ // What this build changed, even when another one's snapshot serves (a main batch stops on it).
669
+ return answerOf(who, key, { ...done.facts, dirtied }, source);
464
670
  }
465
671
 
466
672
  /** The running player's record as it stands, or null; a dead one reads as none. Reads only. */
@@ -587,12 +793,13 @@ function recordPlayer(dir, record) {
587
793
  }
588
794
 
589
795
  /**
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.
796
+ * Play the snapshot card `id` holds on `target`; `id` null: the checkout's ("Play main"). One
797
+ * player per project: the last one stops first. The process is cut loose from its caller, so a
798
+ * board's restart does not end the game. A process that ends with 0 has launched what it launches:
799
+ * nothing is left to stop.
593
800
  */
594
801
  export async function startPlay(projectDir, id, targetName) {
595
- needId(id);
802
+ if (id !== null) needId(id);
596
803
  const dir = path.resolve(projectDir);
597
804
  const play = await projectPlay(dir);
598
805
  const target = Object.hasOwn(play.targets, targetName) ? play.targets[targetName] : null;
@@ -604,10 +811,8 @@ export async function startPlay(projectDir, id, targetName) {
604
811
  // Held to the end: a verdict meanwhile waits, or it would miss the player this start records.
605
812
  return withMainLock(dir, async () => {
606
813
  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}`);
814
+ const key = heldKey(dir, id);
815
+ const snapshot = snapOf(dir, key);
611
816
  stopPlay(dir);
612
817
  const port = await freePort();
613
818
  const lan = lanAddress();
@@ -624,46 +829,44 @@ export async function startPlay(projectDir, id, targetName) {
624
829
  const url = /^https?:\/\//.test(open) ? open : null;
625
830
  const stop = target.stop ? { stop: inCommand(target.stop) } : {};
626
831
  const started = new Date().toISOString();
627
- const record = { pid: child.pid, id, target: targetName, port, open, url, started, ...stop };
832
+ const main = id === null ? { main: true } : {};
833
+ const record = { pid: child.pid, id, ...main, snap: key, target: targetName, port, open, url };
628
834
  // 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 });
835
+ recordPlayer(dir, { ...record, started, ...stop });
631
836
  const end = await outcomeOf(child, target.start.includes('{port}') ? port : null);
632
837
  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 };
838
+ if (end.state === 'running') return { state: 'running', ...record, started, ...stop };
839
+ rmSync(playerFile(dir), { force: true });
840
+ if (end.state === 'launched')
841
+ return { state: 'launched', id, ...main, target: targetName, open, url };
842
+ if (end.state === 'silent') killTree(child.pid);
843
+ undo();
844
+ const why = end.state === 'silent' ? `did not answer on port ${port}` : `failed (${end.why})`;
845
+ throw new Error(withTail(`play.targets.${targetName}.start ${why}`, playerLog(dir)));
657
846
  });
658
847
  }
659
848
 
849
+ /** The snapshot card `id` holds, or the checkout's for null; none throws what to do. */
850
+ function heldKey(dir, id) {
851
+ const link = readJson(linkOf(dir, id ?? MAIN));
852
+ const key = KEY_RE.test(link?.snap ?? '') && !link.released ? link.snap : null;
853
+ if (key && existsSync(snapOf(dir, key)) && existsSync(snapFactsOf(dir, key))) return key;
854
+ throw new Error(
855
+ id
856
+ ? `${id} has no build: ai-factory gcf playtest build ${id}`
857
+ : 'main has no build: ai-factory gcf playtest build --main',
858
+ );
859
+ }
860
+
660
861
  const NO_FACTS = {
862
+ key: null,
661
863
  commit: null,
662
864
  built_at: null,
663
865
  source: null,
664
866
  dirty: false,
665
867
  dirtied: [],
666
868
  size: null,
869
+ shared_with: [],
667
870
  };
668
871
 
669
872
  /**
@@ -678,38 +881,84 @@ function attemptProblem(attempt, going) {
678
881
  : (attempt?.problem ?? null);
679
882
  }
680
883
 
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));
884
+ /**
885
+ * A holder's snapshot and its attempt, read only. `shared_with`: the other cards that hold the
886
+ * same snapshot (d27).
887
+ */
888
+ function heldBuild(dir, who, links) {
889
+ const link = links.get(who);
890
+ const key = link && link !== UNREAD && !link.released ? link.snap : null;
891
+ const facts = key && existsSync(snapOf(dir, key)) ? readJson(snapFactsOf(dir, key)) : null;
892
+ const attempt = readJson(attemptOf(dir, who));
687
893
  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
894
  const problem = attemptProblem(attempt, going);
691
895
  if (!facts && !going && !problem) return null;
896
+ const shared = [...links]
897
+ .filter(([w, l]) => facts && w !== who && w !== MAIN && l !== UNREAD && holds(l, key))
898
+ .map(([w]) => w)
899
+ .sort();
692
900
 
693
- return { ...NO_FACTS, ...facts, ok: Boolean(facts), building: going, problem };
901
+ return {
902
+ ...NO_FACTS,
903
+ ...facts,
904
+ ...(facts ? { key, source: link.source ?? null, shared_with: shared } : {}),
905
+ ok: Boolean(facts),
906
+ building: going,
907
+ problem,
908
+ };
694
909
  }
695
910
 
696
- /** The project's targets and running player, read only: null with no `play:`. */
911
+ /**
912
+ * What a board and a chat show of the card: its snapshot, or the attempt under way or failed.
913
+ * `links`: linksOf once for a whole board.
914
+ */
915
+ export function buildOf(projectDir, id, status, links = linksOf(projectDir)) {
916
+ const dir = path.resolve(projectDir);
917
+ // A card back at work has no build to offer, unless one goes for it in its worktree right now.
918
+ if (status === 'ready' && !building(readJson(attemptOf(dir, id)))) return null;
919
+
920
+ return heldBuild(dir, id, links);
921
+ }
922
+
923
+ /**
924
+ * How the project plays, read only: its `play:` whole (d26), the checkout's snapshot (d30) and the
925
+ * running player; null with no `play:`.
926
+ */
697
927
  export function playFacts(projectDir, config) {
698
928
  let play;
699
929
  try {
700
930
  play = playOf(config);
701
931
  } catch (e) {
702
- return { problem: e.message, targets: [], running: null };
932
+ const none = { build: null, output: null, targets: [], main: null, running: null };
933
+
934
+ return { problem: e.message, ...none };
703
935
  }
704
936
 
705
937
  if (!play) return null;
706
- const p = playerOf(projectDir);
938
+ const dir = path.resolve(projectDir);
939
+ const p = playerOf(dir);
707
940
 
708
941
  return {
709
942
  problem: null,
710
- targets: Object.entries(play.targets).map(([name, t]) => ({ name, open: t.open })),
943
+ build: play.build,
944
+ output: play.output,
945
+ targets: Object.entries(play.targets).map(([name, t]) => ({
946
+ name,
947
+ start: t.start,
948
+ open: t.open,
949
+ stop: t.stop ?? null,
950
+ })),
951
+ main: heldBuild(dir, MAIN, linksOf(dir)),
711
952
  running: p
712
- ? { id: p.id, target: p.target, open: p.open, url: p.url, started: p.started }
953
+ ? {
954
+ id: p.id,
955
+ main: p.main === true,
956
+ snap: p.snap ?? null,
957
+ target: p.target,
958
+ open: p.open,
959
+ url: p.url,
960
+ started: p.started,
961
+ }
713
962
  : null,
714
963
  };
715
964
  }
@@ -738,6 +987,10 @@ export async function setupPlay(projectDir, opts) {
738
987
  throw new Error(`a target's name is one word: ${target}`);
739
988
  if (target === undefined && [start, words, stop].some((v) => v !== undefined))
740
989
  throw new Error('--start, --open and --stop belong to a --target');
990
+ // Now, not at the first build minutes later (d21).
991
+ if (output !== undefined) needOutput(output);
992
+ if (output !== undefined && !ignored(dir, output))
993
+ throw new Error(`play.output ${output} is not ignored by git: add it to .gitignore`);
741
994
  const file = path.join(dir, 'gcf', 'config.yml');
742
995
  const hash = await commitMove(dir, 'gcf(config): play', {
743
996
  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)
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.0",
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