gcf-aif-ext 0.27.1 → 0.28.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
@@ -346,6 +346,8 @@ The run layer of the methodology. Update both extensions together — `gcf-harne
346
346
  - 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`.
347
347
  - `gcf playtest session` — where main stands and a checklist per item: its build, what to check, how to get there, what to feel.
348
348
  - `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.
349
+ - `gcf playtest build <id> --wait|--queue`, `start <id> --target <t> [--device <id>] --wait|--queue`, `cancel <ticket>`, `devices <target>` — a build while a run works in the checkout waits on a ticket `.gcf-session/runs/.build-<n>.json` instead of a refusal; a main run lets it in between its cards by `.gcf-session/.main-run.yield`; `--queue` starts its own waiter and prints `{ticket}`; `cancel` takes a waiting ticket out or stops a build. `play.builds` names the project's builds (one in this release), each with its `plays_on` rows; a target names its `build`, the rows it serves (`for`), its `devices` script and `launches`
350
+ - `gcf play-notes <id> [--template]`, `gcf item show <id>` — the agent's `## Play notes` in a card's plan, and the handoff the core reads from it and the card: outcome, main question, Play by platform, what changed, what to try, what waits; also `items[].handoff` of `gcf board --json`
349
351
  - `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`.
350
352
  - `gcf board [--json]` — everything a board shows in one read.
351
353
 
@@ -408,7 +410,7 @@ Removal leaves `gcf/` and `cnlp.config.json` in place. It also leaves the pre-co
408
410
 
409
411
  - work items — `take <ids...> [--feature <id>]`, `item new [id] --title <text> --type <type>`, `submit`, `close`, `verdict <id> keep|tune|kill`, `decide <id> go|no|wontfix|known|close|continue|kill`, `block`, `unblock`, `drop`, `done`, `where`, `item amend <id> [--text <blocks>] [--add <lines>] [--title <text>] [--from <in-id>] [--dry-run --json]`
410
412
  - inbox and snapshot — `inbox [add <text> [--category <c>] [--detail <word>] | add --text-file <path|-> | category <in-id> | later <in-id> [--off] | categories | drop <in-id> | migrate]`, `live`, `live check`
411
- - runs and play — `context`, `plan check <id>`, `verify <id>`, `playtest`, `playtest session`, `playtest status`, `audit`
413
+ - runs and play — `context`, `plan check <id>`, `verify <id>`, `playtest`, `playtest session`, `playtest status`, `playtest devices`, `play-notes`, `item show`, `audit`
412
414
  - project phase and board — `phase`, `phase next [--reason]`, `board [--json]` (everything a board shows, in one read)
413
415
  - branches — `worktree <id>`, `verify <id> --mark`, `integrate [<id>...]`: a run in its own worktree, the `GCF-Verified` trailer, the merge into main and the move; every committed move holds `.gcf-session/main.lock`
414
416
  - design and sources — `design check`, `design export`, `design import`, `design part`, `design save`, `design discard`, `design commit`, `design migrate`, `anchor`, `section`, `quotes`, `lint`
package/commands/gcf.js CHANGED
@@ -6,6 +6,7 @@ import { existsSync, readFileSync } from 'node:fs';
6
6
  import { spawnSync } from 'node:child_process';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
+ import YAML from 'yaml';
9
10
 
10
11
  const EXT_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
11
12
  /** The commit a switch kept of what a card had staged apart from the disk. */
@@ -81,6 +82,15 @@ const ASSUME =
81
82
  '"<question> = <value>" (repeatable)';
82
83
  const repeated = (v, p) => [...p, v];
83
84
 
85
+ /** A row given on the command line: a YAML flow map, `{ device: phone, os: android }`. */
86
+ function flowMap(text) {
87
+ const v = YAML.parse(String(text).trim().startsWith('{') ? text : `{ ${text} }`);
88
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
89
+ throw new Error(`not a row of fields: ${text}`);
90
+
91
+ return v;
92
+ }
93
+
84
94
  /** A session's own command on its item keeps the item's running mark fresh. */
85
95
  const touchSession = async (id) => (await lib('session-mark')).touchSession(process.cwd(), id);
86
96
 
@@ -388,8 +398,21 @@ function sessionHead(s) {
388
398
  ];
389
399
  }
390
400
 
