@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.
@@ -43,6 +43,8 @@ import {
43
43
  BOUNDARY_VALUES,
44
44
  LIMITS_LONG_WAIT,
45
45
  LIMITS_MODES,
46
+ UNATTENDED_ANSWER,
47
+ UNATTENDED_MODES,
46
48
  MANDATORY_KERNEL_PATHS,
47
49
  PROFILES,
48
50
  TIER_KEYS,
@@ -312,7 +314,7 @@ export const GROUPS = Object.freeze([
312
314
  id: 'overnight',
313
315
  title: 'Overnight mode',
314
316
  blurb:
315
- 'Pause near the subscription usage limit and resume after the window resets. Needs the statusline helper installed — it is the only place the platform reports usage, and without it this whole section is inert and doctor says so.',
317
+ 'Pause near the subscription usage limit and resume after the window resets. Usage is read from the statusline helper if you installed one, otherwise from the platform’s own cache, otherwise from the wall itself once it is hit — that last one cannot stop you early, but it still winds work down cleanly and schedules the restart. Doctor says so when none of the three can see anything.',
316
318
  settings: [
317
319
  {
318
320
  id: 'limits.mode',
@@ -419,6 +421,44 @@ export const GROUPS = Object.freeze([
419
421
  },
420
422
  ],
421
423
  },
424
+ {
425
+ id: 'unattended',
426
+ title: 'Unattended delivery',
427
+ blurb:
428
+ 'What an open question does when nobody is awake to read it. Off, it waits for you — forever, which is the honest word for it. On, the agent takes its own recommendation and the run keeps going, except for questions raised as blocking and questions nobody wrote a recommendation for.',
429
+ settings: [
430
+ {
431
+ id: 'unattended.mode',
432
+ path: ['unattended', 'mode'],
433
+ label: 'Mode',
434
+ ...choice(UNATTENDED_MODES, {
435
+ off: 'Every question waits for you. Work that depends on it waits too.',
436
+ on: 'Questions are answered by their own recommendation as they are raised.',
437
+ }),
438
+ help: 'Whether a question raised while you are asleep gets answered without you.',
439
+ explain: {
440
+ what: 'Whether Tyran rules on its own questions when there is nobody to ask.',
441
+ changes: 'On, an ask carrying a recommendation is closed the moment it is raised, journalled as `answer_mode: unattended` and prefixed `(auto-accepted overnight)` in the decision stream. Asks raised as blocking, and asks with no recommendation at all, still wait for you.',
442
+ effect: 'The difference between waking to shipped work and waking to a queue of four questions and an initiative that stopped at the first one.',
443
+ },
444
+ },
445
+ {
446
+ id: 'unattended.answer',
447
+ path: ['unattended', 'answer'],
448
+ label: 'Take',
449
+ ...choice(UNATTENDED_ANSWER, {
450
+ recommendation: 'The agent’s own advice — what it would do if it were deciding.',
451
+ default: 'The conservative fallback it recorded alongside the advice.',
452
+ }),
453
+ help: 'Which of the two recorded answers is taken when nobody rules.',
454
+ explain: {
455
+ what: 'Which recorded value an unattended answer uses.',
456
+ changes: 'Recommendation takes the agent’s advice; default takes the safe fallback, which is usually some form of "change nothing yet".',
457
+ effect: 'The two are the same string unless the asker deliberately wrote both — and where they differ, `default` is the setting that keeps an overnight run from shipping anything.',
458
+ },
459
+ },
460
+ ],
461
+ },
422
462
  ]);
423
463
 
424
464
  const BY_ID = new Map(GROUPS.flatMap((g) => g.settings.map((s) => [s.id, s])));
@@ -0,0 +1,108 @@
1
+ /**
2
+ * usage-marker — the pause document, and who is allowed to write one.
3
+ *
4
+ * `.tyran/state/paused-until.json` says a run stopped at the subscription wall
5
+ * and when it may start again. Everything downstream reads it: the scheduler
6
+ * arms the resume from `resume_at`, the board's run panel renders it,
7
+ * `session-start` reports it, doctor ages it, and the gate itself self-heals
8
+ * an expired one.
9
+ *
10
+ * IT HAS TWO WRITERS, and that is the fact this module exists for.
11
+ *
12
+ * - `hooks/scripts/usage-gate.mjs`, when a session is still alive to be
13
+ * refused. It sees the wall on the next tool call and prints the wind-down.
14
+ * - `overnight.mjs watch-limit`, when NOTHING is alive. After a five-hour
15
+ * wall the conductor cannot call the model either, so it cannot write its
16
+ * own checkpoint, cannot run the wind-down, and cannot arm a resume. That
17
+ * is the state a real overnight run was found in: walled at 19:25, and
18
+ * still walled at 20:30 because the reset at 20:00 was nobody's job.
19
+ *
20
+ * WHY THE SHAPE IS SPELLED HERE AND NOT IMPORTED FROM THE GATE. `hooks/**` is
21
+ * KERNEL: it is edited by a human, by hand, outside an agent session, because
22
+ * it is the mechanism every other boundary rests on. A `scripts/` module that
23
+ * imported it would invert the dependency — the hooks import scripts, never
24
+ * the reverse — and would drag the whole gate stack into a background watcher
25
+ * and into the board server.
26
+ *
27
+ * So the document is built here, and `tests/unit/usage-marker.test.mjs` pins
28
+ * this function EQUAL to the gate's `markerOf` across a matrix of inputs. That
29
+ * is ADR-21 satisfied by a mechanical check rather than by single-sourcing,
30
+ * which the KERNEL boundary forbids from inside a session. When the gate is
31
+ * next edited by hand, the body of its `markerOf` should be replaced by a call
32
+ * to this one; the equality test is what makes that a safe edit rather than a
33
+ * hopeful one, and it fails loudly the moment the two drift.
34
+ */
35
+ import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
36
+ import { join } from 'node:path';
37
+
38
+ export const MARKER_RELPATH = join('.tyran', 'state', 'paused-until.json');
39
+
40
+ export const SESSION_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
41
+
42
+ /**
43
+ * The pause document. Pure: every input is an argument, so two writers with
44
+ * the same reading produce the same file.
45
+ *
46
+ * `tripped` is `{window, used_percentage, resets_at, lower_bound}` — the shape
47
+ * `trippedWindow` returns, whichever telemetry channel produced it.
48
+ */
49
+ export function pauseMarker(tripped, limits, nowMs, sessionId, init) {
50
+ // `!== null`, not a truthiness or an `undefined` guard, because the gate's
51
+ // `markerOf` spells it exactly this way and the two are pinned equal. The
52
+ // shape that reaches either — `trippedWindow`'s output — always spells
53
+ // "unknown" as null, so the difference is unreachable rather than tolerated.
54
+ // A caller passing `undefined` would produce `new Date(NaN)` and throw; the
55
+ // equality test records that as a latent both writers share, to be fixed on
56
+ // the same day the KERNEL half can be edited by hand.
57
+ const resetsMs = tripped.resets_at !== null ? tripped.resets_at * 1000 : null;
58
+ // No resets_at from the platform: the window is known-exhausted but the
59
+ // reset time is unknown. A null resume_at would be a marker nothing can
60
+ // self-heal — a permanent false pause — so bound it at wait_max_hours from
61
+ // now instead: the pause still protects the remainder, and the marker
62
+ // expires on its own even if every watcher dies.
63
+ const resumeAtMs =
64
+ resetsMs !== null ? resetsMs + limits.resume_margin_minutes * 60 * 1000 : nowMs + limits.wait_max_hours * 3600 * 1000;
65
+ const waitMs = resumeAtMs - nowMs;
66
+ const longWait = waitMs > limits.wait_max_hours * 3600 * 1000;
67
+ return {
68
+ paused_at: new Date(nowMs).toISOString(),
69
+ window: tripped.window,
70
+ used_percentage: tripped.used_percentage,
71
+ resets_at: tripped.resets_at,
72
+ resume_at: new Date(resumeAtMs).toISOString(),
73
+ long_wait: longWait,
74
+ // What the scheduler should DO about a long wait — copied from config at
75
+ // pause time so the decision is auditable next to its inputs.
76
+ long_wait_policy: limits.long_wait,
77
+ session_id: typeof sessionId === 'string' && SESSION_ID_RE.test(sessionId) ? sessionId : null,
78
+ init: init ?? null,
79
+ // WHICH channel said so, and whether the figure was a lower bound. The
80
+ // scheduler must not treat a bound as a measurement when deciding to
81
+ // RESUME: "at least 97%" is a reason to stop and never a reason to start.
82
+ source: tripped.lower_bound === true ? 'claude.json' : 'sidecar',
83
+ lower_bound: tripped.lower_bound === true,
84
+ };
85
+ }
86
+
87
+ /**
88
+ * The same document, with the channel named honestly.
89
+ *
90
+ * The gate's `source` field is derived from `lower_bound` alone, which had
91
+ * only two channels to distinguish. A wall read out of a transcript is not a
92
+ * bound and not the sidecar, and a marker that claims otherwise sends whoever
93
+ * debugs the next stall to the wrong file. Callers that KNOW the channel say
94
+ * so; the two-value derivation stays exactly as it was for callers that do not.
95
+ */
96
+ export function pauseMarkerFrom(tripped, limits, nowMs, sessionId, init, source = null) {
97
+ const marker = pauseMarker(tripped, limits, nowMs, sessionId, init);
98
+ return source === null ? marker : { ...marker, source };
99
+ }
100
+
101
+ /** Atomic create-or-replace: temp in the same directory, then rename. */
102
+ export function writePauseMarker(repoRoot, marker) {
103
+ const dir = join(repoRoot, '.tyran', 'state');
104
+ mkdirSync(dir, { recursive: true });
105
+ const temp = join(dir, `.paused-${process.pid}.tmp`);
106
+ writeFileSync(temp, JSON.stringify(marker, null, 2) + '\n');
107
+ renameSync(temp, join(repoRoot, MARKER_RELPATH));
108
+ }
@@ -16,6 +16,17 @@
16
16
  * with it the one onboarding step no script can perform, since registering a
17
17
  * statusline means writing the operator's own settings file.
18
18
  *
19
+ * AND THEN THAT KEY WENT AWAY TOO. Measured on Claude Code 2.1.197:
20
+ * `cachedUsageUtilization` is not a key of `~/.claude.json` at all, and no
21
+ * percentage is reachable anywhere on the machine. Both channels above are
22
+ * dark, and the account wall was being hit at full speed by runs configured to
23
+ * stop before it. So `readPlatformUsage` gained a third channel — the wall
24
+ * itself, read back out of the session transcript by `usage-transcript.mjs`.
25
+ * It is exact and it is late; what it restores is the wind-down and the
26
+ * scheduled resume, not the early stop. Everything above still applies the
27
+ * moment the platform starts reporting a percentage again, which is why the
28
+ * order in `readPlatformUsage` puts the percentage first.
29
+ *
19
30
  * WHY A STALE READING IS STILL WORTH ACTING ON, which is the whole design.
20
31
  * That cache is refreshed by the platform on its own schedule; measured at 83
21
32
  * minutes old during heavy continuous use. Under the gate's ten-minute
@@ -45,6 +56,7 @@
45
56
  import { readFileSync } from 'node:fs';
46
57
  import { homedir } from 'node:os';
47
58
  import { join } from 'node:path';
59
+ import { readTranscriptRejection } from './usage-transcript.mjs';
48
60
 
49
61
  /**
50
62
  * Where the statusline writes and everything else reads.
@@ -106,7 +118,7 @@ export function windowFrom(node, nowMs) {
106
118
  * budget and a hook process spawn that costs an order of magnitude more. No
107
119
  * caching layer is warranted and none is here.
108
120
  */
109
- export function readPlatformUsage({ home = homedir(), readFile = readFileSync, nowMs = Date.now() } = {}) {
121
+ export function readConfigUsage({ home = homedir(), readFile = readFileSync, nowMs = Date.now() } = {}) {
110
122
  let doc;
111
123
  try {
112
124
  const raw = readFile(join(home, CLAUDE_CONFIG_RELPATH), 'utf8');
@@ -133,3 +145,46 @@ export function readPlatformUsage({ home = homedir(), readFile = readFileSync, n
133
145
  // What the reading cannot support is a RESUME, and the gate is told so.
134
146
  return { written_at: new Date(nowMs).toISOString(), lower_bound: true, source: 'claude.json', ...out };
135
147
  }
148
+
149
+ /**
150
+ * Everything the platform will tell us about this subscription, in the
151
+ * sidecar's shape, or null.
152
+ *
153
+ * TWO CHANNELS, IN THIS ORDER, and the order is the whole point:
154
+ *
155
+ * 1. `~/.claude.json`'s usage cache — a PERCENTAGE, which can cross a
156
+ * threshold BEFORE the window closes. This is the only channel that can
157
+ * stop a run early enough to wind down on its own terms, so it is
158
+ * consulted first and its answer is never second-guessed.
159
+ * 2. the session transcript's `quotaLimits` record — the wall itself, read
160
+ * back after the fact. Exact, and too late to prevent anything.
161
+ *
162
+ * Measured on Claude Code 2.1.197, which is why (2) exists at all: (1)'s key
163
+ * is not present in that file, and neither is the statusline's `rate_limits`
164
+ * block. Both of the percentage channels are dark on this build, so without
165
+ * (2) a repo configured to pause has nothing to pause ON — which is exactly
166
+ * the state a real overnight run was found in, having driven into the wall at
167
+ * full speed and stayed there until a human noticed in the morning.
168
+ *
169
+ * When (1) returns, (2) is not consulted: a percentage below the threshold is
170
+ * a live statement that the window is OPEN, and a stale rejection cannot
171
+ * outrank it.
172
+ */
173
+ export function readPlatformUsage({
174
+ home = homedir(),
175
+ readFile = readFileSync,
176
+ nowMs = Date.now(),
177
+ repoRoot = process.cwd(),
178
+ readTranscript = readTranscriptRejection,
179
+ } = {}) {
180
+ const cached = readConfigUsage({ home, readFile, nowMs });
181
+ if (cached !== null) return cached;
182
+ try {
183
+ return readTranscript({ repoRoot, home, nowMs });
184
+ } catch {
185
+ // Same contract as everything else here: telemetry is consulted, never
186
+ // depended on. A hook that throws over a transcript it was only reading
187
+ // stops the repository's work.
188
+ return null;
189
+ }
190
+ }
@@ -0,0 +1,416 @@
1
+ /**
2
+ * usage-transcript — the account wall, read back out of the session transcript.
3
+ *
4
+ * THE PROBLEM THIS EXISTS FOR, measured rather than supposed. The usage gate
5
+ * needs a subscription figure and has had two channels for one: the statusline
6
+ * sidecar, and `~/.claude.json`'s `cachedUsageUtilization` (see
7
+ * `usage-source.mjs`). On Claude Code 2.1.197 BOTH are empty — the statusline
8
+ * payload carries no `rate_limits` block, and `cachedUsageUtilization` is not
9
+ * a key of that file at all. Measured on a real machine: no `usage.json` had
10
+ * ever been written in ANY repo, and a config carrying `mode: 'pause'` with
11
+ * `pause_at_percent: 99` had never once been able to fire. The gate fails
12
+ * open, so nothing said so; the agents ran into the wall at full speed and the
13
+ * run died there.
14
+ *
15
+ * But the wall itself IS recorded. Every rejected request lands in the session
16
+ * transcript as an `assistant` line with `isApiErrorMessage: true` and:
17
+ *
18
+ * "quotaLimits": {"status":"rejected","resetsAt":1787342400,
19
+ * "rateLimitType":"five_hour", ...}
20
+ *
21
+ * Measured across `~/.claude/projects/**`: 45 such records, `rateLimitType`
22
+ * always one of `five_hour` or `seven_day`, `resetsAt` always epoch SECONDS.
23
+ * It appears in `<session>/subagents/*.jsonl` as well as the session's own
24
+ * file — which closes the seam this project had written off, because the limit
25
+ * usually surfaces inside a subagent's API call where no hook can see it.
26
+ *
27
+ * WHAT THIS SIGNAL IS AND IS NOT. It is exact and it is LATE: there is no
28
+ * record before the wall, only the rejection at it. So this cannot restore the
29
+ * preventive pause — it reports 100% of a window that is already spent. What
30
+ * it buys is the other half, which is the half that was losing whole nights: a
31
+ * `resets_at` precise to the second, from which the marker, the wind-down and
32
+ * the scheduled resume all follow. Unlike the platform cache's reading, this
33
+ * one is not a lower bound — a rejection is not evidence that usage is "at
34
+ * least" anything, it is the window closing — so it is safe to RESUME on.
35
+ *
36
+ * A REJECTION IS NOT PROOF THE WALL IS STILL UP, and this is the correctness
37
+ * rule of the whole module rather than a detail. Measured on this machine: a
38
+ * `seven_day` rejection on 2026-08-22T14:26 carried `resetsAt` of Aug 28 —
39
+ * and 565 successful assistant messages follow it in the same transcript,
40
+ * because a weekly allowance can be topped up, and because a rejection can
41
+ * name a pool the next request does not draw on. Acting on `resetsAt` alone
42
+ * would have paused a session that was working, which is a worse failure than
43
+ * the one this fixes: a false pause burns the night the pause was supposed to
44
+ * save.
45
+ *
46
+ * So a rejection counts only while nothing NEWER shows the model answering.
47
+ * `message.model` carries that: a real answer names a model, and everything
48
+ * the platform generates itself — errors, notices, interruptions — is
49
+ * `<synthetic>`. A later real answer clears every pending rejection.
50
+ *
51
+ * WHY THE READ IS BOUNDED THE WAY IT IS. This runs inside a PreToolUse hook,
52
+ * on every tool call, against a directory that in a busy repo holds 88 session
53
+ * transcripts and their agents, some of them hundreds of megabytes. Reading
54
+ * all of that per tool call is not a telemetry channel, it is an outage. Three
55
+ * bounds, in the order they cut:
56
+ *
57
+ * 1. mtime. A rejection whose reset is still ahead was written at most a
58
+ * weekly window ago, so a file untouched since then cannot hold one.
59
+ * 2. rank. The wall lands in the session that is RUNNING, whose transcript
60
+ * is by construction among the most recently modified. Only the newest
61
+ * few sessions and their agents are opened.
62
+ * 3. the tail. A rejection is at the END of the file it killed. Only the
63
+ * last `TAIL_BYTES` are read, positionally — never the whole file.
64
+ *
65
+ * The third bound is also FREE OF FALSE NEGATIVES, which is why it is safe to
66
+ * be this aggressive: a rejection old enough to have scrolled out of the tail
67
+ * has thousands of lines after it, and a transcript that kept going is one the
68
+ * clearing rule above would have discarded anyway.
69
+ *
70
+ * Measured with these bounds against the busiest repo on this machine: 12
71
+ * files, 34 ms, against the gate's 8-second budget. `tests/unit/
72
+ * usage-transcript.test.mjs` pins the budget rather than describing it.
73
+ *
74
+ * Shape note: like `usage-source.mjs`, this speaks the SIDECAR's language, not
75
+ * the platform's. `resetsAt` becomes `resets_at`, and a closed window becomes
76
+ * `used_percentage: 100` — so the gate has one shape to reason about and its
77
+ * threshold comparison needs no special case for "the wall".
78
+ */
79
+ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from 'node:fs';
80
+ import { homedir } from 'node:os';
81
+ import { basename, join, resolve, sep } from 'node:path';
82
+
83
+ /** The two windows the gate knows about, in the platform's own spelling. */
84
+ export const WINDOW_KEYS = Object.freeze(['five_hour', 'seven_day']);
85
+
86
+ /** Where Claude Code keeps one directory per project, under the home dir. */
87
+ export const PROJECTS_RELPATH = join('.claude', 'projects');
88
+
89
+ /**
90
+ * The platform's directory name for a repo: its absolute path with every
91
+ * separator replaced by a dash, leading separator included.
92
+ *
93
+ * `cost.mjs` resolves the same directory for the spend report and had this
94
+ * rule inline. It lives HERE because the usage gate imports this module on
95
+ * every tool call and must not pay for `cost.mjs` to be loaded — and two
96
+ * spellings of one platform convention is ADR-21's named defect in the place
97
+ * it would be hardest to notice, since nothing fails while they agree.
98
+ */
99
+ export function projectSlug(repoRoot) {
100
+ return resolve(repoRoot).split(sep).join('-');
101
+ }
102
+
103
+ /**
104
+ * Where this repo's transcripts are, or null.
105
+ *
106
+ * Only the direct name. `cost.mjs` additionally SCANS for a directory whose
107
+ * sessions name this repo, because there a miss hides a panel an operator
108
+ * asked for; here a miss means one telemetry channel stays quiet and the gate
109
+ * behaves exactly as it did before this channel existed, which is not worth a
110
+ * directory walk on every tool call.
111
+ */
112
+ export function transcriptDirOf(repoRoot, { home = homedir(), projectsRoot = null, exists = existsSync } = {}) {
113
+ if (typeof repoRoot !== 'string' || repoRoot === '') return null;
114
+ const root = projectsRoot ?? join(home, PROJECTS_RELPATH);
115
+ const dir = join(root, projectSlug(repoRoot));
116
+ return exists(dir) ? dir : null;
117
+ }
118
+
119
+ /** How much of a transcript's END is read. A record is ~1 KB; this is generous. */
120
+ export const TAIL_BYTES = 128 * 1024;
121
+
122
+ /**
123
+ * How far back a transcript can have been touched and still matter. The
124
+ * longest window whose reset can be ahead of us is the weekly one, so a file
125
+ * older than that cannot hold a rejection that is still in force. One extra
126
+ * day for clock skew and a laptop that slept through the boundary.
127
+ */
128
+ export const CANDIDATE_MAX_AGE_MS = 8 * 24 * 3600 * 1000;
129
+
130
+ /** Newest sessions opened per scan; each brings its own agents. */
131
+ export const MAX_SESSIONS = 4;
132
+
133
+ /**
134
+ * A session id safe to hand to `claude --resume <id>` as an argv element.
135
+ *
136
+ * Stricter than the gate's `SESSION_ID_RE` on purpose, in one respect: that
137
+ * pattern allows `-`, including in first position, so `--dangerous` is 11
138
+ * characters of `[A-Za-z0-9_-]` and passes it. There the id comes from the
139
+ * platform's own hook payload; HERE it comes from a FILENAME in a directory
140
+ * this module walks, and a name is a weaker provenance than a payload. An
141
+ * argument that can start a flag never leaves this file.
142
+ */
143
+ export const SAFE_SESSION_ID_RE = /^[A-Za-z0-9_][A-Za-z0-9_-]{7,127}$/;
144
+
145
+ /** Hard ceiling on files opened per scan, agents included. */
146
+ export const MAX_FILES = 12;
147
+
148
+ /** Own-property read on a prototype-free view of foreign JSON. */
149
+ function own(obj, name) {
150
+ return obj !== null && typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, name)
151
+ ? obj[name]
152
+ : undefined;
153
+ }
154
+
155
+ /**
156
+ * One transcript line as a rejection, or null.
157
+ *
158
+ * `nowMs` is what makes a record actionable rather than historical: a
159
+ * rejection whose `resetsAt` has passed is not stale data, it is data about a
160
+ * window that has since REFILLED, and pausing on it would hold a session that
161
+ * has its full allowance. That check is the one that makes everything else
162
+ * here safe, and it is tested directly.
163
+ */
164
+ export function rejectionOf(line, nowMs) {
165
+ // A substring test before JSON.parse. A transcript is overwhelmingly lines
166
+ // that cannot match, and parsing each of them is the entire cost of this
167
+ // module; `quotaLimits` appears on 5 lines of a 5700-line transcript.
168
+ if (line.length === 0 || line.charCodeAt(0) !== 123 /* { */ || !line.includes('"quotaLimits"')) return null;
169
+ let event;
170
+ try {
171
+ event = JSON.parse(line);
172
+ } catch {
173
+ return null;
174
+ }
175
+ const quota = own(event, 'quotaLimits');
176
+ if (own(quota, 'status') !== 'rejected') return null;
177
+ const window = own(quota, 'rateLimitType');
178
+ // An unknown window is not a window this gate has a threshold for. Silently
179
+ // ignoring it is right: the platform may add one, and a hook that throws on
180
+ // an unrecognised string stops the repository's work over telemetry.
181
+ if (typeof window !== 'string' || !WINDOW_KEYS.includes(window)) return null;
182
+ const resets = own(quota, 'resetsAt');
183
+ if (typeof resets !== 'number' || !Number.isFinite(resets)) return null;
184
+ if (resets * 1000 <= nowMs) return null;
185
+ // Required, not optional: the rejection is weighed by ORDERING it against
186
+ // the last real answer, and a record that cannot be placed on that timeline
187
+ // cannot be shown to be current. See `answeredAt`.
188
+ const at = own(event, 'timestamp');
189
+ if (typeof at !== 'string' || at === '') return null;
190
+ return { window, resets_at: resets, at };
191
+ }
192
+
193
+ /**
194
+ * When this line showed a real model answering, or null.
195
+ *
196
+ * The platform writes its own messages into the transcript as `assistant`
197
+ * records too — the wall notice among them — and stamps them `<synthetic>`.
198
+ * Only a named model is evidence that a request went out and came back, which
199
+ * is the one thing that retires a pending rejection.
200
+ *
201
+ * An answer with no timestamp is not usable, because the rule it feeds is an
202
+ * ORDERING against the rejection. Both sides therefore require one, and both
203
+ * sides fail toward "no pause" without it — which is the status quo, and the
204
+ * safe direction for a control that can otherwise halt a working session.
205
+ */
206
+ export function answeredAt(line) {
207
+ if (line.length === 0 || line.charCodeAt(0) !== 123 /* { */ || !line.includes('"assistant"')) return null;
208
+ let event;
209
+ try {
210
+ event = JSON.parse(line);
211
+ } catch {
212
+ return null;
213
+ }
214
+ if (own(event, 'type') !== 'assistant') return null;
215
+ const model = own(own(event, 'message'), 'model');
216
+ if (typeof model !== 'string' || model === '' || model === '<synthetic>') return null;
217
+ const ts = own(event, 'timestamp');
218
+ return typeof ts === 'string' && ts !== '' ? ts : null;
219
+ }
220
+
221
+ /**
222
+ * One block of transcript text, folded to what the caller has to weigh:
223
+ * `{answered_at, rejections: {five_hour?, seven_day?}}`.
224
+ *
225
+ * Rejections are kept per window rather than "the last one seen", because the
226
+ * two are not alternatives: a five-hour wall can follow a weekly one within
227
+ * the same file, and `trippedWindow` gives the weekly precedence for a reason
228
+ * — waiting out the five-hour refill just hits the weekly wall again.
229
+ * Reporting only the newest record would hide the binding constraint behind
230
+ * the recent one.
231
+ *
232
+ * `answered_at` is carried rather than applied here, because the clearing rule
233
+ * is not per file: the wall lands in a SUBAGENT's transcript while its parent
234
+ * session keeps answering in another, and either file read alone gives the
235
+ * wrong verdict. `readTranscriptRejection` reconciles them on one timeline.
236
+ */
237
+ export function scanTail(text, nowMs) {
238
+ const rejections = {};
239
+ let latest = null;
240
+ for (const line of text.split('\n')) {
241
+ const ts = answeredAt(line);
242
+ if (ts !== null) {
243
+ if (latest === null || ts > latest) latest = ts;
244
+ continue;
245
+ }
246
+ const hit = rejectionOf(line, nowMs);
247
+ // Lines are chronological, so a later hit is the fresher reading of that
248
+ // window and simply replaces the earlier one.
249
+ if (hit !== null) rejections[hit.window] = hit;
250
+ }
251
+ return { answered_at: latest, rejections };
252
+ }
253
+
254
+ /**
255
+ * The last `maxBytes` of a file, as complete lines.
256
+ *
257
+ * Positional, so a 200 MB transcript costs the same as a 200 KB one. The first
258
+ * line of a tail read is almost always a fragment of the record that straddles
259
+ * the cut — it is dropped, because a fragment that happens to parse is a
260
+ * reading this module would INVENT. Never throws: an unreadable transcript is
261
+ * one this module has no opinion about.
262
+ */
263
+ export function readTail(path, maxBytes = TAIL_BYTES, io = {}) {
264
+ const { open = openSync, read = readSync, close = closeSync, stat = statSync } = io;
265
+ let fd = null;
266
+ try {
267
+ const size = stat(path).size;
268
+ if (size === 0) return '';
269
+ const want = Math.min(size, maxBytes);
270
+ const start = size - want;
271
+ fd = open(path, 'r');
272
+ const buffer = Buffer.allocUnsafe(want);
273
+ let got = 0;
274
+ while (got < want) {
275
+ const n = read(fd, buffer, got, want - got, start + got);
276
+ if (n === 0) break;
277
+ got += n;
278
+ }
279
+ const text = buffer.subarray(0, got).toString('utf8');
280
+ if (start === 0) return text;
281
+ const nl = text.indexOf('\n');
282
+ return nl === -1 ? '' : text.slice(nl + 1);
283
+ } catch {
284
+ return '';
285
+ } finally {
286
+ if (fd !== null) {
287
+ try {
288
+ close(fd);
289
+ } catch {
290
+ /* a descriptor we could not close is not a reason to fail a read */
291
+ }
292
+ }
293
+ }
294
+ }
295
+
296
+ function mtimeOf(path, stat) {
297
+ try {
298
+ return stat(path).mtimeMs;
299
+ } catch {
300
+ return null;
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Which transcripts are worth opening, newest first: the most recently touched
306
+ * sessions and the agents belonging to them.
307
+ *
308
+ * The three bounds of the header apply here, and the ORDER matters — mtime
309
+ * before rank before tail — because each is cheaper than the next and cuts
310
+ * more.
311
+ */
312
+ export function candidates(transcriptDir, { nowMs = Date.now(), maxAgeMs = CANDIDATE_MAX_AGE_MS, io = {} } = {}) {
313
+ const { readdir = readdirSync, stat = statSync } = io;
314
+ let files;
315
+ try {
316
+ files = readdir(transcriptDir).filter((f) => f.endsWith('.jsonl'));
317
+ } catch {
318
+ return [];
319
+ }
320
+ const sessions = [];
321
+ for (const file of files) {
322
+ const path = join(transcriptDir, file);
323
+ const mtime = mtimeOf(path, stat);
324
+ if (mtime === null || nowMs - mtime > maxAgeMs) continue;
325
+ sessions.push({ path, mtime, session: basename(file, '.jsonl') });
326
+ }
327
+ sessions.sort((a, b) => b.mtime - a.mtime);
328
+
329
+ const out = [];
330
+ for (const session of sessions.slice(0, MAX_SESSIONS)) {
331
+ out.push(session);
332
+ let agents;
333
+ try {
334
+ agents = readdir(join(transcriptDir, session.session, 'subagents')).filter((f) => f.endsWith('.jsonl'));
335
+ } catch {
336
+ continue; // a session with no agents is the common case, not an error
337
+ }
338
+ for (const agent of agents) {
339
+ const path = join(transcriptDir, session.session, 'subagents', agent);
340
+ const mtime = mtimeOf(path, stat);
341
+ if (mtime === null || nowMs - mtime > maxAgeMs) continue;
342
+ out.push({ path, mtime, session: session.session });
343
+ }
344
+ }
345
+ // One more sort so an AGENT that outlived its session's last write is opened
346
+ // before an older session — the wall usually lands in an agent first.
347
+ out.sort((a, b) => b.mtime - a.mtime);
348
+ return out.slice(0, MAX_FILES);
349
+ }
350
+
351
+ /**
352
+ * The account wall as the gate's sidecar document, or null.
353
+ *
354
+ * `repoRoot` decides which project's transcripts are read; the caller inside
355
+ * the hook has no session id to narrow it further, which is why the bounds
356
+ * above do that job instead.
357
+ */
358
+ export function readTranscriptRejection({
359
+ repoRoot = process.cwd(),
360
+ transcriptDir = null,
361
+ home = homedir(),
362
+ projectsRoot = null,
363
+ nowMs = Date.now(),
364
+ maxAgeMs = CANDIDATE_MAX_AGE_MS,
365
+ tailBytes = TAIL_BYTES,
366
+ io = {},
367
+ } = {}) {
368
+ const dir = transcriptDir ?? transcriptDirOf(repoRoot, { home, projectsRoot, ...(io.exists ? { exists: io.exists } : {}) });
369
+ if (typeof dir !== 'string' || dir === '') return null;
370
+
371
+ const found = {};
372
+ const sessionOf = {};
373
+ // ONE timeline across every candidate, which is the whole reason this loop
374
+ // collects before it decides. The wall lands in a subagent's transcript
375
+ // while its parent session keeps answering in another file: read either
376
+ // alone and the verdict is wrong in a different direction each time.
377
+ let lastAnswerAt = null;
378
+ for (const candidate of candidates(dir, { nowMs, maxAgeMs, io })) {
379
+ const { answered_at: seen, rejections } = scanTail(readTail(candidate.path, tailBytes, io), nowMs);
380
+ if (seen !== null && (lastAnswerAt === null || seen > lastAnswerAt)) lastAnswerAt = seen;
381
+ for (const window of WINDOW_KEYS) {
382
+ const hit = rejections[window];
383
+ if (hit === undefined) continue;
384
+ // Across files, the record with the LATEST reset governs: two sessions
385
+ // that hit the same wall report the same reset, and a session that hit
386
+ // it later in the window reports the same one again. A later reset is a
387
+ // later window, and that is the one still in force.
388
+ if (found[window] === undefined || hit.resets_at > found[window].resets_at) {
389
+ found[window] = hit;
390
+ sessionOf[window] = candidate.session;
391
+ }
392
+ }
393
+ }
394
+
395
+ const windows = WINDOW_KEYS.filter(
396
+ (w) => found[w] !== undefined && (lastAnswerAt === null || found[w].at > lastAnswerAt),
397
+ );
398
+ if (windows.length === 0) return null;
399
+
400
+ // The weekly window names the session to resume when both are walled: it is
401
+ // the binding constraint, and its record is the one the scheduler acts on.
402
+ const governing = windows.includes('seven_day') ? 'seven_day' : windows[0];
403
+ const session = sessionOf[governing] ?? null;
404
+ const doc = {
405
+ written_at: new Date(nowMs).toISOString(),
406
+ // NOT a lower bound. The platform cache reports "usage is at least N%",
407
+ // which is a reason to stop and never a reason to start; a rejection is
408
+ // the window closing, with an exact reset. The scheduler may act on it.
409
+ lower_bound: false,
410
+ source: 'transcript',
411
+ session_id: typeof session === 'string' && SAFE_SESSION_ID_RE.test(session) ? session : null,
412
+ rejected_at: found[governing].at,
413
+ };
414
+ for (const window of windows) doc[window] = { used_percentage: 100, resets_at: found[window].resets_at };
415
+ return doc;
416
+ }