gcf-board 0.25.0 → 0.27.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.
@@ -24,7 +24,7 @@ import { isUpload, saveUpload, UPLOAD_MAX } from './upload.js';
24
24
  import { addProject, homeDir, listProjects, projectOf, removeProject, yoloFile, } from './registry.js';
25
25
  import { allThemes } from './themes.js';
26
26
  import { askIfDue, askUsage, configureUsage, lastUsage } from './usage.js';
27
- import { activeRuns, adoptRuns, busyCheck, keepProjects, sweepRuns, closeReport, forgetProject, resumeQueue, holdProject, retryWaiting, runsOf, setAutopilot, startRun, unqueue, whileClickBuilds, } from './runs.js';
27
+ import { activeRuns, adoptRuns, busyCheck, keepProjects, sweepRuns, closeReport, forgetProject, resumeQueue, holdProject, retryWaiting, runsOf, setAutopilot, startRun, unqueue, ticketState, watchTickets, } from './runs.js';
28
28
  import { acceptProposal, agentDefaults, agentPresets, chatCard, deniedGroupIn, lastDeniedOf, lastRunEnd, chatOf, entryTalk, listTalks, openTalk, pickTalk, prepareTalk, startDesign, startTalk, stopTalk, talkEntry, talkId, talkLive, talkSaid, talkWaits, watchTalks, writeTalk, } from './talks.js';
29
29
  import { accountSettings, saveAccountSettings, threadDir, threadOfEntry } from 'gcf-session';