401
+ /** One card of the sheet: its handoff when it has one (docs/Handoff-Plan.md d4), else the old. */
402
+ function itemLines(c, linesOf) {
403
+ if (c.handoff && linesOf) return linesOf(c.id, c.handoff).map((l) => ` ${l}`);
404
+
405
+ return [
406
+ ...buildLine(c.build),
407
+ ` check: ${c.question}`,
408
+ ...(c.play_on?.length ? [` play on: ${c.play_on.join('; ')}`] : []),
409
+ ...c.reach.map((r) => ` try: ${r}`),
410
+ ...c.feel.map((f) => ` feel: ${f}`),
411
+ ];
412
+ }
413
+
391
414
  /** The session sheet: the build, then per item what to check and how to get there. */
392
- export function sessionText(s) {
415
+ export function sessionText(s, linesOf = null) {
393
416
  const lines = sessionHead(s);
394
417
  const decide = s.decisions.length
395
418
  ? [
@@ -424,10 +447,7 @@ export function sessionText(s) {
424
447
  '',
425
448
  `[ ] ${c.id} (${c.status}) [${c.system.join(',')}] ${c.title ?? c.intent ?? ''}`,
426
449
  );
427
- lines.push(...buildLine(c.build), ` check: ${c.question}`);
428
- if (c.play_on?.length) lines.push(` play on: ${c.play_on.join('; ')}`);
429
- for (const r of c.reach) lines.push(` try: ${r}`);
430
- for (const f of c.feel) lines.push(` feel: ${f}`);
450
+ lines.push(...itemLines(c, linesOf));
431
451
  }
432
452
 
433
453
  return [
@@ -462,7 +482,8 @@ function registerPlaytest(gcf) {
462
482
  .action(async (o) => {
463
483
  const r = await (await lib('playtest-list')).playtestSession(process.cwd());
464
484
  // Commander gives a flag both levels define to the parent: `playtest session --json`.
465
- out(o.json || playtest.opts().json, r, sessionText);
485
+ const { handoffLines } = await lib('handoff');
486
+ out(o.json || playtest.opts().json, r, (x) => sessionText(x, handoffLines));
466
487
  });
467
488
  registerPlay(playtest);
468
489
  }
@@ -480,6 +501,30 @@ const startLine = (r) =>
480
501
  ? `playing ${r.id ?? 'main'} on ${r.target} (pid ${r.pid}): ${r.open}`
481
502
  : `launched ${r.id ?? 'main'} on ${r.target}: ${r.open}`;
482
503
 
504
+ /** `playtest devices` as words: each device, whether it plays, and why not. */
505
+ function devicesText(r) {
506
+ if (r.problem) return [r.problem, r.tail].filter(Boolean).join('\n');
507
+ if (r.unavailable) return `${r.target}: ${r.unavailable}`;
508
+ if (!r.devices.length) return `${r.target}: no device found`;
509
+
510
+ return r.devices
511
+ .map((d) => {
512
+ const os = [d.os, d.os_version].filter(Boolean).join(' ');
513
+ const why = d.play ? 'ready' : (d.why ?? d.state);
514
+
515
+ return `${d.id ?? '?'} · ${d.name} · ${os || '?'} · ${why}`;
516
+ })
517
+ .join('\n');
518
+ }
519
+
520
+ /** A build ticket of the queue, as words. */
521
+ const ticketLine = (q) => {
522
+ const then = q.job.start ? ` then ${q.job.start.target}` : '';
523
+ const state = q.building ? 'building' : q.after ? `waits after ${q.after}` : 'waits';
524
+
525
+ return `ticket ${q.ticket}: ${q.job.build ?? 'main'}${then}, ${state}`;
526
+ };
527
+
483
528
  /** The player's line and the targets of `playtest status`. */
484
529
  function statusText(s) {
485
530
  if (!s) return 'how to play is not set up: ai-factory gcf playtest setup';
@@ -490,6 +535,7 @@ function statusText(s) {
490
535
  ? `playing ${s.running.id ?? 'main'} on ${s.running.target}: ${s.running.open}`
491
536
  : 'no player is running',
492
537
  `targets: ${s.targets.map((t) => t.name).join(', ') || 'none'}`,
538
+ ...(s.queue ?? []).map(ticketLine),
493
539
  ].join('\n');
494
540
  }
495
541
 
@@ -501,15 +547,25 @@ function registerPlayBuild(playtest, jsonOf) {
501
547
  .option('--main', 'the checkout with its uncommitted edits, not a card')
502
548
  .option('--fresh', 'build even when a snapshot of this code is there, and replace it')
503
549
  .option('--from <worktree>', "the card's worktree, for a run whose code is not in main yet")
550
+ .option('--wait', 'a busy checkout is waited for on a ticket, in this process')
551
+ .option('--queue', 'a ticket and its own waiter: prints {ticket} and ends at once')
504
552
  .option('--json', 'machine output')
505
553
  .action(async (id, o) => {
506
554
  const play = await lib('play');
507
555
  const fresh = Boolean(o.fresh);
508
556
  const main = oneOf(id, o.main);
509
557
  if (main && o.from) throw new Error("--from names a card's worktree: not with --main");
558
+ if (o.queue) {
559
+ const job = { build: main ? null : id, from: o.from ?? null, fresh };
560
+ const q = await play.queueJob(process.cwd(), job);
561
+
562
+ return out(jsonOf(o), q, (x) => `ticket ${x.ticket}: the build waits its turn`);
563
+ }
564
+
565
+ const wait = Boolean(o.wait);
510
566
  const r = main
511
- ? await play.buildMain(process.cwd(), { fresh })
512
- : await play.buildItem(process.cwd(), id, { from: o.from ?? null, fresh });
567
+ ? await play.buildMain(process.cwd(), { fresh, wait })
568
+ : await play.buildItem(process.cwd(), id, { from: o.from ?? null, fresh, wait });
513
569
  const who = id ?? 'main';
514
570
  out(jsonOf(o), r, (b) =>
515
571
  b.ok
@@ -524,18 +580,56 @@ function registerPlayBuild(playtest, jsonOf) {
524
580
  .description("Start a card's snapshot, or the checkout's (--main), on a target: one player")
525
581
  .option('--main', "the checkout's snapshot, not a card's")
526
582
  .requiredOption('--target <name>', 'a target of play.targets')
583
+ .option('--device <id>', "a device of the target's devices answer: {device} in its commands")
584
+ .option('--wait', 'no build yet: build it on a ticket first, then start (this process waits)')
585
+ .option('--queue', 'no build yet: a ticket and its own waiter; prints {ticket} at once')
527
586
  .option('--json', 'machine output')
528
587
  .action(async (id, o) => {
529
- const main = oneOf(id, o.main);
530
- const r = await (await lib('play')).startPlay(process.cwd(), main ? null : id, o.target);
588
+ const play = await lib('play');
589
+ const who = oneOf(id, o.main) ? null : id;
590
+ if (o.queue && !play.hasBuildOf(process.cwd(), who)) {
591
+ const start = { target: o.target, device: o.device ?? null };
592
+ const q = await play.queueJob(process.cwd(), { build: who, start });
593
+
594
+ return out(jsonOf(o), q, (x) => `ticket ${x.ticket}: the build waits, the start after it`);
595
+ }
596
+
597
+ const how = { wait: Boolean(o.wait), device: o.device ?? null };
598
+ const r = await play.startPlay(process.cwd(), who, o.target, how);
531
599
  out(jsonOf(o), r, startLine);
532
600
  });
533
601
  }
534
602
 
603
+ /** The build queue (docs/Handoff-Plan.md d6): a ticket cancelled; a target's devices (d5). */
604
+ function registerPlayQueue(playtest, jsonOf) {
605
+ playtest
606
+ .command('devices <target>')
607
+ .description("The devices a target's script finds, each under the plays_on row it fits")
608
+ .option('--json', 'machine output')
609
+ .action(async (target, o) => {
610
+ const r = await (await lib('devices')).devicesOf(process.cwd(), target);
611
+ out(jsonOf(o), r, devicesText);
612
+ if (r.problem) process.exitCode = 1;
613
+ });
614
+ playtest
615
+ .command('cancel <ticket>')
616
+ .description('Cancel a build ticket: a waiting one goes, a building one is stopped')
617
+ .option('--json', 'machine output')
618
+ .action(async (ticket, o) => {
619
+ const n = Number(ticket);
620
+ if (!Number.isInteger(n) || n < 1) throw new Error(`${ticket} is no ticket number`);
621
+ const r = await (await lib('build-queue')).cancelTicket(process.cwd(), n);
622
+ out(jsonOf(o), r, (x) =>
623
+ x.was === 'gone' ? `ticket ${n} is not in the queue` : `ticket ${n} cancelled (${x.was})`,
624
+ );
625
+ });
626
+ }
627
+
535
628
  /** The player and the project's play: setup (docs/Play-Plan.md). */
536
629
  function registerPlay(playtest) {
537
630
  const jsonOf = (o) => o.json || playtest.opts().json;
538
631
  registerPlayBuild(playtest, jsonOf);
632
+ registerPlayQueue(playtest, jsonOf);
539
633
  playtest
540
634
  .command('stop')
541
635
  .description('Stop the running player')
@@ -562,12 +656,23 @@ function registerPlay(playtest) {
562
656
  .option('--start <cmd>', 'starts the game: {dir} the snapshot, {port} a free port, {lan}')
563
657
  .option('--open <text>', 'what to open: a URL or words, with the same placeholders')
564
658
  .option('--stop <cmd>', 'runs after the player stops')
659
+ .option('--for <row>', 'the rows the target serves: "{ device: phone, os: android }"', flowMap)
660
+ .option('--devices <cmd>', 'lists the devices: a JSON line each (id, name, device, os, state)')
661
+ .option('--launches', 'the start installs and launches, then ends: wait for its exit')
662
+ .option('--no-launches', 'the start keeps running while the game plays')
663
+ .option(
664
+ '--plays-on <row>',
665
+ 'a row the build plays on: "{ device: phone, os: android, os_min: 10 }" (repeatable)',
666
+ (v, p) => [...(p ?? []), flowMap(v)],
667
+ undefined,
668
+ )
565
669
  .option('--remove-target <name>', 'take a target away')
566
670
  .option('--no-commit', 'leave the change uncommitted')
567
671
  .action(async (o) => {
568
672
  await operatorOnly('playtest setup');
569
673
  const r = await (await lib('play')).setupPlay(process.cwd(), { ...o, open: o.open });
570
674
  console.log(`play: ${r.play.build} into ${r.play.output}${shortHash(r.hash)}`);
675
+ for (const w of r.play.warnings) console.log(`warning: ${w}`);
571
676
  });
572
677
  }
573
678
 
@@ -586,6 +691,23 @@ const removeOptions = (cmd) =>
586
691
  .option('--remove', 'also create a removal item: the code is in main')
587
692
  .option('--no-remove', 'no removal item: the code never reached main');
588
693
 
694
+ /** The agent's part of a card's handoff (docs/Handoff-Plan.md d3). */
695
+ function registerPlayNotes(gcf) {
696
+ gcf
697
+ .command('play-notes <id>')
698
+ .description("A card's ## Play notes: its template, or what its plan holds and lacks")
699
+ .option('--template', "print the section to fill, with the card's rows of play_on")
700
+ .option('--json', 'machine output')
701
+ .action(async (id, o) => {
702
+ const notes = await lib('play-notes');
703
+ if (o.template) return console.log(await notes.playNotesTemplate(process.cwd(), id));
704
+ const item = (await (await lib('ledger')).buildLedger(process.cwd())).item(id);
705
+ if (!item) throw new Error(`${id} is not on the board`);
706
+ const r = await notes.playNotesCheck(process.cwd(), item);
707
+ out(o.json, r, (x) => x.warnings.join('\n') || 'the play notes are whole');
708
+ });
709
+ }
710
+
589
711
  function registerVerdict(gcf) {
590
712
  removeOptions(
591
713
  gcf
@@ -602,7 +724,7 @@ function registerVerdict(gcf) {
602
724
  )
603
725
  .option(
604
726
  '--played-on <line>',
605
- 'where you played it, a line of platforms in game.md (repeatable; a note, not a must)',
727
+ 'where you played it, a build of play.builds (repeatable; a note, not a must)',
606
728
  repeated,
607
729
  [],
608
730
  )
@@ -1175,8 +1297,31 @@ function registerMoves(gcf) {
1175
1297
  });
1176
1298
  }
1177
1299
 
1300
+ /** A card and its handoff (docs/Handoff-Plan.md d4): `item <id>` would meet the subcommands. */
1301
+ function registerItemShow(item) {
1302
+ item
1303
+ .command('show <id>')
1304
+ .description('A card and its handoff to play: blocks 0-6, the technical one in a line')
1305
+ .option('--json', 'machine output')
1306
+ .action(async (id, o) => {
1307
+ const ledger = await (await lib('ledger')).buildLedger(process.cwd());
1308
+ const card = ledger.item(id);
1309
+ if (!card) throw new Error(`${id} is not on the board`);
1310
+ const { handoffLines, handoffOf } = await lib('handoff');
1311
+ const handoff = await handoffOf(process.cwd(), id, { ledger });
1312
+ const r = { id, title: card.data.title ?? null, status: card.data.status, handoff };
1313
+ out(o.json, r, (x) =>
1314
+ [
1315
+ `${x.id} (${x.status})${x.title ? ` ${x.title}` : ''}`,
1316
+ ...(x.handoff ? handoffLines(x.id, x.handoff) : ['it waits for nothing: no handoff']),
1317
+ ].join('\n'),
1318
+ );
1319
+ });
1320
+ }
1321
+
1178
1322
  function registerItem(gcf) {
1179
1323
  const item = gcf.command('item').description('Work items in gcf/work/ (Methodology §3)');
1324
+ registerItemShow(item);
1180
1325
  item
1181
1326
  .command('new [id]')
1182
1327
  .description(
@@ -1473,6 +1618,7 @@ function registerItemMoves(gcf) {
1473
1618
  claimedBy(o, id);
1474
1619
  const r = await (await ops()).submitItem(process.cwd(), id, verifiedMove(o));
1475
1620
  console.log(`${r.id} → ${r.status}${shortHash(r.hash)}`);
1621
+ notesWarned(r);
1476
1622
  });
1477
1623
  gcf
1478
1624
  .command('close <id>')
@@ -1494,9 +1640,15 @@ function registerItemMoves(gcf) {
1494
1640
  await ops()
1495
1641
  ).closeItem(process.cwd(), id, { ...verifiedMove(o), constraints: o.constraint });
1496
1642
  console.log(`closed ${r.id}${r.unplayed ? ' → unplayed' : ''}${shortHash(r.hash)}`);
1643
+ notesWarned(r);
1497
1644
  });
1498
1645
  }
1499
1646
 
1647
+ /** What the card's ## Play notes lack (docs/Handoff-Plan.md d3): a warning, never a refusal. */
1648
+ const notesWarned = (r) => {
1649
+ for (const w of r.play_notes_warnings ?? []) console.log(`play notes: ${w}`);
1650
+ };
1651
+
1500
1652
  function registerDecide(gcf) {
1501
1653
  const ops = () => lib('work-ops');
1502
1654
  removeOptions(
@@ -2310,6 +2462,7 @@ export function register(program) {
2310
2462
  registerAudit(gcf);
2311
2463
  registerPlaytest(gcf);
2312
2464
  registerVerdict(gcf);
2465
+ registerPlayNotes(gcf);
2313
2466
  registerAnchor(gcf);
2314
2467
  registerSection(gcf);
2315
2468
  registerQuotes(gcf);
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.27.1",
4
+ "version": "0.28.0",
5
5
  "description": "Game Context Framework for AI Factory",
6
6
  "skills": [
7
7
  "skills/gcf-init",
@@ -227,6 +227,7 @@ export const DENY_GROUPS = [
227
227
  'ai-factory gcf playtest build*',
228
228
  'ai-factory gcf playtest start*',
229
229
  'ai-factory gcf playtest stop*',
230
+ 'ai-factory gcf playtest cancel*',
230
231
  ),
231
232
  },
232
233
  {
package/lib/audit-core.js CHANGED
@@ -18,6 +18,8 @@ import { inboxVocabulary } from './domain.js';
18
18
  import { gatePolicy, verdictDeferred } from './gates.js';
19
19
  import { milestoneState } from './milestone-state.js';
20
20
  import { mainWork } from './shelf.js';
21
+ import { playOnIssues } from './play-on.js';
22
+ import { platformsOf } from './playtest-list.js';
21
23
 
22
24
  function git(args, cwd) {
23
25
  // A blame of a long file overflows the 1 MiB default, and an overflow reads as a git failure.
@@ -69,6 +71,7 @@ function runningOf(projectDir, id) {
69
71
  * @property {boolean} index_drift
70
72
  * @property {Array<{id: string, status: string}>} illegal_status
71
73
  * @property {Array<{id: string, commits: number | null, limit: number}>} stale_questions
74
+ * @property {{errors: string[], warnings: string[]}} play_on cards' build names (lib/play-on.js)
72
75
  * @property {number} [schema]
73
76
  * @property {Array<{id: string, type: string, gate: string, status: string, system: string[],
74
77
  * depends: string[], parent: string | null, tune_count: number, parallel: string,
@@ -122,10 +125,10 @@ export async function audit(projectDir) {
122
125
  illegal_status: [],
123
126
  stale_questions: staleQuestions(projectDir, root, config),
124
127
  inbox: await inboxProblems(root, inboxVocabulary()),
128
+ play_on: playOnIssues(items, config, await platformsOf(root)),
125
129
  };
126
130
  // The harness gate reads everything from this one report — it never parses gcf/ itself.
127
- report.schema = config.schema;
128
- report.gates = config.gates;
131
+ Object.assign(report, { schema: config.schema, gates: config.gates });
129
132
  report.items = items.map((c) => ({
130
133
  id: c.data.id,
131
134
  type: c.data.type,
@@ -395,9 +398,16 @@ const docAlerts = (report) => [
395
398
  Object.keys(report.linter).length && 'П2 linter findings in systems docs',
396
399
  report.index_drift && 'INDEX drift (regenerate)',
397
400
  report.design?.blocking && `${report.design.blocking} blocking design finding(s)`,
401
+ ...playOnAlerts(report.play_on),
398
402
  ...inboxAlerts(report.inbox),
399
403
  ];
400
404
 
405
+ /** A card's play_on and played_on name builds (docs/Handoff-Plan.md d8). */
406
+ const playOnAlerts = (p) => [
407
+ p.errors.length && `${p.errors.length} play_on name(s) of no build`,
408
+ p.warnings.length && `${p.warnings.length} play_on line(s) of platforms: name builds (Set up)`,
409
+ ];
410
+
401
411
  /** Alerts about gcf/inbox/: the old one-line file, files that are no entry, broken pictures. */
402
412
  const inboxAlerts = (i) => [
403
413
  i.legacy &&
package/lib/board.js CHANGED
@@ -28,6 +28,7 @@ import { designState } from './design-parts.js';
28
28
  import { gatePolicy } from './gates.js';
29
29
  import { milestoneState } from './milestone-state.js';
30
30
  import { buildOf, linksOf, playFacts } from './play.js';
31
+ import { handoffOf } from './handoff.js';
31
32
 
32
33
  // The version of the JSON below (Methodology §11): a board refuses one it does not know. Bump it
33
34
  // when a field changes meaning or goes away; a new field does not bump it.
@@ -321,6 +322,13 @@ async function attachmentsOf(projectDir, id) {
321
322
  }
322
323
 
323
324
  /** One item of the board. */
325
+ /** `handoff` of a card that waits; nothing for any other. */
326
+ async function handoffPart(projectDir, id, read) {
327
+ const handoff = await handoffOf(projectDir, id, read);
328
+
329
+ return handoff ? { handoff } : {};
330
+ }
331
+
324
332
  async function itemOf(projectDir, c, { verified, shelved, ledger, harness, config, links }) {
325
333
  const build = buildOf(projectDir, String(c.data.id), c.data.status, links);
326
334
  const id = String(c.data.id);
@@ -371,6 +379,8 @@ async function itemOf(projectDir, c, { verified, shelved, ledger, harness, confi
371
379
  log: logOf(projectDir, id),
372
380
  // Its build to play (docs/Play-Setup-Plan.md), null while it has none.
373
381
  build,
382
+ // What a card that waits hands to the operator (docs/Handoff-Plan.md d4): read from its plan.
383
+ ...(await handoffPart(projectDir, id, { ledger, config, links })),
374
384
  // Filled by board() from the inbox.
375
385
  lessons: 0,
376
386
  ...(await progress(projectDir, c)),
@@ -0,0 +1,235 @@
1
+ // A build waits, it is not refused (docs/Handoff-Plan.md d6): a request writes a ticket
2
+ // `.gcf-session/runs/.build-<n>.json` and its waiter takes its turn. The checkout is entered by a
3
+ // claim of the main run lock when nobody holds it, or by the yield of a main run between its cards
4
+ // (`.gcf-session/.main-run.yield`: `{run, ticket}`, the builder adds its pid). The run never
5
+ // withdraws a yield: it waits until the ticket is gone or its waiter is dead. The dot keeps a
6
+ // ticket's name apart from a card's id, as `.main-run` does.
7
+ import { existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { mkdir } from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { alive, claimMainRun, MAIN_RUN, withMainLock } from './main-lock.js';
11
+
12
+ const runsOf = (dir) => path.join(dir, '.gcf-session', 'runs');
13
+ const TICKET_RE = /^\.build-(\d+)\.json$/;
14
+ export const ticketFile = (dir, n) => path.join(runsOf(dir), `.build-${n}.json`);
15
+ /** What a queued waiter ended with: the board reads it when the ticket is gone. */
16
+ export const outcomeFile = (dir, n) => path.join(runsOf(dir), `.build-${n}.out.json`);
17
+ const seqFile = (dir) => path.join(runsOf(dir), '.build-seq');
18
+ export const yieldFile = (dir) => path.join(dir, '.gcf-session', `${MAIN_RUN}.yield`);
19
+ const POLL_MS = 300;
20
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
21
+ export const CANCELLED = 'stopped by the operator';
22
+
23
+ function readJson(file) {
24
+ try {
25
+ return JSON.parse(readFileSync(file, 'utf8'));
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ function writeJson(file, value) {
32
+ const tmp = `${file}.tmp-${process.pid}`;
33
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
34
+ // Windows holds a fresh file for a moment (a scanner): the rename tries again.
35
+ for (let attempt = 1; ; attempt++)
36
+ try {
37
+ return renameSync(tmp, file);
38
+ } catch (e) {
39
+ if (!['EPERM', 'EACCES', 'EBUSY'].includes(e.code) || attempt >= 10) throw e;
40
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
41
+ }
42
+ }
43
+
44
+ export const readTicket = (dir, n) => readJson(ticketFile(dir, n));
45
+ export const readYield = (dir) => readJson(yieldFile(dir));
46
+
47
+ /**
48
+ * The tickets in their order; one whose waiter is dead is left out (a sweep takes it).
49
+ * @returns {Array<{n: number, pid: number, job: object, at: string, after?: string | null,
50
+ * building?: boolean, cancelled?: boolean}>}
51
+ */
52
+ export function ticketsOf(projectDir) {
53
+ const dir = path.resolve(projectDir);
54
+ if (!existsSync(runsOf(dir))) return [];
55
+
56
+ return readdirSync(runsOf(dir))
57
+ .map((name) => TICKET_RE.exec(name))
58
+ .filter(Boolean)
59
+ .map((m) => readTicket(dir, Number(m[1])))
60
+ .filter((t) => t && alive(t.pid))
61
+ .sort((a, b) => a.n - b.n);
62
+ }
63
+
64
+ /** The live builder a yield let in, or null: it holds the checkout even when its run is dead. */
65
+ export function builderOf(projectDir) {
66
+ const y = readYield(path.resolve(projectDir));
67
+
68
+ return Number.isInteger(y?.builder) && y.builder !== process.pid && alive(y.builder)
69
+ ? y.builder
70
+ : null;
71
+ }
72
+
73
+ /** A ticket for `job`, numbered past every one before: a reader that saw `n` go never sees it. */
74
+ export async function ticketOpen(projectDir, job, pid = process.pid) {
75
+ const dir = path.resolve(projectDir);
76
+ await mkdir(runsOf(dir), { recursive: true });
77
+
78
+ return withMainLock(dir, async () => {
79
+ const n = (Number(readJson(seqFile(dir))?.n) || 0) + 1;
80
+ writeJson(seqFile(dir), { n });
81
+ writeJson(ticketFile(dir, n), { n, pid, job, at: new Date().toISOString(), after: null });
82
+
83
+ return n;
84
+ });
85
+ }
86
+
87
+ /** Mark ticket `n` (its waiter, a start of building): what is not in `fields` stays. */
88
+ export function ticketSet(dir, n, fields) {
89
+ const t = readTicket(dir, n);
90
+ if (t) writeJson(ticketFile(dir, n), { ...t, ...fields });
91
+
92
+ return t;
93
+ }
94
+
95
+ /** The ticket goes with what its waiter ended with; a yield naming it lets its run go on. */
96
+ export function ticketClose(projectDir, n, outcome = null) {
97
+ const dir = path.resolve(projectDir);
98
+ if (outcome) writeJson(outcomeFile(dir, n), { n, at: new Date().toISOString(), ...outcome });
99
+ rmSync(ticketFile(dir, n), { force: true });
100
+ }
101
+
102
+ /**
103
+ * What holds the checkout ahead of ticket `n`, as words for "waits: after X": the card a main run
104
+ * works, another ticket, or a build by click. Null when nothing does.
105
+ */
106
+ function aheadOf(dir, n) {
107
+ const before = ticketsOf(dir).find((t) => t.n < n);
108
+ if (before) return `ticket ${before.n}`;
109
+ const lock = path.join(runsOf(dir), `${MAIN_RUN}.lock`);
110
+ const text = existsSync(lock) ? readFileSync(lock, 'utf8').split('\n') : [];
111
+ if (!text.length || !alive(Number(text[0]))) return null;
112
+
113
+ return text[1]?.trim() ? `card ${text[1].trim()}` : 'a build';
114
+ }
115
+
116
+ /** The run's yield to ticket `n`: its builder goes in, and out with the release. */
117
+ function byYield(dir, n) {
118
+ const y = readYield(dir);
119
+ if (y?.ticket !== n || !alive(y.run) || (y.builder && alive(y.builder))) return null;
120
+ writeJson(yieldFile(dir), { ...y, builder: process.pid });
121
+ const release = async () => {
122
+ const now = readYield(dir);
123
+ if (now?.builder === process.pid) writeJson(yieldFile(dir), { ...now, builder: null });
124
+ };
125
+
126
+ return { release, yielded: true };
127
+ }
128
+
129
+ /**
130
+ * Enter the checkout for ticket `n` under the main lock: by the run's yield that names this ticket
131
+ * while that run lives, or by a claim when nobody holds it. `from`: a worktree build needs no
132
+ * checkout, only its turn. Null: not yet.
133
+ * @returns {Promise<null | 'gone' | {release: (() => Promise<void>) | null, yielded: boolean}>}
134
+ */
135
+ async function entered(dir, n, from) {
136
+ if (ticketsOf(dir)[0]?.n !== n) return null;
137
+ if (from) return { release: null, yielded: false };
138
+ const yielded = byYield(dir, n);
139
+ if (yielded) return yielded;
140
+ dropDeadYield(dir);
141
+ const release = builderOf(dir) ? null : await claimMainRun(dir);
142
+
143
+ return release ? { release, yielded: false } : null;
144
+ }
145
+
146
+ /**
147
+ * One look under the main lock, which a cancel takes too: a cancelled ticket is gone; one let in
148
+ * is marked `building` before a cancel can see it waiting; one still waiting names what it waits
149
+ * behind. Its file is written only here and by a cancel, so a cancel's removal stays.
150
+ */
151
+ async function enter(dir, n, from) {
152
+ return withMainLock(dir, async () => {
153
+ if (cancelled(dir, n)) return 'gone';
154
+ const got = await entered(dir, n, from);
155
+ const after = got ? null : aheadOf(dir, n);
156
+ if (got || readTicket(dir, n)?.after !== after)
157
+ ticketSet(dir, n, got ? { building: true, after: null } : { after });
158
+
159
+ return got;
160
+ });
161
+ }
162
+
163
+ /** A yield whose run and builder are both dead holds nothing. */
164
+ function dropDeadYield(dir) {
165
+ const y = readYield(dir);
166
+ if (y && !alive(y.run) && !builderOf(dir)) rmSync(yieldFile(dir), { force: true });
167
+ }
168
+
169
+ /**
170
+ * Wait for ticket `n`'s turn; its removal (a cancel) ends the wait with an error. `after` on the
171
+ * ticket says what it waits behind.
172
+ */
173
+ export async function waitTurn(projectDir, n, { from = null } = {}) {
174
+ const dir = path.resolve(projectDir);
175
+ for (;;) {
176
+ const got = await enter(dir, n, from);
177
+ if (got === 'gone') throw new Error(CANCELLED);
178
+ if (got) return got;
179
+ await sleep(POLL_MS);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The operator's cancel: a waiting ticket goes, its waiter sees that and ends; a building one is
185
+ * marked `cancelled`, its waiter kills the build's tree and publishes nothing. Waits for the
186
+ * ticket to go, up to `waitMs`.
187
+ * @returns {Promise<{n: number, was: 'waiting' | 'building' | 'gone'}>}
188
+ */
189
+ export async function cancelTicket(projectDir, n, { waitMs = 15000 } = {}) {
190
+ const dir = path.resolve(projectDir);
191
+ const was = await withMainLock(dir, async () => {
192
+ const t = readTicket(dir, n);
193
+ if (!t) return 'gone';
194
+ if (t.building && alive(t.pid)) {
195
+ ticketSet(dir, n, { cancelled: true });
196
+
197
+ return 'building';
198
+ }
199
+
200
+ ticketClose(dir, n, { ok: false, problem: CANCELLED });
201
+
202
+ return 'waiting';
203
+ });
204
+ for (const until = Date.now() + waitMs; existsSync(ticketFile(dir, n)) && Date.now() < until;)
205
+ await sleep(100);
206
+
207
+ return { n, was };
208
+ }
209
+
210
+ /** Whether ticket `n` was cancelled, or is gone: a build for it must publish nothing. */
211
+ export const cancelled = (dir, n) => {
212
+ const t = readTicket(dir, n);
213
+
214
+ return !t || t.cancelled === true;
215
+ };
216
+
217
+ /**
218
+ * Tickets of dead waiters go, an old waiter's outcome too, and a yield whose run and builder are
219
+ * both dead. Under the main lock.
220
+ */
221
+ export function sweepTickets(projectDir) {
222
+ const dir = path.resolve(projectDir);
223
+ if (!existsSync(runsOf(dir))) return;
224
+ for (const name of readdirSync(runsOf(dir))) {
225
+ const m = /^\.build-\d+\.(json|out\.json)$/.exec(name);
226
+ const file = m && path.join(runsOf(dir), name);
227
+ if (file && !keeps(m[1], readJson(file))) rmSync(file, { force: true });
228
+ }
229
+
230
+ dropDeadYield(dir);
231
+ }
232
+
233
+ /** A ticket keeps while its waiter lives; an outcome, for an hour. */
234
+ const keeps = (kind, t) =>
235
+ kind === 'json' ? Boolean(t && alive(t.pid)) : Date.now() - Date.parse(t?.at ?? 0) < 3600000;
@@ -0,0 +1,5 @@
1
+ // The waiter of a `--queue` ticket (lib/build-queue.js): `node build-waiter.js <dir> <n>`.
2
+ import { runTicket } from './play.js';
3
+
4
+ const [dir, n] = process.argv.slice(2);
5
+ await runTicket(dir, Number(n));