@jjanczur/tyran 0.1.45 → 0.1.47

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.
@@ -11,7 +11,7 @@
11
11
  {
12
12
  "name": "tyran",
13
13
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
14
- "version": "0.1.45",
14
+ "version": "0.1.47",
15
15
  "source": "./",
16
16
  "author": {
17
17
  "name": "Jacek Janczura",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tyran",
3
- "version": "0.1.45",
3
+ "version": "0.1.47",
4
4
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
5
5
  "author": {
6
6
  "name": "Jacek Janczura",
package/CHANGELOG.md CHANGED
@@ -1,5 +1,117 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.47 — 2026-09-19
4
+
5
+ ### The secrets gate scans 10 MiB, and buys the time to do it
6
+
7
+ `MAX_PAYLOAD_BYTES` goes from 4 MiB to 10 MiB, together with what the number
8
+ depends on: `DEADLINE_MS` 7 s → 15 s, the scanner's own budget 5 s → 11 s and
9
+ the registered `timeout` 15 s → 30 s, the most a hook here may declare. The
10
+ old ceiling was true to its 7 s budget, and it made a finished change on a
11
+ real project — two 2.4 MB translation catalogs plus the code that used them —
12
+ into three commits and a chunked push, because the gate could not scan them
13
+ in one go.
14
+
15
+ Measured end to end through the real hook before the number was written
16
+ (8 cores, load average 3): copies of a 2.4 MB JSON catalog, 4 MiB / 3.14 s,
17
+ 8 MiB / 5.99 s, 9.5 MiB / 7.45 s; base64 folded at 76 columns,
18
+ 9.9 MiB / 6.97 s. The ceiling counts every object git would write, so 9.9 MiB
19
+ of catalog files arrived as 10,703,651 bytes in nine objects and was refused
20
+ in 0.08 s.
21
+
22
+ One cost the size made visible, recorded in `docs/hooks.md`: gitleaks 8.30.1
23
+ stops reading a single line that carries no newline, deterministically per
24
+ payload and chunking, exits 0 and reports the smaller count — 3 of 18 runs at
25
+ 8 MiB of unbroken base64, 0 of 6 at 4 MiB, never with newlines. The coverage
26
+ check refuses such a scan rather than trusting it, which is unchanged and is
27
+ the point of that check.
28
+
29
+ The pins moved with the numbers: `tests/unit/hook-secrets-gate.test.mjs` pins
30
+ 10,485,760 and 17,000 and sizes its oversized-report fixture from the constant
31
+ instead of a literal.
32
+
33
+ ## 0.1.46 — 2026-08-22
34
+
35
+ ### The wall is readable, and a question no longer costs a night
36
+
37
+ Two failures were losing whole nights on a real install, and neither was
38
+ visible while it happened.
39
+
40
+ **The pause could never fire.** A repo configured `limits: mode: pause,
41
+ pause_at_percent: 99` drove into the account wall at full speed on three
42
+ separate nights. Both telemetry channels are dark on Claude Code 2.1.197: the
43
+ statusline payload carries no `rate_limits` block — no `usage.json` had ever
44
+ been written in ANY repo on that machine — and `cachedUsageUtilization` is not
45
+ a key of `~/.claude.json` at all. The gate fails open on absent telemetry, by
46
+ design, so nothing said so.
47
+
48
+ The signal exists, and it is the wall itself. Every rejected request lands in
49
+ the session transcript as an assistant record carrying `quotaLimits: {status:
50
+ "rejected", rateLimitType, resetsAt}` — 45 of them across one machine's
51
+ projects, including in `subagents/*.jsonl`, which is the seam this project had
52
+ written off as needing a platform signal it did not have. `usage-transcript.mjs`
53
+ reads it as a third channel, after the two percentage sources, because it is
54
+ exact and LATE: it reports 100% of a window already spent, so it restores the
55
+ clean wind-down and the scheduled resume rather than the early stop.
56
+
57
+ The correctness rule is not "resetsAt is ahead of us". Measured: a weekly
58
+ rejection carrying a reset five days out is followed by 565 successful
59
+ assistant messages in the same file, because an allowance can be topped up.
60
+ Acting on the reset alone would have held a working machine until the
61
+ following Friday — a worse failure than the one being fixed, since a false
62
+ pause burns the night the pause was meant to save. So a rejection counts only
63
+ while nothing newer shows a named model answering, reconciled on one timeline
64
+ across a session and its agents.
65
+
66
+ **Nothing resumed, because nothing was awake to.** After a five-hour wall the
67
+ conductor's own request is the one rejected, so it cannot checkpoint, cannot
68
+ run the wind-down and cannot arm a resume. Measured on this machine: walled at
69
+ 19:25 with the window resetting at 20:00, first real answer at 20:30 — half an
70
+ hour lost because the reset was nobody's job. `overnight.mjs watch-limit` and
71
+ the served board's own timer now do that job, handing off to the existing
72
+ `schedule` so the hold policy, the weekly deferral and the babysitting ladder
73
+ are the ones already there.
74
+
75
+ ### Unattended delivery — the default that finally ships itself
76
+
77
+ An open ask has **no timeout, no expiry and no auto-apply** anywhere in Tyran.
78
+ It sits `WAITING_ON_OPERATOR` forever; doctor turns info into warning after 72
79
+ hours of journal time and that is the whole consequence. The ask protocol has
80
+ said "record a `default` — what ships if nobody ever answers" since it was
81
+ written, and nothing ever took one: it fired when a human clicked **Take the
82
+ default**, at which point somebody was awake and the promise was moot.
83
+
84
+ `unattended: mode: on` closes an ask with its own recommendation the moment it
85
+ is raised, and the run keeps going. Two refusals are mechanical: an ask with
86
+ no recommendation and no default is a real question, and an ask raised
87
+ `--blocking` is its author saying this one must wake you. `.tyran/STOP` still
88
+ outranks both. Everything taken is journalled as `answer_mode: unattended`
89
+ with its decision text prefixed `(auto-accepted overnight)` — an auto-ruling
90
+ that looked like the operator's own would be the failure this is judged by.
91
+
92
+ A recommendation now becomes the `default` at the mint when no other is given.
93
+ The two fields stay distinct, but an ask recording only an opinion rendered as
94
+ `blocking · no safe default` and stopped the queue on a question its own
95
+ author had answered.
96
+
97
+ ### Smaller, and each one a silence
98
+
99
+ - **Answering on the board never woke the conductor.** The terminal path has
100
+ offered to since answers existed; `POST /answer` re-rendered the page and
101
+ returned, so a ruling made at 23:00 sat until a session happened to start.
102
+ - **`limit-near`** — `warn` promised to surface and never did. The gate
103
+ returns PASS ("surfacing is doctor's job") and doctor compared no percentage
104
+ to any threshold, so `warn` differed from `off` in nothing visible.
105
+ - **`limit-watcher-absent`** — a pause in force with no watcher beside it.
106
+ `limit-pause-stale` fires only once `resume_at` has already passed.
107
+ - **`limit-statusline-stale`** — a statusline pinned to a plugin-cache version
108
+ that is no longer running. A cache is not an archive; when it is pruned the
109
+ telemetry stops with no symptom but a pause that never fires.
110
+ - Two findings recorded rather than papered over: `SESSION_ID_RE` admits
111
+ `--dangerous`, so the watcher's filename-sourced id uses a stricter pattern;
112
+ and both marker writers throw on `resets_at: undefined`, unreachable and
113
+ left shared because a guard on one side is a silent divergence.
114
+
3
115
  ## 0.1.45 — 2026-08-22
4
116
 
5
117
  ### The review reads data access and structure, and the self-review has criteria
package/README.md CHANGED
@@ -329,7 +329,7 @@ enforces the cap (3947 of 5000 characters). What each one assumes, when it
329
329
  fires and who invokes it, is in
330
330
  [skills and agents](https://jjanczur.github.io/tyran/skills/); the prompts
331
331
  themselves are in [`skills/`](skills/) and [`agents/`](agents/). Behind all of
332
- it: 1660 unit tests, run with `node --test "tests/**/*.test.mjs"`.
332
+ it: 1713 unit tests, run with `node --test "tests/**/*.test.mjs"`.
333
333
 
334
334
  ## Documentation
335
335
 
package/hooks/hooks.json CHANGED
@@ -19,7 +19,7 @@
19
19
  {
20
20
  "type": "command",
21
21
  "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/scripts/secrets-gate.mjs\"",
22
- "timeout": 15
22
+ "timeout": 30
23
23
  }
24
24
  ]
25
25
  },
@@ -71,13 +71,13 @@ import { fileURLToPath } from 'node:url';
71
71
  import { PASS, field, main, runGate } from './hook-io.mjs';
72
72
 
73
73
  /** This gate's own budget, half the `timeout` its hooks.json entry declares. */
74
- export const DEADLINE_MS = 7000;
74
+ export const DEADLINE_MS = 15000;
75
75
 
76
76
  /** Left unspent so a refusal can still be serialized after the last child. */
77
77
  export const DEADLINE_MARGIN_MS = 1200;
78
78
 
79
79
  /** No single child may hold the whole budget; several have to run. */
80
- export const CHILD_BUDGET_MS = 5000;
80
+ export const CHILD_BUDGET_MS = 11000;
81
81
 
82
82
  /** Cheap `git` queries. Generous next to a measured 24-75 ms. */
83
83
  export const GIT_BUDGET_MS = 2000;
@@ -85,17 +85,23 @@ export const GIT_BUDGET_MS = 2000;
85
85
  /**
86
86
  * The most content this gate will assemble and scan.
87
87
  *
88
- * 4 MB, not 8. The 8 MB figure came from timing `gitleaks stdin` in isolation
89
- * (1.07 s) and ignored everything the gate spends BEFORE the scan — listing
90
- * objects, reading them, and the git calls in front of both. Review measured
91
- * the real ceiling inside the budget at roughly 4.5 MB, so the constant is set
92
- * below it rather than at the number that made the prose sound better.
88
+ * 10 MiB, against a 15 s deadline (hooks.json: 30 s, the most a hook here may
89
+ * register). The first figure here
90
+ * was 8 MB and it was never true: it came from timing `gitleaks stdin` in
91
+ * isolation (1.07 s) and ignored everything the gate spends BEFORE the scan —
92
+ * listing objects, reading them, and the git calls in front of both. Review
93
+ * measured the real ceiling inside the 7 s budget of that time at roughly
94
+ * 4.5 MB, and the constant sat at 4 MiB for the next rounds. It was raised
95
+ * together with the deadline, not instead of it, when 4 MiB forced a real
96
+ * project to split one finished change into several commits and pushes just
97
+ * to get its two 2.4 MB translation catalogs past the gate (measured
98
+ * end to end on that machine: see `docs/hooks.md`, "Costs that are deliberate").
93
99
  *
94
100
  * Past it the gate REFUSES rather than scanning a prefix: a partial scan that
95
101
  * reports nothing is indistinguishable from a clean one, which is the defect
96
102
  * this whole file exists to remove.
97
103
  */
98
- export const MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
104
+ export const MAX_PAYLOAD_BYTES = 10 * 1024 * 1024;
99
105
 
100
106
  /** Bytes of a command we are willing to hand to the scanner as data. */
101
107
  export const MAX_COMMAND_BYTES = 128 * 1024;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.45",
3
+ "version": "0.1.47",
4
4
  "description": "Command-line scripts for the Tyran task conductor (doctor, journal, schema, and repo tooling) for CI and terminals outside Claude Code. Installing this package does NOT install the Claude Code plugin — add that separately with `/plugin marketplace add jjanczur/tyran` inside Claude Code.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -41,6 +41,7 @@
41
41
  * CLI:
42
42
  * node answer.mjs render [--dir <.tyran>] [--force]
43
43
  * node answer.mjs apply [--dir <.tyran>] [--dry-run] [--resume]
44
+ * node answer.mjs auto [--dir <.tyran>] [--dry-run] # unattended.mode: on
44
45
  * Exit: 0 ok · 1 nothing is waiting on you · 2 usage, IO, a sheet that did
45
46
  * not parse, or a sheet with answers already typed into it
46
47
  */
@@ -54,6 +55,8 @@ import { append, ASK_KIND_RE, CAPPED_DATA_KEYS, readJournal } from './journal.mj
54
55
  import { formatCodePoint, invisibleProblem } from './invisible.mjs';
55
56
  import { resumeArgv, SESSION_ID_RE } from './overnight.mjs';
56
57
  import { inlinePlain, naturalCompare, projectFile, WAITING_RE, writeAllAtomic, writeAtomic } from './project.mjs';
58
+ import { unattendedOf } from './schema.mjs';
59
+ import { parse } from './yaml-lite.mjs';
57
60
  import { wantsHelp } from './cli-args.mjs';
58
61
 
59
62
  /** The sheet, and the session record `apply --resume` reads. Both under
@@ -396,13 +399,31 @@ export function answerProblem(answer) {
396
399
  * `ticket` comes from the ASK, which came from the journal. Nothing here may
397
400
  * come from the sheet.
398
401
  */
402
+ /**
403
+ * How each verdict mode is recorded. One table, because the three fields have
404
+ * to agree: a decision whose text says a human ruled, next to a gate whose
405
+ * `answer_mode` says nobody did, is a ledger that cannot be read back.
406
+ *
407
+ * `unattended` is the one nobody was awake for. It is prefixed IN THE DECISION
408
+ * TEXT rather than only in a field, because the decision stream is what an
409
+ * operator actually reads in the morning, and a night's auto-accepted rulings
410
+ * that look identical to their own is the failure this whole feature would be
411
+ * judged by.
412
+ */
413
+ const RECORDING = Object.freeze({
414
+ default: { prefix: '(default accepted) ', actor: 'operator', answer_mode: 'default' },
415
+ answered: { prefix: '', actor: 'operator', answer_mode: 'operator' },
416
+ unattended: { prefix: '(auto-accepted overnight) ', actor: 'overnight', answer_mode: 'unattended' },
417
+ });
418
+
399
419
  export function eventsFor(ask, verdict, decisionId = null) {
420
+ const how = RECORDING[verdict.mode] ?? RECORDING.answered;
400
421
  const decision = {
401
422
  ev: 'decision',
402
423
  init: ask.init,
403
- actor: 'operator',
424
+ actor: how.actor,
404
425
  data: {
405
- text: `${ask.kind}: ${verdict.mode === 'default' ? '(default accepted) ' : ''}${verdict.text}`,
426
+ text: `${ask.kind}: ${how.prefix}${verdict.text}`,
406
427
  ask: ask.kind,
407
428
  ...(ask.ticket != null ? { ticket: String(ask.ticket) } : {}),
408
429
  },
@@ -410,20 +431,92 @@ export function eventsFor(ask, verdict, decisionId = null) {
410
431
  const gate = {
411
432
  ev: 'gate',
412
433
  init: ask.init,
413
- actor: 'operator',
434
+ actor: how.actor,
414
435
  data: {
415
436
  kind: ask.kind,
416
437
  result: 'answered',
417
438
  ...(ask.ticket != null ? { ticket: String(ask.ticket) } : {}),
418
439
  answer: verdict.text,
419
- answer_mode: verdict.mode === 'default' ? 'default' : 'operator',
440
+ answer_mode: how.answer_mode,
420
441
  decision: decisionId,
421
- via: ANSWERS_FILE,
442
+ via: verdict.mode === 'unattended' ? UNATTENDED_VIA : ANSWERS_FILE,
422
443
  },
423
444
  };
424
445
  return { decision, gate };
425
446
  }
426
447
 
448
+ /** What the `via` field says when no human was in the loop. */
449
+ export const UNATTENDED_VIA = 'unattended.mode: on';
450
+
451
+ /**
452
+ * Why an ask may not be auto-answered, or null when it may.
453
+ *
454
+ * BOTH refusals are mechanical, and that is the point: `unattended.mode: on`
455
+ * is a standing instruction to rule on the operator's behalf, and an
456
+ * instruction like that is only safe if the exceptions are enforced by code
457
+ * rather than by an agent remembering them.
458
+ *
459
+ * - No recommendation means nobody wrote down what to do. `raiseAsk` copies
460
+ * a recommendation into `default` when the asker gives no other, so an ask
461
+ * reaching here with neither was raised with neither: a real question.
462
+ * - `blocking` is the asker saying THIS one must wake a human — the
463
+ * irreversible, the outward-facing, the ones that spend money.
464
+ */
465
+ export function autoRefusal(ask) {
466
+ if (ask.blocking === true) return 'raised with --blocking: it must wake you';
467
+ const text = ask.recommendation ?? ask.default;
468
+ if (typeof text !== 'string' || text.trim() === '') return 'no recommendation and no default was recorded';
469
+ return null;
470
+ }
471
+
472
+ /**
473
+ * The verdict `unattended.mode: on` takes on one ask, or null if it may not.
474
+ *
475
+ * `prefer` is `unattended.answer` from the config: `recommendation` (the
476
+ * default) takes the agent's own advice, `default` takes the conservative
477
+ * fallback. They are usually the same string now that `raiseAsk` derives one
478
+ * from the other; they differ exactly when the asker deliberately wrote both.
479
+ */
480
+ export function autoVerdict(ask, prefer = 'recommendation') {
481
+ if (autoRefusal(ask) !== null) return null;
482
+ const first = prefer === 'default' ? ask.default : ask.recommendation;
483
+ const text = typeof first === 'string' && first.trim() !== '' ? first : (ask.default ?? ask.recommendation);
484
+ return { mode: 'unattended', text: String(text) };
485
+ }
486
+
487
+ /**
488
+ * Answer every open ask that may be answered without a human, and say what was
489
+ * left alone.
490
+ *
491
+ * Uses `answerOne` unchanged — same journal lock, same re-check that the ask
492
+ * is still open, same decision-before-gate ordering. An auto-answer is an
493
+ * ordinary answer with a different signature on it, not a second write path.
494
+ */
495
+ export function autoAnswer(tyranDir, { prefer = 'recommendation' } = {}) {
496
+ const { asks, errors } = openAsks(tyranDir);
497
+ const { answerable, unanswerable } = partitionAsks(asks);
498
+ const answered = [];
499
+ const left = [];
500
+ const touched = new Map();
501
+ for (const ask of answerable) {
502
+ const verdict = autoVerdict(ask, prefer);
503
+ if (verdict === null) {
504
+ left.push({ ask, why: autoRefusal(ask) });
505
+ continue;
506
+ }
507
+ const outcome = answerOne(ask, verdict);
508
+ if (outcome.skipped !== undefined) {
509
+ left.push({ ask, why: outcome.skipped });
510
+ continue;
511
+ }
512
+ answered.push({ ask, verdict, decision: outcome.decision });
513
+ touched.set(ask.init, ask.journal);
514
+ }
515
+ if (touched.size > 0) reRender(tyranDir, touched);
516
+ for (const u of unanswerable) left.push({ ask: u.ask, why: u.why });
517
+ return { answered, left, errors };
518
+ }
519
+
427
520
  /** The sheet's blocks, matched against the journal's open asks. Every
428
521
  * mismatch is collected, so one run names every problem at once. */
429
522
  function resolveBlocks(blocks, asks, initNames) {
@@ -762,7 +855,8 @@ export function parseArgs(argv) {
762
855
 
763
856
  const USAGE =
764
857
  'usage: answer.mjs render [--dir <.tyran>] [--force]\n' +
765
- ' answer.mjs apply [--dir <.tyran>] [--dry-run] [--resume]';
858
+ ' answer.mjs apply [--dir <.tyran>] [--dry-run] [--resume]\n' +
859
+ ' answer.mjs auto [--dir <.tyran>] [--dry-run] # unattended.mode: on — take the recommendation';
766
860
 
767
861
  /**
768
862
  * Answers already typed into the sheet on disk, for asks that are STILL OPEN.
@@ -871,6 +965,55 @@ function doApply(tyranDir, sheetPath, flags) {
871
965
  }
872
966
  }
873
967
 
968
+ /**
969
+ * This repo's config, or null. `tyranDir` IS the `.tyran` directory, so the
970
+ * config sits directly inside it rather than under a repo root.
971
+ *
972
+ * Never throws: an unreadable or unparseable config means the unattended
973
+ * switch is not on, which is the safe reading of "I cannot tell".
974
+ */
975
+ function readConfig(tyranDir) {
976
+ try {
977
+ return parse(readFileSync(join(tyranDir, 'config.yaml'), 'utf8'));
978
+ } catch {
979
+ return null;
980
+ }
981
+ }
982
+
983
+ /**
984
+ * `auto` — the unattended sweep.
985
+ *
986
+ * REFUSES unless the repo has opted in. A command that answers the operator's
987
+ * questions on their behalf must not be runnable by accident, and `--dir` is
988
+ * the only thing standing between this and somebody else's repository.
989
+ */
990
+ function doAuto(tyranDir, flags) {
991
+ const unattended = unattendedOf(readConfig(tyranDir));
992
+ if (unattended.mode !== 'on') {
993
+ console.error(
994
+ 'answer: unattended.mode is not "on" in .tyran/config.yaml — refusing to answer your questions for you.\n' +
995
+ ' set unattended:\n mode: on\n to have open asks take their own recommendation while you sleep.',
996
+ );
997
+ process.exit(1);
998
+ }
999
+ if (flags['dry-run'] === true) {
1000
+ const { asks } = openAsks(tyranDir);
1001
+ const { answerable } = partitionAsks(asks);
1002
+ for (const ask of answerable) {
1003
+ const why = autoRefusal(ask);
1004
+ const verdict = autoVerdict(ask, unattended.answer);
1005
+ console.log(why === null ? `${ask.init}/${ask.kind} -> ${excerpt(verdict.text)}` : `${ask.init}/${ask.kind} -> LEFT OPEN (${why})`);
1006
+ }
1007
+ console.log(`answer: ${answerable.length} open · dry run, nothing written`);
1008
+ return;
1009
+ }
1010
+ const result = autoAnswer(tyranDir, { prefer: unattended.answer });
1011
+ for (const a of result.answered) console.log(`answer: ${a.ask.init}/${a.ask.kind} auto-accepted -> ${excerpt(a.verdict.text)} (decision ${a.decision})`);
1012
+ for (const l of result.left) console.log(`answer: ${l.ask.init}/${l.ask.kind} LEFT OPEN — ${l.why}`);
1013
+ console.log(`answer: ${result.answered.length} auto-accepted · ${result.left.length} left for you`);
1014
+ for (const e of result.errors ?? []) console.error(`answer: ${e}`);
1015
+ }
1016
+
874
1017
  function main() {
875
1018
  if (wantsHelp(process.argv.slice(2))) {
876
1019
  console.log(USAGE);
@@ -890,6 +1033,7 @@ function main() {
890
1033
  if (!existsSync(tyranDir)) throw new IOError(`no such directory ${tyranDir}`);
891
1034
  if (parsed.verb === 'render') return doRender(tyranDir, sheetPath, parsed.flags);
892
1035
  if (parsed.verb === 'apply') return doApply(tyranDir, sheetPath, parsed.flags);
1036
+ if (parsed.verb === 'auto') return doAuto(tyranDir, parsed.flags);
893
1037
  // A verb-less invocation NEVER guesses. This command writes to the ledger,
894
1038
  // and an invocation that sometimes writes and sometimes does not is what a
895
1039
  // tired operator gets wrong at 23:00.
package/scripts/board.mjs CHANGED
@@ -52,9 +52,11 @@ import { escapeInvisible, jsonEscapeInvisible } from './invisible.mjs';
52
52
  import { renderBoardError, renderBoardHtml } from './board-html.mjs';
53
53
  import { COST_SCHEMA, WINDOWS, costJson, costReport } from './cost.mjs';
54
54
  import { SettingsError, applyPolicyClass, applySetting, readSettings } from './settings.mjs';
55
+ import { unattendedOf } from './schema.mjs';
56
+ import { parse as parseYaml } from './yaml-lite.mjs';
55
57
  import { checkStopAt } from './stop-check.mjs';
56
- import { runState } from './overnight.mjs';
57
- import { answerOne, answerProblem, classify, openAsks, partitionAsks, reRender, sortAsks } from './answer.mjs';
58
+ import { limitSweep, runState } from './overnight.mjs';
59
+ import { answerOne, answerProblem, autoAnswer, classify, openAsks, partitionAsks, readConductor, reRender, resumePlan, sortAsks } from './answer.mjs';
58
60
  import { wantsHelp } from './cli-args.mjs';
59
61
  import {
60
62
  HEALTH_ROUTE,
@@ -695,6 +697,94 @@ const sendJson = (res, status, body) => {
695
697
  res.end(JSON.stringify(body) + '\n');
696
698
  };
697
699
 
700
+ /** This repo's config, or null. Never throws: a served page must not 500 on
701
+ * a config that does not parse — every caller has a safe default. */
702
+ function configOf(dir) {
703
+ try {
704
+ return parseYaml(readFileSync(join(dir, 'config.yaml'), 'utf8'));
705
+ } catch {
706
+ return null;
707
+ }
708
+ }
709
+
710
+ const unattendedFor = (dir) => unattendedOf(configOf(dir));
711
+
712
+ /**
713
+ * Wake the conductor on the session the answer belongs to.
714
+ *
715
+ * Detached and unwatched on purpose: this is a web request handler, and the
716
+ * session it starts outlives the response by hours.
717
+ */
718
+ function spawnResume(dir, sessionId) {
719
+ try {
720
+ const child = spawnProcess(
721
+ 'claude',
722
+ ['--resume', sessionId, 'Answers landed while you were away — read the journal and carry on.'],
723
+ { cwd: resolve(dir, '..'), detached: true, stdio: 'ignore', shell: false },
724
+ );
725
+ child.on?.('error', (err) => console.error(`board: could not resume ${sessionId}: ${err.message}`));
726
+ child.unref?.();
727
+ console.log(`board: resumed session ${sessionId} (pid ${child.pid ?? '?'})`);
728
+ } catch (err) {
729
+ console.error(`board: could not resume ${sessionId}: ${String(err?.message ?? err)}`);
730
+ }
731
+ }
732
+
733
+ /**
734
+ * The unattended heartbeat, run by the served board because it is the one
735
+ * long-lived process a repo already has.
736
+ *
737
+ * Two jobs, both of which need something awake AFTER the session that was
738
+ * working has died:
739
+ *
740
+ * 1. the usage wall. The conductor's own request is the one the platform
741
+ * rejects, so it cannot write its checkpoint or arm its own resume.
742
+ * 2. the question queue. An ask raised at 02:00 has nobody to sweep it, and
743
+ * `unattended.mode: on` is the operator saying it should not wait.
744
+ *
745
+ * Best-effort throughout: this runs on a timer inside a server whose actual
746
+ * job is to render a page, and nothing here is worth a 500 or an exit.
747
+ */
748
+ export function unattendedTick(dir, { sweep = limitSweep, auto = autoAnswer, schedule = scheduleResume } = {}) {
749
+ const repo = resolve(dir, '..');
750
+ try {
751
+ const wall = sweep(repo);
752
+ if (wall.action === 'paused') {
753
+ console.log(`board: usage wall on the ${wall.marker.window} window — resuming ${wall.marker.resume_at}`);
754
+ schedule(repo);
755
+ }
756
+ } catch (err) {
757
+ console.error(`board: usage watch failed: ${String(err?.message ?? err)}`);
758
+ }
759
+ try {
760
+ const unattended = unattendedFor(dir);
761
+ if (unattended.mode !== 'on') return;
762
+ // Line 603 spells it the same way: `checkStopAt` takes the FILE, and
763
+ // handing it the directory is a brake that silently never engages.
764
+ if (checkStopAt(join(dir, 'STOP')).stopped) return;
765
+ const result = auto(dir, { prefer: unattended.answer });
766
+ for (const a of result.answered) {
767
+ console.log(`board: ${a.ask.init}/${a.ask.kind} auto-accepted (unattended) -> decision ${a.decision}`);
768
+ }
769
+ } catch (err) {
770
+ console.error(`board: unattended sweep failed: ${String(err?.message ?? err)}`);
771
+ }
772
+ }
773
+
774
+ /** Arm the resume through overnight.mjs's own CLI, so the hold policy, the
775
+ * keep-awake warning and the babysitting ladder are the ones the operator
776
+ * already has rather than a second implementation inside a web server. */
777
+ function scheduleResume(repo) {
778
+ const script = new URL('./overnight.mjs', import.meta.url).pathname;
779
+ const child = spawnProcess(process.execPath, [script, 'schedule', '--dir', repo], {
780
+ detached: true,
781
+ stdio: 'ignore',
782
+ shell: false,
783
+ });
784
+ child.on?.('error', (err) => console.error(`board: could not arm the resume: ${err.message}`));
785
+ child.unref?.();
786
+ }
787
+
698
788
  /**
699
789
  * Answer one open question, from the page instead of from a terminal.
700
790
  *
@@ -733,7 +823,29 @@ function handleAnswer(dir, body) {
733
823
  // already correct.
734
824
  reRender(dir, new Map([[ask.init, ask.journal]]));
735
825
  console.log(`board: answered ${ask.init}/${ask.kind} (${verdict.mode}) -> decision ${outcome.decision}`);
736
- return { ok: true, kind: ask.kind, init: ask.init, mode: verdict.mode, decision: outcome.decision, recorded: verdict.text };
826
+
827
+ // AN ANSWER NOBODY IS LISTENING FOR. The terminal path has offered to wake
828
+ // the conductor since answers existed; this one re-rendered the page and
829
+ // returned, so an operator who answered here at 23:00 had their ruling sit
830
+ // in the ledger until they happened to start a session. Measured on a real
831
+ // queue: a question answered in the morning, and the initiative it unblocked
832
+ // still parked that evening.
833
+ //
834
+ // The plan is REPORTED rather than acted on, except under `unattended.mode:
835
+ // on` where the operator has already said "keep going without me". Two
836
+ // conductors on one journal is a hazard this repo has paid for once, and
837
+ // `resumePlan` is the function that knows the difference.
838
+ const plan = resumePlan(readConductor(dir), { resume: unattendedFor(dir).mode === 'on' });
839
+ if (plan.action === 'spawn') spawnResume(dir, plan.sessionId);
840
+ return {
841
+ ok: true,
842
+ kind: ask.kind,
843
+ init: ask.init,
844
+ mode: verdict.mode,
845
+ decision: outcome.decision,
846
+ recorded: verdict.text,
847
+ resume: plan.action,
848
+ };
737
849
  }
738
850
 
739
851
  /**
@@ -1167,6 +1279,13 @@ function main() {
1167
1279
  clear();
1168
1280
  process.exit(0);
1169
1281
  }
1282
+ // The one long-lived process a repo already has. The usage wall and the
1283
+ // unattended queue both need something awake AFTER the session that was
1284
+ // working is gone — the conductor's own request is the one the wall
1285
+ // rejects, so it cannot arm its own resume, and a question raised at
1286
+ // 02:00 has nobody to sweep it. Neither costs anything when its feature
1287
+ // is off: both read the config first and return.
1288
+ unattendedTick(dir);
1170
1289
  }, DIR_WATCHDOG_MS);
1171
1290
  // Unref'd so it is the SERVER that keeps this process alive, never the
1172
1291
  // timer: a watchdog that held the loop open would turn every exit path
package/scripts/cost.mjs CHANGED
@@ -48,6 +48,7 @@ import { pricingOf, PRICING_RATE_KEYS } from './schema.mjs';
48
48
  import { defaultRateCard, RATE_CARD_ID, planOfTier, PLAN_LABELS, SUBSCRIPTION_USD, periodStart } from './pricing.mjs';
49
49
  import { jsonEscapeInvisible } from './invisible.mjs';
50
50
  import { wantsHelp } from './cli-args.mjs';
51
+ import { projectSlug } from './usage-transcript.mjs';
51
52
 
52
53
  export const COST_FILE = 'cost.json';
53
54
 
@@ -410,7 +411,11 @@ export function transcriptDirFor(repoRoot, projectsRoot) {
410
411
  }
411
412
 
412
413
  function findTranscriptDir(want, projectsRoot) {
413
- const direct = join(projectsRoot, want.split(sep).join('-'));
414
+ // The platform's own naming rule, spelled once in `usage-transcript.mjs`
415
+ // because the usage gate needs it on a path where loading THIS module would
416
+ // be too expensive. What is left here is the scan below, which only this
417
+ // report needs.
418
+ const direct = join(projectsRoot, projectSlug(want));
414
419
  if (existsSync(direct)) return direct;
415
420
  if (!existsSync(projectsRoot)) return null;
416
421
  for (const entry of readdirSync(projectsRoot, { withFileTypes: true })) {