gcf-board 0.9.1 → 0.11.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.
@@ -4,12 +4,14 @@
4
4
  // started from a console shows on the board too (its lock or session mark makes the item
5
5
  // `running`); only its report is not here.
6
6
  // In `run_mode: main` the checkout takes one run at a time: a run asked for meanwhile waits in
7
- // the project's queue and starts when the one before it ends.
7
+ // the project's queue and starts when the one before it ends. The queue, its pause, the reports
8
+ // and the trace live in `<board home>/queue.json` too: a board started again goes on with them.
8
9
  import { spawn } from 'node:child_process';
9
10
  import { randomUUID } from 'node:crypto';
10
- import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
11
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
11
12
  import path from 'node:path';
12
13
  import { fileURLToPath } from 'node:url';
14
+ import { writeAtomicSync } from './atomic.js';
13
15
  import { briefError } from './cli.js';
14
16
  import { alive, broadcast } from './events.js';
15
17
  import { HttpError } from './http-error.js';
@@ -29,13 +31,14 @@ const queues = new Map();
29
31
  const paused = new Set();
30
32
  // The paused projects whose pause the usage limit set: a run that ended paused by it (AD-19).
31
33
  const limitPaused = new Set();
34
+ // When the usage limit that paused a project's queue resets, ISO; none when it was not one.
35
+ const pausedUntil = new Map();
32
36
  // Runs going on for a project the operator removed: their end touches no project state.
33
37
  const forgotten = new WeakSet();
38
+ // The projects whose runs a board started again is taking in: their queue waits until it is done.
39
+ const adopting = new Set();
34
40
  // The runs in flight by their record's id: a project added back must not take one twice.
35
41
  const flights = new Map();
36
- // shortcut: reports and acts live in memory, like the queue: a board restart forgets the ones
37
- // it showed (a run in flight is not lost, its record waits); persist them with the queue if
38
- // restarts become common.
39
42
  const reports = new Map();
40
43
  const acts = new Map();
41
44
  const KEEP_REPORTS = 20;
@@ -45,10 +48,176 @@ function trace(project, act, text) {
45
48
  const list = [...(acts.get(project) ?? []), { at: new Date().toISOString(), act, text }];
46
49
  acts.set(project, list.slice(-KEEP_ACTS));
47
50
  }
