@jjanczur/tyran 0.1.44 → 0.1.46

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.44",
14
+ "version": "0.1.46",
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.44",
3
+ "version": "0.1.46",
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,132 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.46 — 2026-08-22
4
+
5
+ ### The wall is readable, and a question no longer costs a night
6
+
7
+ Two failures were losing whole nights on a real install, and neither was
8
+ visible while it happened.
9
+
10
+ **The pause could never fire.** A repo configured `limits: mode: pause,
11
+ pause_at_percent: 99` drove into the account wall at full speed on three
12
+ separate nights. Both telemetry channels are dark on Claude Code 2.1.197: the
13
+ statusline payload carries no `rate_limits` block — no `usage.json` had ever
14
+ been written in ANY repo on that machine — and `cachedUsageUtilization` is not
15
+ a key of `~/.claude.json` at all. The gate fails open on absent telemetry, by
16
+ design, so nothing said so.
17
+
18
+ The signal exists, and it is the wall itself. Every rejected request lands in
19
+ the session transcript as an assistant record carrying `quotaLimits: {status:
20
+ "rejected", rateLimitType, resetsAt}` — 45 of them across one machine's
21
+ projects, including in `subagents/*.jsonl`, which is the seam this project had
22
+ written off as needing a platform signal it did not have. `usage-transcript.mjs`
23
+ reads it as a third channel, after the two percentage sources, because it is
24
+ exact and LATE: it reports 100% of a window already spent, so it restores the
25
+ clean wind-down and the scheduled resume rather than the early stop.
26
+
27
+ The correctness rule is not "resetsAt is ahead of us". Measured: a weekly
28
+ rejection carrying a reset five days out is followed by 565 successful
29
+ assistant messages in the same file, because an allowance can be topped up.
30
+ Acting on the reset alone would have held a working machine until the
31
+ following Friday — a worse failure than the one being fixed, since a false
32
+ pause burns the night the pause was meant to save. So a rejection counts only
33
+ while nothing newer shows a named model answering, reconciled on one timeline
34
+ across a session and its agents.
35
+
36
+ **Nothing resumed, because nothing was awake to.** After a five-hour wall the
37
+ conductor's own request is the one rejected, so it cannot checkpoint, cannot
38
+ run the wind-down and cannot arm a resume. Measured on this machine: walled at
39
+ 19:25 with the window resetting at 20:00, first real answer at 20:30 — half an
40
+ hour lost because the reset was nobody's job. `overnight.mjs watch-limit` and
41
+ the served board's own timer now do that job, handing off to the existing
42
+ `schedule` so the hold policy, the weekly deferral and the babysitting ladder
43
+ are the ones already there.
44
+
45
+ ### Unattended delivery — the default that finally ships itself
46
+
47
+ An open ask has **no timeout, no expiry and no auto-apply** anywhere in Tyran.
48
+ It sits `WAITING_ON_OPERATOR` forever; doctor turns info into warning after 72
49
+ hours of journal time and that is the whole consequence. The ask protocol has
50
+ said "record a `default` — what ships if nobody ever answers" since it was
51
+ written, and nothing ever took one: it fired when a human clicked **Take the
52
+ default**, at which point somebody was awake and the promise was moot.
53
+
54
+ `unattended: mode: on` closes an ask with its own recommendation the moment it
55
+ is raised, and the run keeps going. Two refusals are mechanical: an ask with
56
+ no recommendation and no default is a real question, and an ask raised
57
+ `--blocking` is its author saying this one must wake you. `.tyran/STOP` still
58
+ outranks both. Everything taken is journalled as `answer_mode: unattended`
59
+ with its decision text prefixed `(auto-accepted overnight)` — an auto-ruling
60
+ that looked like the operator's own would be the failure this is judged by.
61
+
62
+ A recommendation now becomes the `default` at the mint when no other is given.
63
+ The two fields stay distinct, but an ask recording only an opinion rendered as
64
+ `blocking · no safe default` and stopped the queue on a question its own
65
+ author had answered.
66
+
67
+ ### Smaller, and each one a silence
68
+
69
+ - **Answering on the board never woke the conductor.** The terminal path has
70
+ offered to since answers existed; `POST /answer` re-rendered the page and
71
+ returned, so a ruling made at 23:00 sat until a session happened to start.
72
+ - **`limit-near`** — `warn` promised to surface and never did. The gate
73
+ returns PASS ("surfacing is doctor's job") and doctor compared no percentage
74
+ to any threshold, so `warn` differed from `off` in nothing visible.
75
+ - **`limit-watcher-absent`** — a pause in force with no watcher beside it.
76
+ `limit-pause-stale` fires only once `resume_at` has already passed.
77
+ - **`limit-statusline-stale`** — a statusline pinned to a plugin-cache version
78
+ that is no longer running. A cache is not an archive; when it is pruned the
79
+ telemetry stops with no symptom but a pause that never fires.
80
+ - Two findings recorded rather than papered over: `SESSION_ID_RE` admits
81
+ `--dangerous`, so the watcher's filename-sourced id uses a stricter pattern;
82
+ and both marker writers throw on `resets_at: undefined`, unreachable and
83
+ left shared because a guard on one side is a silent divergence.
84
+
85
+ ## 0.1.45 — 2026-08-22
86
+
87
+ ### The review reads data access and structure, and the self-review has criteria
88
+
89
+ `code-review` gained two dimensions. **Data access and wasted work**: the
90
+ round trips one request makes and how the count moves with the rows — a query
91
+ inside a loop or an awaited per-item `map` is 1 + N, awaits with no dependency
92
+ between them run together with the fan-out bounded, the same pure computation
93
+ runs once per request, and a cache comes AFTER those, never instead of them,
94
+ with the diff saying what invalidates it and why the TTL is that number. None
95
+ of it shows in the diff alone, so the rule is to follow the new call up to the
96
+ request that triggers it, and the finding is a count — "N+1 queries for N rows,
97
+ expected 1" — which is what lets it pin as a test. **Structure**: a
98
+ thousand-line file is built one reasonable addition at a time, so the question
99
+ is whether THIS addition gives a module a second reason to change; the
100
+ counterweight is `deslop`'s own — a layer or helper introduced for one caller
101
+ is the opposite failure, not the cure — and a giant the story merely touched is
102
+ a `NOTES.md` debt, not an in-story refactor.
103
+
104
+ Reported from the operator's own repos: the implementer and reviewer shipped
105
+ N+1 queries, serial awaits over independent calls, repeated queries that could
106
+ have been one, and caches with no stated reason for their TTL, often enough
107
+ that the same eight-point checklist was being pasted into every handoff by
108
+ hand. The checklist now lives in one place — the skill the reviewer already
109
+ loads — and nowhere else.
110
+
111
+ The implementer's "self-review of your own diff" had no criteria: it named no
112
+ skill and listed no dimension. It is now the `code-review` skill run on
113
+ yourself, loaded rather than recalled, with data access called out as the
114
+ dimension an author misses most, because each call site looked fine where it
115
+ was written. For work that reads or writes data the short plan states the
116
+ round trips one request will cost. `deslop` says in one sentence that a slow
117
+ data path is not its business — it deletes, and the fix for a query in a loop
118
+ adds lines — so "the optimization pass" can no longer be read as the
119
+ performance pass. A test pins the pointer and the N+1 clause, because 0.1.40
120
+ is exactly the kind of edit that drops a cross-reference.
121
+
122
+ Not added: a performance-audit skill. The operator's four-phase audit — recon,
123
+ a false-positive pass, a report split by what is safe to fix without asking,
124
+ iterative implementation — is the shape of an initiative under `/tyran:run`:
125
+ scout, plan, implementer, reviewer, with the policy classes deciding what needs
126
+ a human. A skill nothing asks for by name is a library entry, and every
127
+ description is paid for by every session. Skill descriptions: 3868 → 3947 of
128
+ 5000.
129
+
3
130
  ## 0.1.44 — 2026-08-19