30
30
  const send = (res, status, body) => {
@@ -75,9 +75,49 @@ const treeArgs = (url) => {
75
75
  return tree && tree !== 'main' ? [`--worktree=${tree}`] : [];
76
76
  };
77
77
  /** Parse the JSON a command printed, or say what it printed instead. */
78
- // How long the board waits for a build: the core ends it by the project's `dod_timeout_min`, and
79
- // the board must not cut it sooner, on POSIX with its engine still going.
80
- const PLAY_BUILD_MS = 24 * 60 * 60_000;
78
+ // A start that installs on a device (`launches`) takes longer than the CLI's two minutes.
79
+ const PLAY_START_MS = 30 * 60_000;
80
+ const WORD_RE = /^[\w][\w-]*$/;
81
+ // A device id goes into a shell command: the core takes only these characters (d5).
82
+ const DEVICE_RE = /^\w[\w.:-]*$/;
83
+ const PROFILE_RE = /^(?:debug|release)$/;
84
+ /** The core's command for a Play route, its body checked: words where words go. */
85
+ export function playArgs(what, body) {
86
+ const word = (v, name, re = WORD_RE) => {
87
+ if (typeof v !== 'string' || !re.test(v))
88
+ throw new HttpError(400, `${name} is one word`);
89
+ return v;
90
+ };
91
+ const flag = (v, name) => {
92
+ if (v !== undefined && typeof v !== 'boolean')
93
+ throw new HttpError(400, `${name} is true or false`);
94
+ return v === true;
95
+ };
96
+ // A card, or the checkout as it is ("Play main", docs/Play-Setup-Plan.md d30).
97
+ const who = () => (flag(body.main, 'main') ? ['--main'] : [word(body.id, 'id')]);
98
+ const opt = (v, name, re = WORD_RE) => v === undefined || v === null ? [] : [`--${name}`, word(v, name, re)];
99
+ // Which profile (docs/Handoff-Plan.md t18): debug when none is named.
100
+ const profile = () => opt(body.profile, 'profile', PROFILE_RE);
101
+ if (what === 'stop')
102
+ return ['gcf', 'playtest', 'stop', '--json'];
103
+ if (what === 'devices')
104
+ return ['gcf', 'playtest', 'devices', word(body.target, 'target'), '--json'];
105
+ if (what === 'build')
106
+ return [
107
+ ...['gcf', 'playtest', 'build', ...who(), '--queue', '--json'],
108
+ // "Build again" (d23): a snapshot of the same code is replaced, not taken.
109
+ ...(flag(body.fresh, 'fresh') ? ['--fresh'] : []),
110
+ // Which build (t16): else the card's own, else auto_build.
111
+ ...opt(body.of, 'of'),
112
+ ...profile(),
113
+ ];
114
+ return [
115
+ ...['gcf', 'playtest', 'start', ...who(), '--queue', '--json'],
116
+ ...['--target', word(body.target, 'target')],
117
+ ...opt(body.device, 'device', DEVICE_RE),
118
+ ...profile(),
119
+ ];
120
+ }
81
121
  function jsonOf(r, what) {
82
122
  try {
83
123
  return JSON.parse(r.out);
@@ -756,39 +796,40 @@ export function createApp(o) {
756
796
  [
757
797
  // Playing a card: the project's own commands, so POSTs with their Origin checked. A refusal
758
798
  // comes back as an error with its words; a build that failed is an answer (`ok: false`).
799
+ // A build, and a start with no build yet, go on a ticket (docs/Handoff-Plan.md d6, d9):
800
+ // the core starts its own waiter and answers `{ticket}` at once, which outlives this board.
759
801
  'POST',
760
- /^\/api\/p\/([^/]+)\/play\/(build|start|stop)$/,
802
+ /^\/api\/p\/([^/]+)\/play\/(build|start|stop|devices)$/,
761
803
  async (req, res, m) => {
762
804
  const p = await projectOf(m[1]);
763
- const body = await bodyOf(req);
764
- const word = (v, what) => {
765
- if (typeof v !== 'string' || !/^[\w][\w-]*$/.test(v))
766
- throw new HttpError(400, `${what} is one word`);
767
- return v;
768
- };
769
- const flag = (v, what) => {
770
- if (v !== undefined && typeof v !== 'boolean')
771
- throw new HttpError(400, `${what} is true or false`);
772
- return v === true;
773
- };
774
- // A card, or the checkout as it is ("Play main", docs/Play-Setup-Plan.md d30).
775
- const who = () => (flag(body.main, 'main') ? ['--main'] : [word(body.id, 'id')]);
776
- const args = m[2] === 'stop'
777
- ? ['gcf', 'playtest', 'stop', '--json']
778
- : m[2] === 'build'
779
- ? [
780
- ...['gcf', 'playtest', 'build', ...who(), '--json'],
781
- // "Build again" (d23): a snapshot of the same code is replaced, not taken.
782
- ...(flag(body.fresh, 'fresh') ? ['--fresh'] : []),
783
- ]
784
- : [
785
- ...['gcf', 'playtest', 'start', ...who(), '--json'],
786
- ...['--target', word(body.target, 'target')],
787
- ];
788
- // A build of a real game takes minutes.
789
- const r = m[2] === 'build'
790
- ? await whileClickBuilds(p, () => cli(p, args, PLAY_BUILD_MS))
791
- : await cli(p, args);
805
+ const args = playArgs(m[2], await bodyOf(req));
806
+ watchTickets(p);
807
+ const r = await cli(p, args, m[2] === 'start' ? PLAY_START_MS : undefined);
808
+ broadcast({ type: 'board', project: p.name });
809
+ try {
810
+ send(res, 200, JSON.parse(r.out));
811
+ }
812
+ catch {
813
+ throw new HttpError(409, briefError(r.err || r.out));
814
+ }
815
+ },
816
+ ],
817
+ [
818
+ // A ticket as it stands: waiting, building, or done with what its waiter ended with (d6).
819
+ 'GET',
820
+ /^\/api\/p\/([^/]+)\/play\/queue\/(\d+)$/,
821
+ async (_req, res, m) => {
822
+ const p = await projectOf(m[1]);
823
+ send(res, 200, ticketState(p.path, Number(m[2])));
824
+ },
825
+ ],
826
+ [
827
+ // The operator's Cancel of a ticket (d6): a waiting one goes, a building one is stopped.
828
+ 'DELETE',
829
+ /^\/api\/p\/([^/]+)\/play\/queue\/(\d+)$/,
830
+ async (_req, res, m) => {
831
+ const p = await projectOf(m[1]);
832
+ const r = await cli(p, ['gcf', 'playtest', 'cancel', m[2], '--json']);
792
833
  broadcast({ type: 'board', project: p.name });
793
834
  try {
794
835
  send(res, 200, JSON.parse(r.out));
@@ -29,21 +29,94 @@ const BEAT_STALE_MS = 90_000;
29
29
  // A board that stops leaves its runs going: killing one would lose its integrate step.
30
30
  const active = new Set();
31
31
  const queues = new Map();
32
- // The projects whose folder a click build holds: a run now would only be refused, and a refused
33
- // run stalls the queue and turns the autopilot off. They wait for it instead.
34
- const clickBuilds = new Set();
35
- /** Run a click build with the project's runs held back; they go when it ends. */
36
- export async function whileClickBuilds(p, build) {
37
- clickBuilds.add(p.name);
32
+ /** The project's build tickets in their order, from its files: they outlive a board's restart. */
33
+ export function buildTickets(dir) {
34
+ const runs = path.join(dir, '.gcf-session', 'runs');
35
+ let names;
38
36
  try {
39
- return await build();
37
+ names = readdirSync(runs).filter((n) => /^\.build-\d+\.json$/.test(n));
40
38
  }
41
- finally {
42
- clickBuilds.delete(p.name);
43
- advance(p.name);
44
- setImmediate(() => void pilot(p.name));
39
+ catch {
40
+ return [];
41
+ }
42
+ const tickets = [];
43
+ for (const name of names)
44
+ try {
45
+ const t = JSON.parse(readFileSync(path.join(runs, name), 'utf8'));
46
+ if (Number.isInteger(t.n) && pidAlive(Number(t.pid)))
47
+ tickets.push(t);
48
+ }
49
+ catch {
50
+ // Being written: the next look reads it.
51
+ }
52
+ return tickets.sort((a, b) => a.n - b.n);
53
+ }
54
+ // shortcut: a waiter's pid that Windows gave to another process keeps its ticket alive, and runs
55
+ // held, until that process ends; a heartbeat on the ticket would tell them apart.
56
+ const pidAlive = (pid) => {
57
+ try {
58
+ process.kill(pid, 0);
59
+ return true;
60
+ }
61
+ catch (e) {
62
+ return e.code === 'EPERM';
63
+ }
64
+ };
65
+ // The projects whose folder a build by click holds or waits for: a run now would only be refused,
66
+ // and a refused run stalls the queue and turns the autopilot off. They wait for it instead.
67
+ const clickBuilding = (project) => {
68
+ const dir = paths.get(project);
69
+ const held = dir !== undefined && buildTickets(dir).length > 0;
70
+ // Seen here first (a short ticket between two looks): its end still lets the queue go on.
71
+ if (held && !ticketed.has(project))
72
+ ticketed.set(project, '');
73
+ return held;
74
+ };
75
+ // What the tickets of a project were at the last look (their number, building, after): when the
76
+ // last goes, its queue goes on; any change redraws its board.
77
+ const ticketed = new Map();
78
+ const TICKETS_EVERY_MS = 1000;
79
+ let ticketTimer = null;
80
+ /**
81
+ * Ticket `n` of a project: waiting or building while its waiter lives, done with its outcome
82
+ * (`.build-<n>.out.json`), or gone: a dead waiter left none.
83
+ */
84
+ export function ticketState(dir, n) {
85
+ const t = buildTickets(dir).find((x) => x.n === n);
86
+ if (t)
87
+ return { ticket: n, state: t.building ? 'building' : 'waiting', after: t.after ?? null };
88
+ try {
89
+ const out = JSON.parse(readFileSync(path.join(dir, '.gcf-session', 'runs', `.build-${n}.out.json`), 'utf8'));
90
+ return { ticket: n, state: 'done', ...out };
91
+ }
92
+ catch {
93
+ return { ticket: n, state: 'gone', ok: false, problem: 'its waiter ended without a word' };
45
94
  }
46
95
  }
96
+ /** A ticket's end lets the project's queue and autopilot go on, as a click build's end did. */
97
+ function lookAtTickets() {
98
+ for (const [project, dir] of paths) {
99
+ const tickets = buildTickets(dir);
100
+ const sign = tickets.map((t) => `${t.n}:${t.building === true}:${t.after ?? ''}`).join(',');
101
+ if (tickets.length ? ticketed.get(project) === sign : !ticketed.has(project))
102
+ continue;
103
+ if (tickets.length)
104
+ ticketed.set(project, sign);
105
+ else {
106
+ ticketed.delete(project);
107
+ advance(project);
108
+ setImmediate(() => void pilot(project));
109
+ }
110
+ broadcast({ type: 'board', project });
111
+ }
112
+ }
113
+ /** Watch the project's build tickets from now on (a click opened one, or a board started again). */
114
+ export function watchTickets(p) {
115
+ paths.set(p.name, p.path);
116
+ ticketTimer ??= setInterval(lookAtTickets, TICKETS_EVERY_MS);
117
+ ticketTimer.unref();
118
+ lookAtTickets();
119
+ }
47
120
  // Projects whose queue waits after a failure the next run would repeat (`stalled`).
48
121
  const paused = new Set();
49
122
  // The projects the operator holds (Hold-Plan d20): no queued or autopilot run starts; the
@@ -209,7 +282,8 @@ function queuedOf(v) {
209
282
  /** The state a board before this one kept of project `p`: its queue, pause, reports and trace. */
210
283
  function restore(entry, p) {
211
284
  loaded ??= readSaved();
212
- paths.set(p.name, p.path);
285
+ // Tickets outlive a board's restart: their end lets the restored queue go on.
286
+ watchTickets(p);
213
287
  if (loaded === 'bad') {
214
288
  trace(p.name, 'queue-lost', `${stateFile()} could not be read (kept as queue.json.bad): the board starts with no queue`);
215
289
  // Said once: the next project starts empty with no line of its own.
@@ -326,7 +400,7 @@ function limited(run, result) {
326
400
  function advance(project) {
327
401
  if (adopting.has(project))
328
402
  return;
329
- if (paused.has(project) || projectHolds.has(project) || clickBuilds.has(project))
403
+ if (paused.has(project) || projectHolds.has(project) || clickBuilding(project))
330
404
  return;
331
405
  if (activeRuns(project).some((r) => r.mode === 'main'))
332
406
  return;
@@ -866,7 +940,7 @@ export function startRun(entry, p, ids, mode = 'worktree', fresh = false, harnes
866
940
  busyCheck(p, ids);
867
941
  const { active: going } = runsOf(p.name);
868
942
  // A paused queue holds a new main run too: it would repeat the failure, and jump the queue.
869
- const held = paused.has(p.name) || clickBuilds.has(p.name);
943
+ const held = paused.has(p.name) || clickBuilding(p.name);
870
944
  if (mode === 'main' && (held || going.some((r) => r.mode === 'main'))) {
871
945
  queues.set(p.name, [
872
946
  ...(queues.get(p.name) ?? []),
@@ -1025,7 +1099,7 @@ export const reserveText = (r) => r?.weekly
1025
1099
  /** Whether the project is idle for the autopilot: no run, no queue to go, no pause. */
1026
1100
  const idle = (project) => !paused.has(project) &&
1027
1101
  !projectHolds.has(project) &&
1028
- !clickBuilds.has(project) &&
1102
+ !clickBuilding(project) &&
1029
1103
  !activeRuns(project).length &&
1030
1104
  !queues.get(project)?.some((q) => !q.waiting);
1031
1105
  /** Main's loose work outside gcf/ a main batch would carry; none when the gate cannot say. */
@@ -213,22 +213,30 @@ function playLines(board, item) {
213
213
  'a tech card with propose_item_new that adds them and names them in AGENTS.md.',
214
214
  '',
215
215
  ];
216
- const b = item.build;
217
- const targets = board.play.targets.map((t) => `${t.name} (${t.open})`).join(', ') || 'none';
218
- const shared = b?.shared_with?.length ? ` The same build as ${b.shared_with.join(', ')}.` : '';
219
- const said = b?.building
216
+ // Its builds by build and profile (schema 5): what is ready, what is made now.
217
+ const builds = item.builds ?? [];
218
+ const targets = board.play.targets
219
+ .map((t) => `${t.name} (${t.open}${t.build ? `, plays ${t.build}` : ''})`)
220
+ .join(', ') || 'none';
221
+ const ready = builds.filter((b) => b.ok);
222
+ const shared = ready.find((b) => b.shared_with?.length)?.shared_with ?? [];
223
+ const sharedText = shared.length ? ` The same build as ${shared.join(', ')}.` : '';
224
+ const said = builds.some((b) => b.building)
220
225
  ? 'its build is being made now.'
221
- : b?.ok
222
- ? `its build is ready: commit ${b.commit?.slice(0, 7) ?? 'unknown'}, built ${b.built_at}, ` +
223
- `${b.source === 'click' ? 'by hand, so it may hold later cards' : 'by its run'}.${shared}`
226
+ : ready.length
227
+ ? `its builds are ready: ${ready
228
+ .map((b) => `${b.build} ${b.profile} at commit ${b.commit?.slice(0, 7) ?? 'unknown'}, built ` +
229
+ `${b.built_at}, ${b.source === 'click' ? 'by hand, so it may hold later cards' : 'by its run'}`)
230
+ .join('; ')}.${sharedText}`
224
231
  : 'it has no build yet: its Play button builds it first.';
232
+ const problem = builds.find((b) => b.problem)?.problem;
225
233
  const running = board.play.running?.id === item.id
226
234
  ? [`It plays now on ${board.play.running.target}: ${board.play.running.open}.`]
227
235
  : [];
228
236
  return [
229
237
  '',
230
238
  `To play it: ${said}`,
231
- ...(b?.problem ? [`The last build failed: ${b.problem.split('\n')[0]}`] : []),
239
+ ...(problem ? [`The last build failed: ${problem.split('\n')[0]}`] : []),
232
240
  ...running,
233
241
  `Targets: ${targets}.`,
234
242
  'Never answer that you cannot build it: the card has its Play button, which builds first;',
@@ -1,6 +1,6 @@
1
1
  // The read model of `ai-factory gcf board --json` (Methodology §11): the board refuses a schema
2
2
  // it does not know. Types only, plus the version this board reads.
3
- export const BOARD_SCHEMA = 4;
3
+ export const BOARD_SCHEMA = 5;
4
4
  // Where a project keeps files given to an item or an inbox entry (Board-PRD §5.3, §5.6): only
5
5
  // there may the board hand out a file that is not text. One list: a later kind is one line.
6
6
  const ATTACHED = [