51
+ const stateFile = () => path.join(homeDir(), 'queue.json');
52
+ // The folder of each project the board keeps state of: the key `queue.json` checks on a restart.
53
+ const paths = new Map();
54
+ // What a board started again read from `queue.json` and has not given a project yet; null: not
55
+ // read yet, 'bad': there but unreadable.
56
+ let loaded = null;
57
+ /**
58
+ * Write what the board keeps of every project, whole, at once. A project not adopted yet keeps
59
+ * the part it had: the board adopts its projects one by one.
60
+ * shortcut: two boards on one home read and write the same file, and both go on with its queue;
61
+ * two boards on one home is not a setup the board offers (a second start opens the first).
62
+ */
63
+ function save() {
64
+ loaded ??= readSaved();
65
+ const names = new Set([...queues.keys(), ...paused, ...reports.keys(), ...acts.keys()]);
66
+ const projects = loaded !== 'bad' ? { ...loaded } : {};
67
+ for (const name of names) {
68
+ const where = paths.get(name);
69
+ if (!where)
70
+ continue;
71
+ projects[name] = {
72
+ path: where,
73
+ queue: (queues.get(name) ?? []).map(({ entry: _e, p: _p, ...q }) => q),
74
+ paused_by: runsOf(name).paused_by,
75
+ paused_until: pausedUntil.get(name) ?? null,
76
+ reports: reports.get(name) ?? [],
77
+ acts: acts.get(name) ?? [],
78
+ };
79
+ }
80
+ try {
81
+ mkdirSync(homeDir(), { recursive: true });
82
+ // `seq`: the last report id given, so a report closed before a restart keeps its id to itself.
83
+ writeAtomicSync(stateFile(), `${JSON.stringify({ seq: reportSeq, projects }, null, 2)}\n`);
84
+ }
85
+ catch (e) {
86
+ // The board goes on in memory; a restart then starts with the queue last written.
87
+ console.error(`gcf-board: the run queue was not saved: ${e.message}`);
88
+ }
89
+ }
90
+ /** The project's runs changed: keep them, and tell its board. */
91
+ function changed(project) {
92
+ save();
93
+ broadcast({ type: 'board', project });
94
+ }
95
+ /**
96
+ * `queue.json` as a board before this one left it: none is no state; one that cannot be read
97
+ * (locked, not JSON, not a map of projects) is 'bad', and its parts are lost.
98
+ */
99
+ function readSaved() {
100
+ let text = '';
101
+ // A file a scanner holds for a moment is read again, as a write tries again (atomic.ts).
102
+ for (let i = 0;; i++)
103
+ try {
104
+ text = readFileSync(stateFile(), 'utf8');
105
+ break;
106
+ }
107
+ catch (e) {
108
+ const code = e.code ?? '';
109
+ if (code === 'ENOENT')
110
+ return {};
111
+ if (!['EPERM', 'EACCES', 'EBUSY'].includes(code) || i >= 10)
112
+ return setAside();
113
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
114
+ }
115
+ try {
116
+ const v = JSON.parse(text);
117
+ if (typeof v?.projects !== 'object' || v.projects === null || Array.isArray(v.projects))
118
+ return setAside();
119
+ if (Number.isInteger(v.seq))
120
+ reportSeq = Math.max(reportSeq, v.seq);
121
+ return v.projects;
122
+ }
123
+ catch {
124
+ return setAside();
125
+ }
126
+ }
127
+ /** A kept file that cannot be read goes beside it (`queue.json.bad`): the next save must not wipe it. */
128
+ function setAside() {
129
+ try {
130
+ renameSync(stateFile(), `${stateFile()}.bad`);
131
+ }
132
+ catch {
133
+ // Still held: the next save writes over it, the trace has said it was lost.
134
+ }
135
+ return 'bad';
136
+ }
137
+ /** The projects on the board now: the saved parts of any other go (a later one of that name starts empty). */
138
+ export function keepProjects(names) {
139
+ loaded ??= readSaved();
140
+ if (loaded === 'bad')
141
+ return;
142
+ for (const name of Object.keys(loaded))
143
+ if (!names.includes(name))
144
+ delete loaded[name];
145
+ }
146
+ const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
147
+ const WORD = /^[A-Za-z0-9][\w.-]*$/;
148
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
149
+ const list = (v) => (Array.isArray(v) ? v : []);
150
+ const pick = (v) => (typeof v === 'string' && WORD.test(v) ? v : null);
151
+ /**
152
+ * A queued request as `queue.json` holds it, or null: its ids go to the harness's command line,
153
+ * so each must be an item id; its mode one of the two; its pick plain words.
154
+ */
155
+ function queuedOf(v) {
156
+ if (!isObject(v))
157
+ return null;
158
+ const ids = list(v.ids);
159
+ if (!ids.length || !ids.every((id) => typeof id === 'string' && SLUG.test(id)))
160
+ return null;
161
+ if (v.mode !== 'main' && v.mode !== 'worktree')
162
+ return null;
163
+ if (typeof v.harness !== 'string' || !SLUG.test(v.harness))
164
+ return null;
165
+ const agent = isObject(v.agent)
166
+ ? { model: pick(v.agent.model), effort: pick(v.agent.effort) }
167
+ : undefined;
168
+ return {
169
+ ids: ids,
170
+ mode: v.mode,
171
+ harness: v.harness,
172
+ ...(v.fresh === true ? { fresh: true } : {}),
173
+ ...(v.waitLimit === true ? { waitLimit: true } : {}),
174
+ ...(agent ? { agent } : {}),
175
+ };
176
+ }
177
+ /** The state a board before this one kept of project `p`: its queue, pause, reports and trace. */
178
+ function restore(entry, p) {
179
+ loaded ??= readSaved();
180
+ paths.set(p.name, p.path);
181
+ if (loaded === 'bad') {
182
+ trace(p.name, 'queue-lost', `${stateFile()} could not be read (kept as queue.json.bad): the board starts with no queue`);
183
+ // Said once: the next project starts empty with no line of its own.
184
+ loaded = {};
185
+ return;
186
+ }
187
+ const s = loaded[p.name];
188
+ delete loaded[p.name];
189
+ if (!isObject(s))
190
+ return;
191
+ if (s.path !== p.path) {
192
+ trace(p.name, 'queue-lost', `the queue kept for ${String(s.path)} is not this folder's`);
193
+ return;
194
+ }
195
+ const queue = list(s.queue)
196
+ .map(queuedOf)
197
+ .filter((q) => q !== null);
198
+ if (queue.length)
199
+ queues.set(p.name, queue.map((q) => ({ ...q, entry, p })));
200
+ if (s.paused_by === 'limit' || s.paused_by === 'failure')
201
+ paused.add(p.name);
202
+ if (s.paused_by === 'limit')
203
+ limitPaused.add(p.name);
204
+ const until = s.paused_by === 'limit' ? s.paused_until : null;
205
+ if (typeof until === 'string' && !Number.isNaN(Date.parse(until)))
206
+ pausedUntil.set(p.name, until);
207
+ const kept = list(s.reports).filter((r) => isObject(r) && typeof r.id === 'string' && Array.isArray(r.ids));
208
+ if (kept.length)
209
+ reports.set(p.name, kept);
210
+ const did = list(s.acts).filter((a) => isObject(a) && typeof a.act === 'string' && typeof a.text === 'string');
211
+ if (did.length)
212
+ acts.set(p.name, did);
213
+ // Report ids go on after the kept ones, as after a file before `seq`.
214
+ for (const r of kept)
215
+ reportSeq = Math.max(reportSeq, Number(r.id.slice(1)) || 0);
216
+ }
48
217
  /** The operator closed a run report. */