4
131
 
5
132
  ### The board follows your OS, and finally has a light mode
package/README.md CHANGED
@@ -325,11 +325,11 @@ branch), `tyran:reviewer` (may fix what it finds, but editing forfeits
325
325
  suite on the cheapest tier, reports raw counts, never fixes), `tyran:retro`. A skill is admitted only when something already asks
326
326
  for the protocol by name, and every description is loaded into every session
327
327
  whether the skill fires or not — so the combined length is capped and CI
328
- enforces the cap (3868 of 5000 characters). What each one assumes, when it
328
+ 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: 1658 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
 
@@ -54,6 +54,14 @@ commits and anything written to disk are in English.**
54
54
  optimization pass recorded in the story file (`deslop` — it deletes rather
55
55
  than adds, and it needs a test that ran BEFORE your edit), repo validation,
56
56
  then commits, push and PR on the story branch.
57
+ - **The self-review is the `code-review` skill run on yourself** — load it
58
+ with the `Skill` tool; a checklist recalled from memory is the one you
59
+ already failed to apply while writing. The dimension an author misses
60
+ most is data access: each call site looked fine where you wrote it, and
61
+ the loop that multiplies it is in a file you did not open, so follow your
62
+ new call up to the request. For work that reads or writes data, the
63
+ short plan states the round trips one request will cost — a number
64
+ written down before the code is the cheapest one you will ever fix.
57
65
  - When a test fails for a reason you cannot explain, **stop patching and
58
66
  follow `root-cause`**. Reproduce it, change one variable at a time with
59
67
  the prediction written down first, and name the mechanism. A fix for a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.44",
3
+ "version": "0.1.46",
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.
@@ -2269,7 +2269,15 @@ if (data.schema !== 1) {
2269
2269
  (run.paused.used_percentage === null ? 'the threshold' : run.paused.used_percentage + '%') +
2270
2270
  '. Resumes ' + (run.paused.wait || 'later') + '.');
2271
2271
  }
2272
- if (run.watcher && run.watcher.alive === false) {
2272
+ // A dead watcher is only news while something is waiting to be
2273
+ // resumed. resume.json outlives its own cancellation — overnight
2274
+ // cancel writes state 'cancelled' rather than deleting the file —
2275
+ // so alive:false with no pause marker and no 'waiting' claim is a
2276
+ // leftover, not a failure. Measured 2026-08-19 on a live board: the
2277
+ // banner burned on a watcher cancelled the previous day, on a repo
2278
+ // with overnight mode off and nothing paused at all.
2279
+ var watcherMatters = run.paused !== null || (run.watcher && run.watcher.state === 'waiting');
2280
+ if (watcherMatters && run.watcher && run.watcher.alive === false) {
2273
2281
  lines.push('The resume watcher is not running, so nothing will restart this by itself.');
2274
2282
  }
2275
2283
  if (run.usage && run.usage.stale === true) {
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 })) {