gcf-board 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,7 @@ A local web board for game projects on [GCF](../gcf-aif-ext): the items by statu
6
6
 
7
7
  - Node.js ≥ 22.18
8
8
  - [`ai-factory`](https://www.npmjs.com/package/ai-factory) installed globally, and in each project [`gcf-aif-ext`](../gcf-aif-ext) ≥ 0.10 (`gcf board --json` with `schema: 3`: the columns, the moves, the item's fields, the blocks and the Help terms come from it as data)
9
- - for runs: [`gcf-harness-aif-ext`](../gcf-harness-aif-ext) ≥ 0.8 and Claude Code (`claude -p`)
9
+ - for runs: [`gcf-harness-aif-ext`](../gcf-harness-aif-ext) ≥ 0.11 (every board run opens its chat: `--chat`, `--chat-timeout`, `gcf-harness chat`) and Claude Code (`claude -p`)
10
10
  - gcf-board 0.2 needs `gcf-aif-ext` ≥ 0.7 (priority, questions, session marks, `run_mode`)
11
11
 
12
12
  ## Run
@@ -44,7 +44,7 @@ The board knows no domain by name: the project's board read gives its columns, m
44
44
  - `run_mode: worktree`: one worktree and one agent session per item, all at once, then the integrator;
45
45
  - `run_mode: main`: one item at a time in the project folder. A run asked for meanwhile waits in the board's **queue**; **remove from queue** takes it out.
46
46
 
47
- A run asks first: it spends the subscription. **Stop** on a running item ends its session; the item stays ready and its work is kept. A queued main run that the next one would repeat (the harness did not start, or another run works the checkout) pauses the queue: the header shows **queue paused — resume**; fix the cause, then resume. A card marked **interrupted** had a run that stopped (a timeout, a stop, a crash, the usage limit): **resume** continues its agent session with all its context, **start fresh** drops it. After the usage limit the card reads **paused: limit** and the board resumes it by itself at the reset time; the header shows **resumes HH:MM** with **cancel**, and a queue the limit paused resumes only by that clock until the operator cancels it; a pause after a failure keeps its **resume** button. When a run ends, a report card lists each item's result and stays until closed, across page reloads. **What the board did by itself** lists its automatic acts with their times: a usage limit, a context handoff, the queue paused or started, a resume run or cancelled. A run confirmation names what each interrupted item picks up. The queue, the reports and that list live in the board's memory: a board restart forgets them.
47
+ A run asks first: it spends the subscription. **Stop** on a running item ends its session; the item stays ready and its work is kept. A queued main run that the next one would repeat (the harness did not start, or another run works the checkout) pauses the queue: the header shows **queue paused — resume**; fix the cause, then resume. A card marked **interrupted** had a run that stopped (a timeout, a stop, a crash, the usage limit): **resume** continues its agent session with all its context, **start fresh** drops it. After the usage limit the card reads **paused: limit** and the board resumes it by itself at the reset time; the header shows **resumes HH:MM** with **cancel**, and a queue the limit paused resumes only by that clock until the operator cancels it; a pause after a failure keeps its **resume** button. When a run ends, a report card lists each item's result and stays until closed, across page reloads. **What the board did by itself** lists its automatic acts with their times: a usage limit, a context handoff, the queue paused or started, a resume run or cancelled. A run confirmation names what each interrupted item picks up. The header shows the usage limit as the last run read it, from the newest `.gcf-session/runs/quota.json` of the board's projects: `quota 19% left · resets 03:00`, the window with the least left, every window in its tooltip; `quota ?` before any reading, or once every window has reset since. The queue, the reports and that list live in the board's memory: a board restart forgets them. A run itself outlives the board: closing it or Ctrl+C in its console leaves the run going, and the board started again shows it running, then its report (a run in flight keeps its record in `~/.gcf/runs/`).
48
48
  - **Who runs it** (core 0.7.13): a running card tells a console run and **your session** (a `gcf claim` mark) from the board's own run; a session offers **release mark** instead of **stop**. A ready card whose dependencies are not built yet shows **waits for <dep>**; the drawer shows when an item began to wait (`since_at`).
49
49
  - **Run next N independent**: the framework's gate picks the ready items that can run together now, by priority, and the board runs them after asking.
50
50
  - **Priority**: drop a ready card on another to put it before; the column's ranks are committed (`gcf prioritize`).
@@ -52,6 +52,7 @@ The board knows no domain by name: the project's board read gives its columns, m
52
52
  - **New item**: `gcf item new … --commit`, its form from the core: a bug asks its severity, a release its version and channel. The item's `model` and `effort` go to its run.
53
53
  - **Help** (**?**): the domain's terms, columns, moves and field values with what each means, and the words of runs, under one filter.
54
54
  - **Settings**: the keys of `gcf/config.yml` and the agents' language (`language.ui`, `language.artifacts` of `.ai-factory/config.yaml`), each a `gcf config set` commit.
55
+ - **Chat** (data only, the page waits for its design; harness 0.11.1, core 0.11.1): every run the board starts keeps its agent sessions open; the project's `chat:` settings (Settings tab: `chat.ask`, `chat.answer_timeout_min`) say what the agent asks and how long a question waits. `GET /api/p/<project>/chat/<id>` follows the item's chat from its start, in raw chunks of JSON lines (the page splits them): the talk, the questions, the run's milestones, its sessions and context share. `POST` there sends `{type: 'say', text, images?}`, `{type: 'interrupt'}` or `{type: 'answer', request_id, answers}` through `gcf-harness chat`: a message with no live session to read it gets 409, bad input 400. Until the chat screen ships, a board run waits for no answer (`--chat-timeout 0`). `GET /api/p/<project>/chat/<id>/att/<file>` serves a chat picture; the item move **attach** (`gcf item attach`) gives a file to the item.
55
56
  - **Inbox**: add, erase, or turn an entry into an item. Open questions are listed there too.
56
57
  - **Lessons** (core 0.7.10, harness 0.9.2): what got in an agent's way, asked at the end of each session, lands in the inbox with its kind (`tool`, `rules`, `framework`, `template`, `other`) and its item. The inbox filters them; a card shows `N lessons`, and the drawer lists the item's lessons with the inbox's buttons. A run's report line ends with `, N lessons`, and with `— code written outside aif-implement` when a session skipped that skill.
57
58
  - **Playtest**: `gcf playtest session` with the checklist grouped by subsystem; keep, tune or kill each item from the list. **Build** runs `dod.build`. A note goes to the inbox as `--source playtest`.
@@ -4,29 +4,31 @@
4
4
  // move, a run. Every write is a command of the framework.
5
5
  import { randomBytes } from 'node:crypto';
6
6
  import { createServer } from 'node:http';
7
- import { existsSync, statSync } from 'node:fs';
8
- import { readFile } from 'node:fs/promises';
7
+ import { existsSync, statSync, writeFileSync } from 'node:fs';
8
+ import { lstat, mkdtemp, readFile, rm } from 'node:fs/promises';
9
+ import os from 'node:os';
9
10
  import path from 'node:path';
10
11
  import { BOARD_SCHEMA } from '../shared/board.js';
11
12
  import { admit, cookieName, hostAllowed, tokenInUrl } from './auth.js';
12
13
  import { briefError, runCli } from './cli.js';
13
14
  import { broadcast, planRev, subscribe, watchProject } from './events.js';
15
+ import { CHAT_BODY_MAX, chatInput, IMAGE_EXT } from './chat.js';
14
16
  import { followLog, readShown, shownShape } from './files.js';
15
17
  import { HttpError } from './http-error.js';
16
18
  import { isCenterMove, moveArgs, runIds } from './moves.js';
17
19
  import { addProject, listProjects, projectOf, removeProject } from './registry.js';
18
- import { cancelResume, closeReport, forgetProject, resumeQueue, runsOf, startRun, unqueue, } from './runs.js';
20
+ import { adoptRuns, cancelResume, closeReport, forgetProject, resumeQueue, runsOf, startRun, unqueue, } from './runs.js';
19
21
  const send = (res, status, body) => {
20
22
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
21
23
  res.end(JSON.stringify(body));
22
24
  };
23
- async function bodyOf(req) {
25
+ async function bodyOf(req, limit = 1_000_000) {
24
26
  // Bytes first, text once: a letter cut between two chunks stays whole.
25
27
  const chunks = [];
26
28
  let size = 0;
27
29
  for await (const chunk of req) {
28
30
  size += chunk.length;
29
- if (size > 1_000_000)
31
+ if (size > limit)
30
32
  throw new HttpError(413, 'request too large');
31
33
  chunks.push(chunk);
32
34
  }
@@ -89,6 +91,20 @@ async function sendPage(res, web, pathname) {
89
91
  res.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream' });
90
92
  res.end(await readFile(file));
91
93
  }
94
+ /**
95
+ * The usage limit is one for the account: the newest `quota.json` any project's harness wrote
96
+ * (Board-PRD decision 17), or null. A missing or broken file is no reading.
97
+ */
98
+ async function lastQuota() {
99
+ const read = (p) => readFile(path.join(p.path, '.gcf-session', 'runs', 'quota.json'), 'utf8')
100
+ .then((t) => JSON.parse(t))
101
+ .catch(() => null);
102
+ const seen = (await Promise.all((await listProjects()).map(read))).filter((q) => typeof q?.at === 'string' &&
103
+ !Number.isNaN(Date.parse(q.at)) &&
104
+ typeof q.info === 'object' &&
105
+ q.info !== null);
106
+ return seen.sort((a, b) => Date.parse(b.at) - Date.parse(a.at))[0] ?? null;
107
+ }
92
108
  export function createApp(o) {
93
109
  const watchers = new Map();
94
110
  let closed = false;
@@ -98,8 +114,11 @@ export function createApp(o) {
98
114
  if (closed)
99
115
  return;
100
116
  for (const p of projects)
101
- if (!watchers.has(p.name))
117
+ if (!watchers.has(p.name)) {
102
118
  watchers.set(p.name, watchProject(p));
119
+ // The runs a board before this one started go on: show them, and their ends.
120
+ adoptRuns(o.entry, p);
121
+ }
103
122
  };
104
123
  const cli = (p, args, timeout) => runCli(o.entry, p.path, args, timeout);
105
124
  // The last domain each project's board read gave: an item move is built from its form.
@@ -165,7 +184,12 @@ export function createApp(o) {
165
184
  const p = await projectOf(m[1]);
166
185
  // The board's own runs ride along: what it started and what waits in its queue; and the
167
186
  // count of plan writes, which tells the page an open plan's text changed.
168
- const own = { runs: runsOf(p.name), plans_rev: planRev(p.name), board_version: o.version };
187
+ const own = {
188
+ runs: runsOf(p.name),
189
+ plans_rev: planRev(p.name),
190
+ board_version: o.version,
191
+ quota: await lastQuota(),
192
+ };
169
193
  const board = await boardOf(p);
170
194
  // A running item's last log write tells a working session from a stuck one; a run's
171
195
  // lock is this board's run or a console's.
@@ -199,6 +223,74 @@ export function createApp(o) {
199
223
  followLog((await projectOf(m[1])).path, m[2], res);
200
224
  },
201
225
  ],
226
+ [
227
+ // An item's chat as it grows: one event a line (docs/Chat-Plan.md).
228
+ 'GET',
229
+ /^\/api\/p\/([^/]+)\/chat\/([a-z0-9][a-z0-9-]*)$/,
230
+ async (_req, res, m) => {
231
+ followLog((await projectOf(m[1])).path, m[2], res, 'chat.jsonl');
232
+ },
233
+ ],
234
+ [
235
+ // A picture of an item's chat (`<id>.att/`, where `gcf-harness chat` put it); never through
236
+ // a link. "Attach to item" gives it to the item with the domain's `attach` move.
237
+ 'GET',
238
+ /^\/api\/p\/([^/]+)\/chat\/([a-z0-9][a-z0-9-]*)\/att\/([0-9a-f]{8}\.(png|jpe?g|gif|webp))$/,
239
+ async (_req, res, m) => {
240
+ const p = await projectOf(m[1]);
241
+ const session = path.join(p.path, '.gcf-session');
242
+ const att = path.join(session, 'runs', `${m[2]}.att`);
243
+ const file = path.join(att, m[3]);
244
+ for (const f of [session, path.dirname(att), att, file]) {
245
+ const st = await lstat(f).catch(() => null);
246
+ if (!st || st.isSymbolicLink())
247
+ throw new HttpError(404, `no picture ${m[3]}`);
248
+ }
249
+ const type = m[4] === 'jpg' ? 'jpeg' : m[4];
250
+ res.writeHead(200, { 'content-type': `image/${type}`, 'cache-control': 'private' });
251
+ res.end(await readFile(file));
252
+ },
253
+ ],
254
+ [
255
+ // The operator writes into an item's chat: the run's session reads it on.
256
+ 'POST',
257
+ /^\/api\/p\/([^/]+)\/chat\/([a-z0-9][a-z0-9-]*)$/,
258
+ // The harness's own command writes it (`<harness> chat`): it checks the input, the links
259
+ // and that a live session takes it, so a message nobody would read is refused (409).
260
+ async (req, res, m) => {
261
+ const p = await projectOf(m[1]);
262
+ const line = chatInput(await bodyOf(req, CHAT_BODY_MAX));
263
+ const chat = [await harnessOf(p), 'chat', m[2]];
264
+ const tmp = await mkdtemp(path.join(os.tmpdir(), 'gcf-board-chat-'));
265
+ try {
266
+ let args = [...chat, 'interrupt'];
267
+ let input;
268
+ if (line.type === 'say') {
269
+ const images = (line.images ?? []).map((im, i) => {
270
+ const file = path.join(tmp, `${i}${IMAGE_EXT[im.media_type]}`);
271
+ writeFileSync(file, Buffer.from(im.data, 'base64'));
272
+ return ['--image', file];
273
+ });
274
+ args = [...chat, 'say', '--text-file', '-', ...images.flat()];
275
+ input = line.text;
276
+ }
277
+ else if (line.type === 'answer') {
278
+ args = [...chat, 'answer', line.request_id, '--answers-file', '-'];
279
+ input = JSON.stringify(line.answers);
280
+ }
281
+ const r = await runCli(o.entry, p.path, args, undefined, input);
282
+ if (r.ok)
283
+ return send(res, 202, { ok: true });
284
+ const why = briefError(r.err || r.out).replace(/^[\w-]+ chat: /, '');
285
+ if (/unknown command 'chat'/.test(why))
286
+ throw new HttpError(400, 'the chat needs gcf-harness-aif-ext 0.11.0 or later');
287
+ throw new HttpError(r.code === 3 ? 409 : r.code === 1 ? 400 : 500, why);
288
+ }
289
+ finally {
290
+ await rm(tmp, { recursive: true, force: true });
291
+ }
292
+ },
293
+ ],
202
294
  [
203
295
  'GET',
204
296
  /^\/api\/p\/([^/]+)\/playtest$/,
@@ -256,7 +348,8 @@ export function createApp(o) {
256
348
  if (!domain.harness)
257
349
  throw new HttpError(400, 'this project has no harness: its items run from a console');
258
350
  const ids = runIds(body);
259
- send(res, 202, startRun(o.entry, p, ids, mode, body.fresh === true, domain.harness));
351
+ const fresh = body.fresh === true;
352
+ send(res, 202, startRun(o.entry, p, ids, mode, fresh, domain.harness));
260
353
  },
261
354
  ],
262
355
  [
@@ -0,0 +1,54 @@
1
+ import { HttpError } from './http-error.js';
2
+ /** A chat message may carry images: a body up to 10 MB. */
3
+ export const CHAT_BODY_MAX = 10_000_000;
4
+ /** The file a picture of each type is handed to the harness as. */
5
+ export const IMAGE_EXT = {
6
+ 'image/png': '.png',
7
+ 'image/jpeg': '.jpg',
8
+ 'image/gif': '.gif',
9
+ 'image/webp': '.webp',
10
+ };
11
+ const IMAGE_TYPES = Object.keys(IMAGE_EXT);
12
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
13
+ const TEXT_MAX = 64_000;
14
+ // About 5 MB of image, the most one image may be.
15
+ const IMAGE_MAX = 6_990_000;
16
+ const bad = (why) => new HttpError(400, `chat: ${why}`);
17
+ function images(v) {
18
+ if (v === undefined)
19
+ return [];
20
+ if (!Array.isArray(v) || v.length > 10)
21
+ throw bad('images is a list of up to 10');
22
+ return v.map((i) => {
23
+ const { media_type: type, data } = (i ?? {});
24
+ if (!IMAGE_TYPES.includes(type))
25
+ throw bad(`an image is ${IMAGE_TYPES.join(', ')}`);
26
+ if (typeof data !== 'string' || data.length > IMAGE_MAX || !BASE64.test(data))
27
+ throw bad('an image is base64 data, up to 5 MB');
28
+ return { media_type: type, data };
29
+ });
30
+ }
31
+ /** The line a request writes into the chat input: a message, a stop of the step, an answer. */
32
+ export function chatInput(body) {
33
+ if (body.type === 'interrupt')
34
+ return { type: 'interrupt' };
35
+ if (body.type === 'say') {
36
+ const { text } = body;
37
+ if (typeof text !== 'string' || !text.trim() || text.length > TEXT_MAX)
38
+ throw bad(`a message is text, up to ${TEXT_MAX} characters`);
39
+ const list = images(body.images);
40
+ return list.length ? { type: 'say', text, images: list } : { type: 'say', text };
41
+ }
42
+ if (body.type === 'answer') {
43
+ const { request_id: id, answers } = body;
44
+ const values = Object.values((answers ?? {}));
45
+ const map = typeof answers === 'object' && answers !== null && !Array.isArray(answers);
46
+ // The id goes to `gcf-harness chat` as a word: one like `--help` would be an option.
47
+ if (typeof id !== 'string' || !/^[A-Za-z0-9_][\w-]*$/.test(id) || !map)
48
+ throw bad('an answer names its request_id and its answers');
49
+ if (!values.length || values.some((x) => typeof x !== 'string'))
50
+ throw bad('each answer is text');
51
+ return { type: 'answer', request_id: id, answers: answers };
52
+ }
53
+ throw bad('type is say, interrupt or answer');
54
+ }
@@ -49,16 +49,23 @@ function globalRoots() {
49
49
  */
50
50
  export function briefError(err) {
51
51
  const m = err.match(/^\w*Error: ([\s\S]*?)\r?\n {4}at /m) ?? err.match(/^\w*Error: (.+)$/m);
52
- return (m?.[1] ?? err).replace(/\r/g, '').trim();
52
+ return (m?.[1] ?? err).replaceAll('\r', '').trim();
53
53
  }
54
- /** Run `ai-factory <args>` in a project; a move can wait up to a minute on gcf's main lock. */
55
- export function runCli(entry, cwd, args, timeoutMs = 120_000) {
54
+ /**
55
+ * Run `ai-factory <args>` in a project; a move can wait up to a minute on gcf's main lock.
56
+ * `input` goes to its stdin: a text longer than a command line may be.
57
+ */
58
+ export function runCli(entry, cwd, args, timeoutMs = 120_000, input) {
56
59
  return new Promise((resolve) => {
57
60
  const child = spawn(process.execPath, [entry, ...args], {
58
61
  cwd,
59
62
  shell: false,
60
- stdio: ['ignore', 'pipe', 'pipe'],
63
+ stdio: ['pipe', 'pipe', 'pipe'],
61
64
  });
65
+ // No input is an empty stdin. A command that ends before it reads it breaks the pipe: its
66
+ // exit says why.
67
+ child.stdin.on('error', () => { });
68
+ child.stdin.end(input);
62
69
  // A decoder per stream: a Cyrillic letter cut between two chunks stays one letter.
63
70
  child.stdout.setEncoding('utf8');
64
71
  child.stderr.setEncoding('utf8');
@@ -24,6 +24,19 @@ export function openInBrowser(url) {
24
24
  }
25
25
  /** A PowerShell single-quoted string: a quote inside is doubled. */
26
26
  const psQuote = (s) => `'${s.replaceAll("'", "''")}'`;
27
+ /** A POSIX shell single-quoted string: nothing inside expands; a quote closes, escapes, reopens. */
28
+ const shQuote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
29
+ /**
30
+ * A quoted .desktop Exec argument: `"`, `` ` ``, `$` and `\` escaped inside the quotes, then the
31
+ * key's own string escape doubles each backslash and writes a line break as `\n` (a raw one would
32
+ * end the key), and `%` (a field code) is written `%%`.
33
+ */
34
+ const execQuote = (s) => `"${s.replace(/["`$\\]/g, '\\$&')}"`
35
+ .replaceAll('\\', '\\\\')
36
+ .replaceAll('\n', '\\n')
37
+ .replaceAll('\r', '\\r')
38
+ .replaceAll('\t', '\\t')
39
+ .replaceAll('%', '%%');
27
40
  export function shortcutPlan(platform, node, main, port) {
28
41
  const args = ['--port', String(port)];
29
42
  if (platform === 'win32')
@@ -41,15 +54,16 @@ export function shortcutPlan(platform, node, main, port) {
41
54
  `Join-Path $d '${NAME}.lnk'`,
42
55
  ].join('; '),
43
56
  };
44
- const command = `"${node}" "${main}" ${args.join(' ')}`;
57
+ // A `$(…)` or a quote in an install path stays part of the path.
58
+ const command = (quote) => [quote(node), quote(main), ...args].join(' ');
45
59
  if (platform === 'darwin')
46
60
  return {
47
61
  file: path.join(os.homedir(), 'Desktop', `${NAME}.command`),
48
- text: `#!/bin/sh\nexec ${command}\n`,
62
+ text: `#!/bin/sh\nexec ${command(shQuote)}\n`,
49
63
  };
50
64
  return {
51
65
  file: path.join(os.homedir(), '.local', 'share', 'applications', 'gcf-board.desktop'),
52
- text: `[Desktop Entry]\nType=Application\nName=${NAME}\nExec=${command}\nTerminal=false\n` +
66
+ text: `[Desktop Entry]\nType=Application\nName=${NAME}\nExec=${command(execQuote)}\nTerminal=false\n` +
53
67
  'Categories=Development;\n',
54
68
  };
55
69
  }
@@ -30,7 +30,7 @@ export function broadcast(event) {
30
30
  // reports a mark's expiry.
31
31
  const SESSION_TTL_MS = 120 * 60_000;
32
32
  const LOG_STEP_MS = 10_000;
33
- const alive = (pid) => {
33
+ export const alive = (pid) => {
34
34
  if (!Number.isInteger(pid) || pid <= 0)
35
35
  return false;
36
36
  try {
@@ -113,11 +113,25 @@ export function watchProject(p, debounceMs = 300) {
113
113
  });
114
114
  const runs = path.join(p.path, '.gcf-session', 'runs');
115
115
  let last = runsState(runs);
116
+ const quotaAt = () => {
117
+ try {
118
+ return statSync(path.join(runs, 'quota.json')).mtimeMs;
119
+ }
120
+ catch {
121
+ return 0;
122
+ }
123
+ };
124
+ let read = quotaAt();
116
125
  const poll = setInterval(() => {
117
126
  const now = runsState(runs);
118
127
  if (now !== last)
119
128
  fire();
120
129
  last = now;
130
+ // The limit is the account's: a new reading here changes every project's top bar.
131
+ const quota = quotaAt();
132
+ if (quota !== read)
133
+ broadcast({ type: 'quota' });
134
+ read = quota;
121
135
  }, 1500);
122
136
  return () => {
123
137
  for (const w of watchers)
@@ -57,12 +57,13 @@ async function inside(root, file) {
57
57
  }
58
58
  /**
59
59
  * Follow the run log of `id` as it grows: its last 256 KB first, then every new chunk, polled
60
- * each second (a log on another disk does not always fire a watch). A log that shrank was
60
+ * each second (a log on another disk does not always fire a watch). Its chat (`ext` chat.jsonl,
61
+ * docs/Chat-Plan.md) is the conversation's history: read from its start. A log that shrank was
61
62
  * started again: a `reset` event tells the page to drop what it holds, then it is read from its
62
63
  * start. One decoder for the stream: a letter cut between two reads stays whole.
63
64
  */
64
- export function followLog(root, id, res) {
65
- const file = path.join(root, '.gcf-session', 'runs', `${id}.log`);
65
+ export function followLog(root, id, res, ext = 'log') {
66
+ const file = path.join(root, '.gcf-session', 'runs', `${id}.${ext}`);
66
67
  openStream(res);
67
68
  let pos = -1;
68
69
  let decoder = new StringDecoder('utf8');
@@ -71,7 +72,7 @@ export function followLog(root, id, res) {
71
72
  return;
72
73
  const { size } = await stat(file);
73
74
  if (pos < 0)
74
- pos = Math.max(0, size - 256 * 1024);
75
+ pos = ext === 'log' ? Math.max(0, size - 256 * 1024) : 0;
75
76
  if (size < pos) {
76
77
  pos = 0;
77
78
  decoder = new StringDecoder('utf8');
@@ -0,0 +1,50 @@
1
+ // `node relay.js <record> <end file> <ai-factory entry> <harness> run <ids> --json …`: the process
2
+ // a board run lives in (runs.ts). The board starts it detached, so the run outlives the board
3
+ // (Ctrl+C in its console, its window closed, a restart); it starts the harness with
4
+ // `windowsHide`, so the harness and all it starts share one hidden console: a detached process
5
+ // has none, and each console program it started would open a window of its own. The harness's
6
+ // code, stdout and stderr go to the end file once, whole, when it ends. While it runs, the relay
7
+ // touches the record: a board started again tells it from a dead relay whose pid another took.
8
+ import { spawn } from 'node:child_process';
9
+ import { rmSync, utimesSync, writeFileSync } from 'node:fs';
10
+ import { writeAtomic } from './atomic.js';
11
+ // A board that finds the run at its start counts the relay dead after three missed beats
12
+ // (BEAT_STALE_MS in runs.ts).
13
+ const BEAT_MS = 30_000;
14
+ const [record, end, ...args] = process.argv.slice(2);
15
+ const beat = setInterval(() => {
16
+ try {
17
+ const now = new Date();
18
+ utimesSync(record, now, now);
19
+ }
20
+ catch {
21
+ // Its write failed, or a board took it already: nothing to touch.
22
+ }
23
+ }, BEAT_MS);
24
+ beat.unref();
25
+ const child = spawn(process.execPath, args, {
26
+ stdio: ['ignore', 'pipe', 'pipe'],
27
+ windowsHide: true,
28
+ });
29
+ child.stdout.setEncoding('utf8');
30
+ child.stderr.setEncoding('utf8');
31
+ let out = '';
32
+ let err = '';
33
+ child.stdout.on('data', (d) => (out += d));
34
+ child.stderr.on('data', (d) => (err += d));
35
+ let done = false;
36
+ const finish = (code, message = '') => {
37
+ // A spawn that fails fires both error and close: one end only.
38
+ if (done)
39
+ return;
40
+ done = true;
41
+ const text = JSON.stringify({ code, out, err: err + message });
42
+ // A rename a scanner holds up: the end still goes, written in place.
43
+ writeAtomic(end, text).catch(() => {
44
+ writeFileSync(end, text);
45
+ // writeAtomic's own temporary file, left by the rename that failed.
46
+ rmSync(`${end}.${process.pid}.tmp`, { force: true });
47
+ });
48
+ };
49
+ child.on('error', (e) => finish(null, e.message));
50
+ child.on('close', (code) => finish(code));