@jjanczur/tyran 0.1.23 → 0.1.25

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/scripts/board.mjs CHANGED
@@ -20,7 +20,7 @@
20
20
  * initiative reads as "all is well" exactly when it is not.
21
21
  *
22
22
  * CLI:
23
- * node board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>]]
23
+ * node board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>] [--write]]
24
24
  * Exit: 0 ok · 1 drift (--check) · 2 usage/IO
25
25
  */
26
26
  import { existsSync, readdirSync, statSync, readFileSync } from 'node:fs';
@@ -39,10 +39,13 @@ import {
39
39
  inline,
40
40
  warnings,
41
41
  writeAllAtomic,
42
+ writeAtomic,
42
43
  } from './project.mjs';
43
44
  import { jsonEscapeInvisible } from './invisible.mjs';
44
45
  import { renderBoardError, renderBoardHtml } from './board-html.mjs';
45
46
  import { COST_SCHEMA, costJson, costReport } from './cost.mjs';
47
+ import { SettingsError, applyPolicyClass, applySetting, readSettings } from './settings.mjs';
48
+ import { checkStopAt } from './stop-check.mjs';
46
49
 
47
50
  export const BOARD_HTML_FILE = 'board.html';
48
51
 
@@ -136,8 +139,10 @@ export function readInitiativeBoards(tyranDir) {
136
139
  * rather than embedded. Relative is also the more useful form — it is what
137
140
  * the reader pastes, from the repo root, into an editor.
138
141
  *
139
- * Nothing is served: `--serve` routes three URLs and derives a filesystem
140
- * path from none of them, which is worth more than a clickable link.
142
+ * Nothing is served from here: `--serve` derives a filesystem path from no
143
+ * URL at all, which is worth more than a clickable link. The one route that
144
+ * writes — Settings, behind `--write` — reaches two fixed files named in
145
+ * `settings.mjs` and takes a KEY from the request, never a path.
141
146
  */
142
147
  export const INITIATIVE_FILES = Object.freeze(['PLAN.md', 'NOTES.md', 'RETRO.md', 'STATE.md', 'PROGRESS.md']);
143
148
 
@@ -151,10 +156,20 @@ export function initiativeFiles(tyranDir, name) {
151
156
  }
152
157
 
153
158
  /** Pure merge of per-initiative boards into the one payload. */
154
- export function crossBoard({ initiatives, errors, warned = [] }) {
159
+ /**
160
+ * How many logged errors travel in the payload.
161
+ *
162
+ * `board.json` is committed and compared byte for byte, so an unbounded list
163
+ * would grow the artefact with every bad night. Newest first and a count for
164
+ * the rest: the board's job is to say something is wrong, not to be the log.
165
+ */
166
+ export const MAX_LOGGED_ERRORS = 20;
167
+
168
+ export function crossBoard({ initiatives, errors, warned = [], stop = null }) {
155
169
  const asks = [];
156
170
  const agents = [];
157
171
  const paused = [];
172
+ const logged = [];
158
173
  const files = {};
159
174
  const lanes = Object.fromEntries(LANES.map((lane) => [lane, []]));
160
175
  let merged = 0;
@@ -169,6 +184,22 @@ export function crossBoard({ initiatives, errors, warned = [] }) {
169
184
  for (const a of board.agents) agents.push({ ...a, init: name });
170
185
  if (board.paused !== null) paused.push({ ...board.paused, init: name });
171
186
  if (docs !== undefined && docs.length > 0) files[name] = docs;
187
+ // An `error` event with no ticket landed in STATE.md's Errors table and
188
+ // nowhere else: the fold collects it, and the board that exists to say
189
+ // "not all is well" carried neither `state.errors` nor the tickets an
190
+ // error named that the journal has never seen. A whole class of agent
191
+ // failure was invisible on the one screen meant to show it.
192
+ for (const e of state.errors) {
193
+ logged.push({
194
+ init: name,
195
+ class: e.class,
196
+ detail: e.detail,
197
+ ticket: e.ticket ?? null,
198
+ ticket_unknown: e.ticket_unknown === true,
199
+ ts: e.ts,
200
+ actor: e.actor,
201
+ });
202
+ }
172
203
  for (const lane of LANES) {
173
204
  for (const card of board.lanes.get(lane)) lanes[lane].push({ ...card, init: name });
174
205
  }
@@ -181,6 +212,9 @@ export function crossBoard({ initiatives, errors, warned = [] }) {
181
212
  // ISO string from the journal, so ascending string order IS ascending time;
182
213
  // an agent with no signal at all sorts to the front, where it belongs.
183
214
  agents.sort((a, b) => String(a.last_signal ?? '').localeCompare(String(b.last_signal ?? '')));
215
+ // Newest first: an error from four days ago is history, the one from ten
216
+ // minutes ago is the reason you opened this page.
217
+ logged.sort((a, b) => String(b.ts ?? '').localeCompare(String(a.ts ?? '')));
184
218
 
185
219
  return {
186
220
  schema: 1,
@@ -199,11 +233,26 @@ export function crossBoard({ initiatives, errors, warned = [] }) {
199
233
  blocked: lanes.blocked.length + lanes['changes-requested'].length
200
234
  + agents.filter((a) => a.state === 'blocked').length,
201
235
  },
236
+ // Committed repo state, so it belongs in the artefact rather than behind a
237
+ // route: `.tyran/STOP` is identical in every clone, and `--check` stays
238
+ // byte-exact. The machine-local half of "is this run supposed to be
239
+ // running" — the pause marker, the resume watcher — is served instead,
240
+ // for the same reason spend is.
241
+ // `{stopped, reason}` and NOT the path `checkStopAt` also returns: an
242
+ // absolute path in a committed, byte-compared artefact makes two clones of
243
+ // one journal disagree on a machine whose home directory is spelled
244
+ // differently. The same trap the initiative file list was caught in.
245
+ stop: stop === null ? null : { stopped: stop.stopped, reason: stop.reason },
202
246
  paused,
203
247
  asks,
204
248
  agents,
205
249
  files,
206
250
  lanes,
251
+ // The key is `errors_logged`, NOT `errors`: `errors` on this payload
252
+ // already means "this initiative's journal could not be read at all", and
253
+ // one key with two meanings is the defect ADR-21 is named after.
254
+ errors_logged: logged.slice(0, MAX_LOGGED_ERRORS),
255
+ errors_logged_total: logged.length,
207
256
  errors,
208
257
  warned,
209
258
  };
@@ -220,6 +269,11 @@ export function renderCrossMd(payload) {
220
269
  `**${t.agents} agent(s) running across ${t.initiatives} initiative(s) · ` +
221
270
  `${t.merged}/${t.tickets} tickets merged (${t.percent}%) · as of ${inline(payload.as_of)}**\n`,
222
271
  );
272
+ // First, and above the pause: a STOP outranks everything. It is the one
273
+ // state where a strip of silent agents is the system doing as it was told.
274
+ if (payload.stop?.stopped === true) {
275
+ parts.push(`\n**STOPPED** — an operator halted this repo: ${inline(payload.stop.reason)}\n`);
276
+ }
223
277
  for (const p of payload.paused) {
224
278
  parts.push(`\n**PAUSED** — ${inline(p.init)}: gate ${inline(p.kind)} (${inline(p.result)}) since ${inline(p.since)}\n`);
225
279
  }
@@ -229,6 +283,13 @@ export function renderCrossMd(payload) {
229
283
  for (const d of payload.warned ?? []) {
230
284
  for (const w of d.warnings) parts.push(`\n**WARNING** — ${inline(d.name)}: ${inline(w)}\n`);
231
285
  }
286
+ for (const e of payload.errors_logged ?? []) {
287
+ const what = `${inline(e.class ?? 'error')}${e.detail != null ? `: ${inline(e.detail)}` : ''}` +
288
+ (e.ticket_unknown ? ` — it names ticket ${inline(e.ticket)}, which this journal has never declared` : '');
289
+ parts.push(`\n**ERROR** — ${inline(e.init)}: ${what} (${inline(e.ts)})\n`);
290
+ }
291
+ const hidden = (payload.errors_logged_total ?? 0) - (payload.errors_logged ?? []).length;
292
+ if (hidden > 0) parts.push(`\n**ERROR** — and ${hidden} older error(s); read the journals for the rest\n`);
232
293
 
233
294
  parts.push('\n## Waiting on you\n\n');
234
295
  if (payload.asks.length === 0) parts.push('_none — the agents have what they need_\n');
@@ -277,7 +338,12 @@ export function renderCrossMd(payload) {
277
338
  }
278
339
 
279
340
  export function renderAll(tyranDir) {
280
- const payload = crossBoard(readInitiativeBoards(tyranDir));
341
+ const payload = crossBoard({
342
+ ...readInitiativeBoards(tyranDir),
343
+ // Named from the board's own directory rather than reconstructed from a
344
+ // repo root: `--dir` need not be spelled `.tyran`.
345
+ stop: checkStopAt(join(tyranDir, 'STOP')),
346
+ });
281
347
  const json = crossJson(payload);
282
348
  return {
283
349
  payload,
@@ -289,13 +355,116 @@ export function renderAll(tyranDir) {
289
355
  };
290
356
  }
291
357
 
358
+ // ------------------------------------------------------- the write channel
359
+
360
+ /** A request body big enough for any setting and small enough to ignore. */
361
+ const MAX_BODY_BYTES = 64 * 1024;
362
+
363
+ /**
364
+ * Read a JSON request body, or reject it.
365
+ *
366
+ * Three refusals, all deliberate. A body over the cap is dropped rather than
367
+ * buffered, because this server has no reason to hold a megabyte of anything.
368
+ * A body that is not `application/json` is refused BEFORE it is read — that
369
+ * content type is what forces a browser to preflight a cross-origin POST, and
370
+ * accepting `text/plain` here would hand back the exact hole the preflight
371
+ * closes. And anything that is not a JSON object is refused, so a handler
372
+ * never reasons about a string that happens to have a `.value`.
373
+ */
374
+ function readJsonBody(req) {
375
+ return new Promise((resolve_, reject) => {
376
+ const type = String(req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
377
+ if (type !== 'application/json') {
378
+ reject(new SettingsError('this route takes application/json'));
379
+ return;
380
+ }
381
+ let size = 0;
382
+ const chunks = [];
383
+ req.on('data', (chunk) => {
384
+ size += chunk.length;
385
+ if (size > MAX_BODY_BYTES) {
386
+ reject(new SettingsError('request body is too large'));
387
+ req.destroy();
388
+ return;
389
+ }
390
+ chunks.push(chunk);
391
+ });
392
+ req.on('error', (err) => reject(err));
393
+ req.on('end', () => {
394
+ let parsed;
395
+ try {
396
+ parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
397
+ } catch {
398
+ reject(new SettingsError('request body is not JSON'));
399
+ return;
400
+ }
401
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
402
+ reject(new SettingsError('request body must be a JSON object'));
403
+ return;
404
+ }
405
+ resolve_(parsed);
406
+ });
407
+ });
408
+ }
409
+
410
+ /**
411
+ * `Origin`, on top of the `Host` pin the whole server already carries.
412
+ *
413
+ * The two answer different questions and neither covers the other. `Host` says
414
+ * which name the client dialled, which stops DNS rebinding. `Origin` says
415
+ * which page is asking, which is the only thing that distinguishes the board's
416
+ * own fetch from a POST issued by some other tab the operator has open. A
417
+ * request with no `Origin` at all is allowed: that is `curl`, and a local
418
+ * process that can reach loopback needs no browser's help — see the honest
419
+ * statement of what this does and does not defend in `docs/board.md`.
420
+ */
421
+ function originAllowed(req) {
422
+ const origin = req.headers.origin;
423
+ if (origin === undefined || origin === 'null') return true;
424
+ try {
425
+ const { hostname } = new URL(String(origin));
426
+ return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1';
427
+ } catch {
428
+ return false;
429
+ }
430
+ }
431
+
432
+ const sendJson = (res, status, body) => {
433
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
434
+ res.end(JSON.stringify(body) + '\n');
435
+ };
436
+
437
+ /**
438
+ * Apply one edit and write it, or change nothing and say why.
439
+ *
440
+ * The write itself is `writeAtomic` — the same rename-into-place the
441
+ * projections use — so a config file can never be found half-written, however
442
+ * the process dies.
443
+ */
444
+ function handleSettingsWrite(dir, route, body) {
445
+ // `confirm` is only ever compared for equality against the value the server
446
+ // itself computed, so a caller cannot widen anything by sending a truthy
447
+ // flag — it has to name the exact change it is making.
448
+ const confirm = typeof body.confirm === 'string' ? body.confirm : null;
449
+ const applied =
450
+ route === 'config'
451
+ ? applySetting(dir, String(body.id ?? ''), body.value, confirm)
452
+ : applyPolicyClass(dir, body.path === null || body.path === undefined ? null : String(body.path), String(body.class ?? ''), confirm);
453
+ writeAtomic(applied.file, applied.text);
454
+ // The operator's terminal is the audit trail. A change made from a web page
455
+ // that left no trace anywhere a person looks is how a settings screen turns
456
+ // into a thing nobody trusts.
457
+ console.log(`board: wrote ${applied.file} — ${applied.path.join('.')}: ${JSON.stringify(applied.before)} -> ${JSON.stringify(applied.after)}`);
458
+ return { ok: true, file: applied.file, path: applied.path, before: applied.before, after: applied.after };
459
+ }
460
+
292
461
  // ------------------------------------------------------------------- CLI
293
462
 
294
- const BOOLEAN_FLAGS = ['check', 'serve'];
463
+ const BOOLEAN_FLAGS = ['check', 'serve', 'write'];
295
464
  const VALUE_FLAGS = ['dir', 'port'];
296
465
 
297
466
  function parseArgs(argv) {
298
- const flags = { dir: '.tyran', port: 4173, check: false, serve: false };
467
+ const flags = { dir: '.tyran', port: 4173, check: false, serve: false, write: false };
299
468
  for (let i = 0; i < argv.length; i += 1) {
300
469
  const arg = argv[i];
301
470
  if (!arg.startsWith('--')) throw new UsageError(`unexpected argument "${arg}"`);
@@ -321,7 +490,11 @@ function main() {
321
490
  } catch (err) {
322
491
  if (!(err instanceof UsageError)) throw err;
323
492
  console.error(`board: ${err.message}`);
324
- console.error('usage: board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>]]');
493
+ console.error('usage: board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>] [--write]]');
494
+ process.exit(2);
495
+ }
496
+ if (flags.write && !flags.serve) {
497
+ console.error('board: --write only means anything with --serve (it is what the served page may edit)');
325
498
  process.exit(2);
326
499
  }
327
500
  const dir = resolve(flags.dir);
@@ -354,6 +527,55 @@ function main() {
354
527
  res.end('forbidden: this board answers to 127.0.0.1 only\n');
355
528
  return;
356
529
  }
530
+ // ---- settings: the routes that read and write config -----------
531
+ //
532
+ // Config is served rather than embedded for the same reason spend is:
533
+ // it is not journal state, it is not a projection, and writing it into
534
+ // `board.json` would break the byte-exact `--check` contract. Over
535
+ // `file://` the fetch fails and the tab says how to open the board
536
+ // with a server, which is the honest answer.
537
+ if (req.url === '/settings.json') {
538
+ sendJson(res, 200, { ...readSettings(dir), writable: flags.write });
539
+ return;
540
+ }
541
+ if (req.url === '/settings/config' || req.url === '/settings/policy') {
542
+ const route = req.url.slice('/settings/'.length);
543
+ if (req.method !== 'POST') {
544
+ sendJson(res, 405, { ok: false, error: 'this route takes POST' });
545
+ return;
546
+ }
547
+ // Writes are OFF unless the operator asked for them on the command
548
+ // line. A board someone left running is a board that can be reached
549
+ // by anything on this machine, and the difference between reading
550
+ // that and editing the autonomy policy through it is the difference
551
+ // this flag exists to make. The refusal names the flag, because a
552
+ // 403 an operator cannot act on is just a bug report.
553
+ if (!flags.write) {
554
+ sendJson(res, 403, {
555
+ ok: false,
556
+ error: 'this board is read-only. Restart it with: npx @jjanczur/tyran board --serve --write',
557
+ });
558
+ return;
559
+ }
560
+ if (!originAllowed(req)) {
561
+ sendJson(res, 403, { ok: false, error: 'forbidden: this board answers its own pages only' });
562
+ return;
563
+ }
564
+ readJsonBody(req)
565
+ .then((body) => sendJson(res, 200, handleSettingsWrite(dir, route, body)))
566
+ .catch((err) => {
567
+ const known = err instanceof SettingsError;
568
+ if (!known) console.error(`board: settings write failed: ${String(err?.message ?? err)}`);
569
+ sendJson(res, known ? 400 : 500, {
570
+ ok: false,
571
+ error: String(err?.message ?? err),
572
+ // Present only on a refusal the operator can answer, and it
573
+ // carries the exact token that answers it.
574
+ ...(err?.widens === true ? { widens: true, confirm_with: err.confirm_with } : {}),
575
+ });
576
+ });
577
+ return;
578
+ }
357
579
  // Spend is served, never rendered into the artefacts. It is derived
358
580
  // from transcripts under the operator's home directory — machine-local
359
581
  // by nature — so putting it in board.json would make two clones of one
@@ -409,7 +631,10 @@ function main() {
409
631
  process.exitCode = 2;
410
632
  });
411
633
  server.listen(flags.port, '127.0.0.1', () => {
412
- console.log(`board: serving http://127.0.0.1:${flags.port}/ (read-only; Ctrl-C to stop)`);
634
+ console.log(
635
+ `board: serving http://127.0.0.1:${flags.port}/ ` +
636
+ `(${flags.write ? 'Settings can edit config.yaml and autonomy.yaml' : 'read-only'}; Ctrl-C to stop)`,
637
+ );
413
638
  });
414
639
  return;
415
640
  }
@@ -554,7 +554,20 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
554
554
  state.retro.push({ kind: data.kind ?? null, target: data.target ?? null, confidence: data.confidence ?? null, ts });
555
555
  break;
556
556
  case 'error': {
557
- state.errors.push({ class: data.class ?? null, detail: data.detail ?? null, ts, actor });
557
+ // The ticket travels ON the error, not only in the separate
558
+ // unknown-ticket list. A consumer that wanted both — the board does —
559
+ // otherwise had to join the two by timestamp, and emitted one event as
560
+ // two rows when it could not.
561
+ const errTicket = data.ticket != null ? String(data.ticket) : null;
562
+ const errKnown = errTicket !== null && state.tickets.has(errTicket);
563
+ state.errors.push({
564
+ class: data.class ?? null,
565
+ detail: data.detail ?? null,
566
+ ts,
567
+ actor,
568
+ ticket: errTicket,
569
+ ticket_unknown: errTicket !== null && !errKnown,
570
+ });
558
571
  // `data.ticket` is optional metadata on an error, so a typo here is a
559
572
  // typo nothing rejected at append. Binding it to a ticket the journal
560
573
  // has never seen would MINT that ticket, and a minted ticket is one
@@ -1210,6 +1223,13 @@ export function writeAllAtomic(entries) {
1210
1223
  const staged = [];
1211
1224
  try {
1212
1225
  for (const [path, content] of entries) {
1226
+ // The directory may not exist yet, and the first time that matters is
1227
+ // the worst time: `.tyran/state/` is created by the first initiative, so
1228
+ // `board.mjs --dir .tyran` on a freshly set-up repo — the command the
1229
+ // README leads with — died with an ENOENT naming a temp file nobody had
1230
+ // heard of. Staging into a directory is not a decision, it is what
1231
+ // writing a file there means.
1232
+ mkdirSync(dirname(path), { recursive: true });
1213
1233
  const tmp = tempPathFor(path);
1214
1234
  writeFileSync(tmp, content, 'utf8');
1215
1235
  staged.push([tmp, path]);
@@ -355,6 +355,26 @@ export function scanRepo(dir, { run = gitRunner(dir) } = {}) {
355
355
  tiers: { cheap: 'haiku', work: 'sonnet', deep: 'opus', top: 'fable' },
356
356
  validation,
357
357
  shared_zones: [],
358
+ // Written out in full, every value at its shipped default, with the
359
+ // feature OFF. Nothing here enables anything — `mode: 'off'` is the same
360
+ // inert state as omitting the block entirely.
361
+ //
362
+ // The difference is that an absent key cannot be edited. The board's
363
+ // Settings tab patches values that exist and deliberately refuses to
364
+ // invent keys (choosing where a key goes and what comment explains it is
365
+ // authoring, not editing), so a scanned config with no `limits:` rendered
366
+ // the whole Overnight section as dead text on every fresh install. So did
367
+ // doctor's `limit-telemetry-missing`, which is conditioned on a mode that
368
+ // was never written.
369
+ limits: {
370
+ mode: 'off',
371
+ pause_at_percent: 97,
372
+ weekly_pause_at_percent: 97,
373
+ wait_max_hours: 5,
374
+ long_wait: 'hold',
375
+ resume_margin_minutes: 5,
376
+ keep_awake: false,
377
+ },
358
378
  };
359
379
 
360
380
  const questions = [];