49
218
  export function closeReport(project, id) {
50
219
  reports.set(project, (reports.get(project) ?? []).filter((r) => r.id !== id));
51
- broadcast({ type: 'board', project });
220
+ changed(project);
52
221
  }
53
222
  export const activeRuns = (project) => [...active].filter((r) => r.project === project);
54
223
  /** What runs and what waits, for a project; a paused queue waits for `resumeQueue`. */
@@ -60,7 +229,13 @@ export function runsOf(project) {
60
229
  queued_with: Object.fromEntries((queues.get(project) ?? []).flatMap((q) => q.agent && (q.agent.model || q.agent.effort) ? q.ids.map((id) => [id, q.agent]) : [])),
61
230
  paused: paused.has(project),
62
231
  // Why it waits: a run the usage limit ended paused, or a failure; the operator resumes it.
63
- paused_by: paused.has(project) ? (limitPaused.has(project) ? 'limit' : 'failure') : null,
232
+ paused_by: (paused.has(project)
233
+ ? limitPaused.has(project)
234
+ ? 'limit'
235
+ : 'failure'
236
+ : null),
237
+ // When the usage limit that paused it resets, ISO: none for a pause of another kind.
238
+ paused_until: paused.has(project) ? (pausedUntil.get(project) ?? null) : null,
64
239
  reports: reports.get(project) ?? [],
65
240
  acts: acts.get(project) ?? [],
66
241
  };
@@ -72,8 +247,11 @@ export function forgetProject(project) {
72
247
  queues.delete(project);
73
248
  paused.delete(project);
74
249
  limitPaused.delete(project);
250
+ pausedUntil.delete(project);
75
251
  reports.delete(project);
76
252
  acts.delete(project);
253
+ paths.delete(project);
254
+ save();
77
255
  }
78
256
  /**
79
257
  * A run some of whose items the usage limit ended paused: the harness waits for a reset it
@@ -85,11 +263,16 @@ function limited(run, result) {
85
263
  if (!hit.length)
86
264
  return '';
87
265
  const project = run.p.name;
266
+ const resets = hit.find((i) => i.limit_resets)?.limit_resets ?? '';
88
267
  if (run.mode === 'main') {
89
268
  paused.add(project);
90
269
  limitPaused.add(project);
270
+ // An ISO reset (harness 0.12) shows as a time; the words of an older one only in the report.
271
+ if (resets && !Number.isNaN(Date.parse(resets)))
272
+ pausedUntil.set(project, resets);
273
+ else
274
+ pausedUntil.delete(project);
91
275
  }
92
- const resets = hit.find((i) => i.limit_resets)?.limit_resets ?? '';
93
276
  // A harness before 0.12 does not wait for the reset by itself.
94
277
  const old = result?.limit_wait
95
278
  ? ''
@@ -101,6 +284,8 @@ function limited(run, result) {
101
284
  }
102
285
  /** Start the next queued batch when the checkout is free: after a run, or on the operator's resume. */
103
286
  function advance(project) {
287
+ if (adopting.has(project))
288
+ return;
104
289
  if (paused.has(project) || activeRuns(project).some((r) => r.mode === 'main'))
105
290
  return;
106
291
  const next = queues.get(project)?.shift();
@@ -116,8 +301,9 @@ export function resumeQueue(project) {
116
301
  trace(project, 'queue-resumed', 'the operator resumed the queue');
117
302
  paused.delete(project);
118
303
  limitPaused.delete(project);
304
+ pausedUntil.delete(project);
119
305
  advance(project);
120
- broadcast({ type: 'board', project });
306
+ changed(project);
121
307
  }
122
308
  /** Take an item out of the queue before its run starts. */
123
309
  export function unqueue(project, id) {
@@ -125,7 +311,7 @@ export function unqueue(project, id) {
125
311
  .map((q) => ({ ...q, ids: q.ids.filter((x) => x !== id) }))
126
312
  .filter((q) => q.ids.length);
127
313
  queues.set(project, queue);
128
- broadcast({ type: 'board', project });
314
+ changed(project);
129
315
  }
130
316
  /**
131
317
  * Whether a main run ended in a way the next one would repeat: no report at all (the harness
@@ -222,9 +408,9 @@ function spawnRun(q, mode) {
222
408
  return run;
223
409
  }
224
410
  /**
225
- * A run's end: its report from the end file its relay wrote, or what went wrong. `live`: a
226
- * board saw it end, so a usage limit or a stalled queue acts on it; a run that ended while no
227
- * board was up only reports (a reset counted from now could be a day late).
411
+ * A run's end: its report from the end file its relay wrote, or what went wrong. A usage limit or
412
+ * a stalled queue pauses the queue `queue.json` kept even when the run ended while no board was
413
+ * up (`live` false): the report says so.
228
414
  */
229
415
  function land(q, run, rid, live, message = '') {
230
416
  // A spawn that fails fires both error and exit: one end only.
@@ -251,7 +437,7 @@ function land(q, run, rid, live, message = '') {
251
437
  active.delete(run);
252
438
  if (q.mode === 'main')
253
439
  advance(q.p.name);
254
- broadcast({ type: 'board', project: run.project });
440
+ changed(run.project);
255
441
  return;
256
442
  }
257
443
  // Held by a scanner for a moment: report now; the end stays for a board after this one,
@@ -274,22 +460,25 @@ function land(q, run, rid, live, message = '') {
274
460
  message = "the run's relay ended without a result";
275
461
  // A run of a project removed meanwhile only reports: it pauses nothing.
276
462
  const kept = !forgotten.has(run);
277
- const acting = kept && live;
278
- const stop = acting && mode === 'main' && queues.get(p.name)?.length && stalled(ok, result);
463
+ const stop = kept && mode === 'main' && queues.get(p.name)?.length && stalled(ok, result);
279
464
  if (stop) {
280
465
  paused.add(p.name);
281
466
  limitPaused.delete(p.name);
467
+ pausedUntil.delete(p.name);
282
468
  }
283
469
  const note = !kept
284
470
  ? ''
285
- : !live
286
- ? 'it ended while the board was stopped: nothing was paused'
287
- : limited(q, result) ||
288
- (stop ? 'the queue is paused: fix the cause, then resume it on the board' : '');
471
+ : [
472
+ live ? '' : 'it ended while the board was stopped',
473
+ limited(q, result) ||
474
+ (stop ? 'the queue is paused: fix the cause, then resume it on the board' : ''),
475
+ ]
476
+ .filter(Boolean)
477
+ .join('; ');
289
478
  if (stop)
290
479
  trace(p.name, 'queue-paused', `after ${ids.join(', ')}: ${note}`);
291
480
  for (const i of result?.items ?? [])
292
- if (acting && i.handoffs)
481
+ if (kept && i.handoffs)
293
482
  trace(p.name, 'handoff', `${i.id}: ${i.handoffs} context handoff(s) to a fresh session`);
294
483
  // A harness before 0.11 refuses the chat flags every board run passes, one before 0.12 the
295
484
  // limit wait of a queued start: say what to update.
@@ -316,7 +505,7 @@ function land(q, run, rid, live, message = '') {
316
505
  // The checkout is free now, for whatever queue the name has: a project added back meanwhile.
317
506
  if (mode === 'main')
318
507
  advance(p.name);
319
- broadcast({ type: 'board', project: p.name });
508
+ changed(p.name);
320
509
  }
321
510
  /**
322
511
  * Whether the relay of a run found on adoption still goes: its pid lives and it touched its
@@ -332,12 +521,10 @@ function going(rid, pid) {
332
521
  }
333
522
  }
334
523
  /**
335
- * The runs a board before this one started for the project: one going shows as active until it
336
- * ends, one that ended meanwhile as its report, one whose relay died with no end as a failure.
337
- * shortcut: the records of a project removed while no board was up stay in the board home until
338
- * it is added back; sweep the ones of unregistered projects at the start if they pile up.
524
+ * Drop the run records of projects no longer on the board (removed while no board was up, so none
525
+ * took their ends), once their runs are over: nothing would ever read them.
339
526
  */
340
- export function adoptRuns(entry, p) {
527
+ export function sweepRuns(projects) {
341
528
  let names;
342
529
  try {
343
530
  names = readdirSync(flightsDir());
@@ -351,38 +538,89 @@ export function adoptRuns(entry, p) {
351
538
  const rid = name.slice(0, -'.json'.length);
352
539
  if (flights.has(rid))
353
540
  continue;
354
- let f;
355
541
  try {
356
- f = JSON.parse(readFileSync(recordOf(rid), 'utf8'));
542
+ const f = JSON.parse(readFileSync(recordOf(rid), 'utf8'));
543
+ if (projects.some((p) => p.name === f.project && p.path === f.path) || going(rid, f.pid))
544
+ continue;
545
+ rmSync(endOf(rid), { force: true });
546
+ rmSync(recordOf(rid), { force: true });
357
547
  }
358
548
  catch {
359
- continue;
549
+ // Unreadable or gone meanwhile: the next start looks again.
360
550
  }
361
- if (f.project !== p.name || f.path !== p.path)
362
- continue;
363
- const agent = { model: f.model ?? null, effort: f.effort ?? null };
364
- const run = { project: p.name, ids: f.ids, started: f.started, mode: f.mode, ...agent };
365
- const q = { entry, p, ids: f.ids, mode: f.mode, harness: f.harness, agent };
366
- active.add(run);
367
- flights.set(rid, run);
368
- // shortcut: off Windows a dead relay leaves its harness going (no job object), reported
369
- // failed here; record the harness pid if that bites. A board started within a beat of the
370
- // machine waking takes a run going since before the sleep for a dead one (its beat is late):
371
- // a main queue then starts in a busy checkout, and the end that relay writes stays behind.
372
- // Once adopted, only the pid's death ends it: a sleep stops the beats too.
373
- if (going(rid, f.pid)) {
374
- const poll = setInterval(() => {
375
- if (alive(f.pid))
376
- return;
377
- clearInterval(poll);
378
- land(q, run, rid, true);
379
- }, 2000);
380
- poll.unref();
551
+ }
552
+ }
553
+ /**
554
+ * What a board before this one left for the project: first its queue, pause, reports and trace
555
+ * (`queue.json`), then its runs: one going shows as active until it ends, one that ended
556
+ * meanwhile as its report, one whose relay died with no end as a failure, which pauses the
557
+ * queue. Only then a queue not paused and with no main run going goes on.
558
+ */
559
+ export function adoptRuns(entry, p) {
560
+ try {
561
+ restore(entry, p);
562
+ }
563
+ catch (e) {
564
+ // The rest of the board's start must go on: this project only starts with no queue.
565
+ trace(p.name, 'queue-lost', `the kept queue could not be read: ${e.message}`);
566
+ }
567
+ // Its queue goes on only once every run of it is in: one that ended may pause it.
568
+ adopting.add(p.name);
569
+ try {
570
+ let names;
571
+ try {
572
+ names = readdirSync(flightsDir());
381
573
  }
382
- else
383
- land(q, run, rid, false);
574
+ catch {
575
+ names = [];
576
+ }
577
+ for (const name of names) {
578
+ if (!name.endsWith('.json') || name.endsWith('.end.json'))
579
+ continue;
580
+ const rid = name.slice(0, -'.json'.length);
581
+ if (flights.has(rid))
582
+ continue;
583
+ let f;
584
+ try {
585
+ f = JSON.parse(readFileSync(recordOf(rid), 'utf8'));
586
+ }
587
+ catch {
588
+ continue;
589
+ }
590
+ if (f.project !== p.name || f.path !== p.path)
591
+ continue;
592
+ const agent = { model: f.model ?? null, effort: f.effort ?? null };
593
+ const run = { project: p.name, ids: f.ids, started: f.started, mode: f.mode, ...agent };
594
+ const q = { entry, p, ids: f.ids, mode: f.mode, harness: f.harness, agent };
595
+ active.add(run);
596
+ flights.set(rid, run);
597
+ // shortcut: off Windows a dead relay leaves its harness going (no job object), reported
598
+ // failed here; record the harness pid if that bites. A board started within a beat of the
599
+ // machine waking takes a run going since before the sleep for a dead one (its beat is late):
600
+ // a main queue then starts in a busy checkout, and the end that relay writes stays behind.
601
+ // Once adopted, only the pid's death ends it: a sleep stops the beats too.
602
+ if (going(rid, f.pid)) {
603
+ const poll = setInterval(() => {
604
+ if (alive(f.pid))
605
+ return;
606
+ clearInterval(poll);
607
+ land(q, run, rid, true);
608
+ }, 2000);
609
+ poll.unref();
610
+ }
611
+ else
612
+ land(q, run, rid, false);
613
+ }
614
+ }
615
+ finally {
616
+ adopting.delete(p.name);
617
+ }
618
+ const waiting = queues.get(p.name) ?? [];
619
+ if (waiting.length && !paused.has(p.name) && !activeRuns(p.name).some((r) => r.mode === 'main')) {
620
+ trace(p.name, 'queue-restored', 'the board started again: the queue goes on');
621
+ advance(p.name);
384
622
  }
385
- broadcast({ type: 'board', project: p.name });
623
+ changed(p.name);
386
624
  }
387
625
  /**
388
626
  * Start a batch in the project's run mode, or queue it behind the main run going on. Its end
@@ -393,6 +631,7 @@ export function adoptRuns(entry, p) {
393
631
  */
394
632
  export function startRun(entry, p, ids, mode = 'worktree', fresh = false, harness = 'gcf-harness', agent) {
395
633
  // A second click on the same card: the harness would refuse it on its lock, noisily.
634
+ paths.set(p.name, p.path);
396
635
  const { active: going, queued } = runsOf(p.name);
397
636
  const busy = ids.filter((id) => queued.includes(id) || going.some((r) => r.ids.includes(id)));
398
637
  if (busy.length)
@@ -403,7 +642,7 @@ export function startRun(entry, p, ids, mode = 'worktree', fresh = false, harnes
403
642
  ...(queues.get(p.name) ?? []),
404
643
  { entry, p, ids, mode, fresh, harness, agent },
405
644
  ]);
406
- broadcast({ type: 'board', project: p.name });
645
+ changed(p.name);
407
646
  return { queued: ids };
408
647
  }
409
648
  return { started: spawnRun({ entry, p, ids, mode, fresh, harness, agent }, mode) };
@@ -131,6 +131,8 @@ export function talkSpec(p, board, mcp) {
131
131
  ...(board.context?.window ? { window: board.context.window } : {}),
132
132
  skill: chat.skill,
133
133
  mainLock: path.join(p.path, '.gcf-session', 'runs', '.main-run.lock'),
134
+ // The project's model and effort: a thread that picked none runs on them.
135
+ pick: Object.fromEntries(['model', 'effort'].flatMap((k) => board.agent?.[k] ? [[k, board.agent[k]]] : [])),
134
136
  };
135
137
  }
136
138
  /** A command's output in the project, or empty. */
@@ -469,6 +471,7 @@ export function cardIn(events) {
469
471
  tool: e.tool,
470
472
  ...(e.reason ? { reason: e.reason } : {}),
471
473
  ...(e.always ? { always: e.always } : {}),
474
+ ...(e.always && e.always_wide ? { always_wide: true } : {}),
472
475
  });
473
476
  else if (e.type === 'question')
474
477
  open.set(e.request_id, {
@@ -0,0 +1,75 @@
1
+ // The operator's themes: one JSON file each in `<board home>/themes/<id>.json`, made by the
2
+ // designer or by hand. A theme sets design tokens (`--gcf-<name>` of web/tokens.css) over the
3
+ // built-in dark; the page checks the names, it owns the tokens. Read anew on each request.
4
+ import { readdir, readFile, stat } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { homeDir } from './registry.js';
7
+ export const themesDir = () => path.join(homeDir(), 'themes');
8
+ const ID_RE = /^[a-z0-9-]{1,40}$/;
9
+ const FILE_MAX = 64 * 1024;
10
+ const VALUE_MAX = 200;
11
+ // The page sets each value through the CSSOM, which cannot be broken out of; a function outside
12
+ // the colour and arithmetic ones (`url(`, `image-set(`, `src(`) could fetch from the network.
13
+ const BAD_VALUE = /[;{}<>\\]/;
14
+ const FUNCTIONS = new Set('rgb rgba hsl hsla hwb lab lch oklab oklch color color-mix light-dark var calc min max clamp'.split(' '));
15
+ const badFunction = (v) => [...v.matchAll(/([a-z-]*)\(/gi)].find((m) => m[1] && !FUNCTIONS.has(m[1].toLowerCase()))?.[1];
16
+ const BOM = new RegExp(`^${String.fromCharCode(0xfeff)}`);
17
+ /** A theme file's problem, or null when it is good. */
18
+ export function themeProblem(id, data) {
19
+ if (id === 'dark')
20
+ return 'the name dark is the built-in theme: rename the file';
21
+ if (!ID_RE.test(id))
22
+ return 'a file name takes a-z, 0-9 and -, up to 40';
23
+ if (typeof data !== 'object' || data === null)
24
+ return 'not a JSON object';
25
+ const t = data;
26
+ if (t.gcf_theme !== 1)
27
+ return 'gcf_theme must be 1';
28
+ if (typeof t.name !== 'string' || !t.name.trim())
29
+ return 'name is required';
30
+ if (t.scheme !== 'light' && t.scheme !== 'dark')
31
+ return 'scheme must be light or dark';
32
+ if (typeof t.tokens !== 'object' || t.tokens === null || Array.isArray(t.tokens))
33
+ return 'tokens must be an object';
34
+ for (const [k, v] of Object.entries(t.tokens)) {
35
+ if (!/^[a-z0-9-]+$/.test(k))
36
+ return `token ${k}: a name without --gcf-, a-z, 0-9 and -`;
37
+ if (typeof v !== 'string' || !v.trim() || v.length > VALUE_MAX || BAD_VALUE.test(v))
38
+ return `token ${k}: a CSS value up to ${VALUE_MAX} characters, no ; { } < > \\`;
39
+ const fn = badFunction(v);
40
+ if (fn)
41
+ return `token ${k}: ${fn}( is not a colour function (oklch, rgb, color-mix, var…)`;
42
+ }
43
+ return null;
44
+ }
45
+ /** Every `*.json` of the themes folder: a good theme, or its id and what is wrong with it. */
46
+ export async function readThemes(dir = themesDir()) {
47
+ let names;
48
+ try {
49
+ names = (await readdir(dir)).filter((n) => n.endsWith('.json')).sort();
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ const themes = [];
55
+ for (const n of names) {
56
+ const id = n.slice(0, -'.json'.length);
57
+ const file = path.join(dir, n);
58
+ try {
59
+ if ((await stat(file)).size > FILE_MAX)
60
+ throw new Error(`larger than ${FILE_MAX / 1024} KB`);
61
+ // A file saved by a Windows editor may start with a byte order mark.
62
+ const text = (await readFile(file, 'utf8')).replace(BOM, '');
63
+ const data = JSON.parse(text);
64
+ const problem = themeProblem(id, data);
65
+ if (problem)
66
+ themes.push({ id, error: problem });
67
+ else
68
+ themes.push({ id, name: data.name, scheme: data.scheme, tokens: data.tokens });
69
+ }
70
+ catch (e) {
71
+ themes.push({ id, error: e.message });
72
+ }
73
+ }
74
+ return themes;
75
+ }
@@ -1,3 +1,11 @@
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
3
  export const BOARD_SCHEMA = 3;
4
+ // Where a project keeps files given to an item or an inbox entry (Board-PRD §5.3, §5.6): only
5
+ // there may the board hand out a file that is not text. One list: a later kind is one line.
6
+ const ATTACHED = [
7
+ /^gcf\/inbox\/in-[0-9a-f]{8}\/attachments\/./,
8
+ /^gcf\/work\/[a-z0-9]+(-[a-z0-9]+)*\/attachments\/./,
9
+ ];
10
+ /** Whether project path `rel` lies where attachments are: the board serves it as one. */
11
+ export const attachedShape = (rel) => ATTACHED.some((r) => r.test(rel));