@jjanczur/tyran 0.1.9 → 0.1.11

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.
@@ -178,6 +178,37 @@ function list(items) {
178
178
 
179
179
  // ------------------------------------------------------------------ fold
180
180
 
181
+ /** The open blockage this agent reported clears when the agent moves on. */
182
+ function clearBlockageBy(state, agent) {
183
+ state.blockages.delete(String(agent));
184
+ }
185
+
186
+ /** A `review`/`merge` settles the ticket for EVERY agent blocked on it. */
187
+ function clearBlockagesOn(state, ticketId) {
188
+ for (const [key, blockage] of state.blockages) {
189
+ // A ticketless blockage is keyed to its agent and belongs to no ticket —
190
+ // the `(no ticket)` pseudo-ticket of a review/merge without `data.ticket`
191
+ // is a different thing and must not sweep it up.
192
+ if (blockage.ticket != null && String(blockage.ticket) === ticketId) state.blockages.delete(key);
193
+ }
194
+ }
195
+
196
+ /**
197
+ * A `report` — and a `review`, which is the reviewer's completion event —
198
+ * ENDS that agent's stint, so everything still keyed by its name goes with it.
199
+ *
200
+ * ADR-18 permits a later `spawn` to reuse the name once the prior one is
201
+ * closed, and that is the standard close-spawn recovery path, not an exotic
202
+ * journal. Kept, these records render against the NEXT incarnation: a fresh
203
+ * agent that has emitted nothing showed as `blocked at <old ts>` while
204
+ * `## Open blockages` said _none_ — one document contradicting itself. Cleared
205
+ * here, at fold time, so no reader has to compare timestamps of its own.
206
+ */
207
+ function closeAgent(state, agent) {
208
+ clearBlockageBy(state, agent);
209
+ state.progressByAgent.delete(String(agent));
210
+ }
211
+
181
212
  /**
182
213
  * Fold a journal read into the projection state. Pure: no clock, no I/O.
183
214
  * Every closed-set event type must hit a branch here; anything else is
@@ -210,6 +241,25 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
210
241
  milestones: [],
211
242
  unusableAgentNames: [],
212
243
  ambiguousAgents: [],
244
+ // agent name -> latest self-reported signal (last one wins)
245
+ progressByAgent: new Map(),
246
+ // agent name -> that agent's open blockage, the ticket inside the value.
247
+ //
248
+ // Keyed by AGENT and not by ticket, because one agent has at most one live
249
+ // blockage (last-blocked-wins, exactly like its last signal) while one
250
+ // ticket can block SEVERAL agents. Under ticket keys the second agent's
251
+ // record replaced the first's, and the second agent's next movement signal
252
+ // then deleted a blockage its owner had never cleared — so an agent stayed
253
+ // stuck with nothing anywhere saying so. The ticket survives as rendered
254
+ // context and as what `review`/`merge` match against.
255
+ //
256
+ // Cleared by `unblocked`/`started`/`working` from the SAME agent, by that
257
+ // agent's report/review, and by a `review`/`merge` on the ticket — AT FOLD
258
+ // TIME, so no reader needs temporal reasoning of its own.
259
+ blockages: new Map(),
260
+ findings: [],
261
+ // `ticket.status` events naming a ticket no other event mentions
262
+ unknownOverrides: [],
213
263
  };
214
264
 
215
265
  /**
@@ -259,6 +309,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
259
309
  report: null,
260
310
  review: null,
261
311
  merge: null,
312
+ override: null,
262
313
  lastTs: seenTs ?? null,
263
314
  });
264
315
  }
@@ -357,8 +408,59 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
357
408
  });
358
409
  }
359
410
  if (data.ticket != null) {
360
- ticketOf(data.ticket, ts).report = { verdict: data.verdict ?? null, ts, by: data.agent ?? actor };
411
+ const t = ticketOf(data.ticket, ts);
412
+ t.report = { verdict: data.verdict ?? null, ts, by: data.agent ?? actor };
413
+ t.override = null; // a lifecycle event outranks a hand-set lane
414
+ }
415
+ if (data.agent != null) closeAgent(state, data.agent);
416
+ break;
417
+ }
418
+ case 'progress': {
419
+ const agent = String(data.agent ?? '(no agent)');
420
+ state.progressByAgent.set(agent, {
421
+ state: data.state ?? null,
422
+ ticket: data.ticket ?? null,
423
+ detail: data.detail ?? null,
424
+ next: data.next ?? null,
425
+ ts,
426
+ });
427
+ if (data.state === 'blocked') {
428
+ state.blockages.set(agent, { ticket: data.ticket ?? null, agent, detail: data.detail ?? null, ts });
429
+ } else {
430
+ // started / working / unblocked all say "this agent is moving";
431
+ // whatever it reported itself blocked on is no longer blocking.
432
+ clearBlockageBy(state, agent);
433
+ }
434
+ break;
435
+ }
436
+ case 'finding':
437
+ state.findings.push({
438
+ id: data.id ?? null,
439
+ area: data.area ?? null,
440
+ claim: data.claim ?? null,
441
+ proof: data.proof ?? null,
442
+ ticket: data.ticket ?? null,
443
+ confidence: data.confidence ?? null,
444
+ ts,
445
+ actor,
446
+ });
447
+ break;
448
+ case 'ticket.status': {
449
+ // An override is a LANE, not progress: it must never move the percent.
450
+ // Minting a ledger ticket for an id no other event mentions did exactly
451
+ // that — one mistyped id (`T-1O` for `T-10`) enlarged the denominator
452
+ // and dropped the headline percent, while the ticket the operator meant
453
+ // to park stayed unparked. So the override lands only on a ticket the
454
+ // journal already knows; an unknown one is refused OUT LOUD (see
455
+ // `warnings()`) rather than inventing the ticket it names, because a
456
+ // silent exclusion is the failure ADR-19 correction 1 forbids.
457
+ const key = String(data.ticket ?? '(no ticket)');
458
+ if (!state.tickets.has(key)) {
459
+ state.unknownOverrides.push({ ticket: key, ts });
460
+ break;
361
461
  }
462
+ const t = ticketOf(key, ts);
463
+ t.override = { column: data.column ?? null, reason: data.reason ?? null, until: data.until ?? null, ts };
362
464
  break;
363
465
  }
364
466
  case 'gate': {
@@ -376,20 +478,26 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
376
478
  // `review`/`merge` require data.ticket, but a hand-written or older
377
479
  // journal may omit it — bucket those under a visible pseudo-ticket
378
480
  // instead of dropping the event (silent loss is the worse failure).
379
- case 'review':
380
- ticketOf(data.ticket ?? '(no ticket)', ts).review = {
381
- verdict: data.verdict ?? null,
382
- by: data.by ?? actor,
383
- ts,
384
- };
481
+ case 'review': {
482
+ const t = ticketOf(data.ticket ?? '(no ticket)', ts);
483
+ t.review = { verdict: data.verdict ?? null, by: data.by ?? actor, ts };
484
+ t.override = null;
485
+ clearBlockagesOn(state, t.id);
486
+ // The review is the REVIEWER's completion event, as a report is the
487
+ // implementer's: pairSpawns closes the reviewer's spawn on `data.by`,
488
+ // and the same correlator closes what that spawn left behind. Without
489
+ // it a reviewer's ticketless blockage outlived its own review with no
490
+ // later event that could ever clear it.
491
+ if (data.by != null) closeAgent(state, data.by);
385
492
  break;
386
- case 'merge':
387
- ticketOf(data.ticket ?? '(no ticket)', ts).merge = {
388
- sha: data.sha ?? null,
389
- mode: data.mode ?? null,
390
- ts,
391
- };
493
+ }
494
+ case 'merge': {
495
+ const t = ticketOf(data.ticket ?? '(no ticket)', ts);
496
+ t.merge = { sha: data.sha ?? null, mode: data.mode ?? null, ts };
497
+ t.override = null;
498
+ clearBlockagesOn(state, t.id);
392
499
  break;
500
+ }
393
501
  case 'decision':
394
502
  state.decisions.push({ id: data.id ?? '(no id)', text: data.text ?? null, ts, actor });
395
503
  break;
@@ -433,6 +541,10 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
433
541
 
434
542
  /** Human-readable status of one ticket, derived from the strongest signal. */
435
543
  export function ticketStatus(t) {
544
+ // A hand-set lane outranks derivation — but only until the next stronger
545
+ // lifecycle event, which clears it AT FOLD TIME. It never touches the
546
+ // merged count or the percent: an override is a lane, not progress.
547
+ if (t.override) return `${t.override.column ?? '(no column)'} (set by ticket.status)`;
436
548
  if (t.merge) return `merged (${t.merge.sha ?? 'no sha'})`;
437
549
  if (t.review) return `review: ${t.review.verdict ?? 'no verdict'}`;
438
550
  if (t.report) return `reported: ${t.report.verdict ?? 'no verdict'}`;
@@ -477,6 +589,11 @@ export function warnings(state) {
477
589
  for (const [ev, n] of sortByKey([...state.unknownTypes.entries()], (e) => e[0])) {
478
590
  out.push(`unknown event type "${inlinePlain(ev)}" x${n} — counted but not folded (newer Tyran?)`);
479
591
  }
592
+ // The lane the operator meant to set is NOT set, and the id they typed is the
593
+ // only thing that can tell them why.
594
+ for (const { ticket } of state.unknownOverrides) {
595
+ out.push(`ticket.status for unknown ticket "${inlinePlain(ticket)}" — ignored (an override never invents a ticket)`);
596
+ }
480
597
  if (state.initiatives.length > 1) {
481
598
  out.push(
482
599
  `journal mixes ${state.initiatives.length} initiatives: ${state.initiatives.map((i) => inlinePlain(i)).join(', ')}`,
@@ -529,17 +646,54 @@ function renderState(state) {
529
646
  parts.push('\n## Agents\n\n');
530
647
  parts.push(
531
648
  table(
532
- ['Agent', 'Role', 'Model', 'Ticket', 'Worktree', 'Status', 'Spawned'],
533
- sortByKey(state.agents, (a) => `${a.agent} ${a.spawnTs ?? ''}`).map((a) => [
534
- inline(a.agent),
535
- inline(a.role),
536
- inline(a.model),
537
- inline(a.ticket),
538
- inline(a.worktree),
539
- a.status === 'running'
540
- ? '**running (no report yet)**'
541
- : `${inline(a.status)}${a.verdict == null ? '' : `: ${inline(a.verdict)}`}`,
542
- inline(a.spawnTs),
649
+ ['Agent', 'Role', 'Model', 'Ticket', 'Worktree', 'Status', 'Spawned', 'Last signal'],
650
+ sortByKey(state.agents, (a) => `${a.agent} ${a.spawnTs ?? ''}`).map((a) => {
651
+ // A signal that outlived its report is stale by definition, and cannot
652
+ // be read here: the report deleted it at fold time (see `closeAgent`),
653
+ // and only running rows carry a signal at all. The filter alone was not
654
+ // enough — a re-spawned name is running again.
655
+ const signal = a.status === 'running' ? state.progressByAgent.get(a.agent) : null;
656
+ return [
657
+ inline(a.agent),
658
+ inline(a.role),
659
+ inline(a.model),
660
+ inline(a.ticket),
661
+ inline(a.worktree),
662
+ a.status === 'running'
663
+ ? '**running (no report yet)**'
664
+ : `${inline(a.status)}${a.verdict == null ? '' : `: ${inline(a.verdict)}`}`,
665
+ inline(a.spawnTs),
666
+ signal ? `${inline(signal.state)} at ${inline(signal.ts)}` : inline(null),
667
+ ];
668
+ }),
669
+ ),
670
+ );
671
+
672
+ parts.push('\n## Open blockages\n\n');
673
+ parts.push(
674
+ table(
675
+ ['Ticket', 'Agent', 'Detail', 'Since'],
676
+ sortByKey([...state.blockages.values()], (b) => `${b.ticket ?? ''} ${b.agent}`).map((b) => [
677
+ inline(b.ticket),
678
+ inline(b.agent),
679
+ inline(b.detail),
680
+ inline(b.ts),
681
+ ]),
682
+ ),
683
+ );
684
+
685
+ parts.push('\n## Findings\n\n');
686
+ parts.push(
687
+ table(
688
+ ['Id', 'Area', 'Claim', 'Proof', 'Ticket', 'By', 'At'],
689
+ state.findings.map((f) => [
690
+ inline(f.id),
691
+ inline(f.area),
692
+ inline(f.claim),
693
+ inline(f.proof),
694
+ inline(f.ticket),
695
+ inline(f.actor),
696
+ inline(f.ts),
543
697
  ]),
544
698
  ),
545
699
  );
@@ -509,23 +509,61 @@ export function ensureAutonomyPolicy(repoRoot, { templatePath = policyTemplatePa
509
509
  }
510
510
 
511
511
  export const STATE_GITIGNORE_PATH = '.tyran/.gitignore';
512
+ export const STATE_GITIGNORE_LINES = Object.freeze([
513
+ 'state/*/locks/',
514
+ 'state/paused-until.json',
515
+ 'state/resume.json',
516
+ 'state/resume.log',
517
+ 'state/usage.json',
518
+ ]);
512
519
  const STATE_GITIGNORE_BODY =
513
520
  '# Runtime files, never history. Leases record who holds a worktree or a\n' +
514
521
  '# heavy slot RIGHT NOW; committing one makes every parallel merge conflict\n' +
515
- '# on state that was stale the moment it was written.\n' +
516
- 'state/*/locks/\n';
522
+ '# on state that was stale the moment it was written. The overnight files\n' +
523
+ '# are machine-local by nature: another clone has a different watcher pid,\n' +
524
+ '# a different telemetry stream, and no business inheriting this one\'s pause.\n' +
525
+ `${STATE_GITIGNORE_LINES.join('\n')}\n`;
517
526
 
518
527
  /**
519
- * Create-only write of `.tyran/.gitignore` excluding lease files. A nested
520
- * gitignore rather than a line in the host's, because `.tyran/` is committed
521
- * and travels into every worktree — the exclusion has to travel with it.
522
- * Returns `{ path, status: 'created' | 'present' }`; never overwrites, so an
523
- * operator's own additions survive re-running setup.
528
+ * Seed `.tyran/.gitignore` excluding runtime files. A nested gitignore rather
529
+ * than a line in the host's, because `.tyran/` is committed and travels into
530
+ * every worktree — the exclusion has to travel with it. An existing file gains
531
+ * any managed line it lacks, APPENDED at the end (matched by exact trimmed
532
+ * line): create-only seeding left every 0.1.9 install without the overnight
533
+ * exclusions, and the wind-down checklist's `git add .tyran/state` then
534
+ * committed a machine-local pause marker that every clone inherited. Existing
535
+ * content — operator additions included — is never reordered or rewritten,
536
+ * and a `!`-negated managed line is an operator decision this never reverses.
537
+ * Returns `{ path, status: 'created' | 'updated' | 'present' | 'unreadable' }`.
524
538
  */
525
539
  export function ensureStateGitignore(repoRoot) {
526
540
  const root = resolve(repoRoot);
527
541
  const path = join(root, ...STATE_GITIGNORE_PATH.split('/'));
528
- if (existsSync(path)) return { path, status: 'present' };
542
+ if (existsSync(path)) {
543
+ let existing;
544
+ try {
545
+ existing = readFileSync(path, 'utf8');
546
+ } catch {
547
+ // A directory or unreadable file at this path is the operator's to
548
+ // resolve; crashing the scan over an ignore nicety helps nobody.
549
+ return { path, status: 'unreadable' };
550
+ }
551
+ const have = new Set(existing.split('\n').map((line) => line.trim()));
552
+ // `!line` is the operator explicitly TRACKING that file; appending the
553
+ // plain line after it would win by last-match and silently reverse them.
554
+ const missing = STATE_GITIGNORE_LINES.filter((line) => !have.has(line) && !have.has(`!${line}`));
555
+ if (missing.length === 0) return { path, status: 'present' };
556
+ try {
557
+ const glue = existing === '' || existing.endsWith('\n') ? '' : '\n';
558
+ writeFileSync(path, `${existing}${glue}${missing.join('\n')}\n`);
559
+ } catch (error) {
560
+ throw new BootstrapError(
561
+ `could not write ${escapeInvisible(path)}: ${error.message}`,
562
+ 'check the directory permissions; re-running this command is safe',
563
+ );
564
+ }
565
+ return { path, status: 'updated' };
566
+ }
529
567
  try {
530
568
  mkdirSync(dirname(path), { recursive: true });
531
569
  writeFileSync(path, STATE_GITIGNORE_BODY);
@@ -561,10 +599,7 @@ function main() {
561
599
  ? `scan-repo: created ${escapeInvisible(seeded.path)} from the shipped template`
562
600
  : `scan-repo: ${escapeInvisible(seeded.path)} already exists — left untouched`,
563
601
  );
564
- const ignored = seedStateGitignore(dir);
565
- if (ignored.status === 'created') {
566
- console.error(`scan-repo: created ${escapeInvisible(ignored.path)} (lease files stay out of history)`);
567
- }
602
+ reportStateGitignore(seedStateGitignore(dir));
568
603
  return;
569
604
  }
570
605
 
@@ -581,10 +616,7 @@ function main() {
581
616
  if (seeded.status === 'created') {
582
617
  console.error(`scan-repo: created ${escapeInvisible(seeded.path)} from the shipped template`);
583
618
  }
584
- const ignored = seedStateGitignore(dir);
585
- if (ignored.status === 'created') {
586
- console.error(`scan-repo: created ${escapeInvisible(ignored.path)} (lease files stay out of history)`);
587
- }
619
+ reportStateGitignore(seedStateGitignore(dir));
588
620
  }
589
621
  try {
590
622
  mkdirSync(dirname(path), { recursive: true });
@@ -610,6 +642,17 @@ function seedPolicy(dir) {
610
642
  }
611
643
  }
612
644
 
645
+ /** A silent line only when nothing changed — every other shape is reported. */
646
+ function reportStateGitignore({ path, status }) {
647
+ if (status === 'created') {
648
+ console.error(`scan-repo: created ${escapeInvisible(path)} (lease files stay out of history)`);
649
+ } else if (status === 'updated') {
650
+ console.error(`scan-repo: updated ${escapeInvisible(path)} (appended missing runtime exclusions)`);
651
+ } else if (status === 'unreadable') {
652
+ console.error(`scan-repo: could not read ${escapeInvisible(path)} — runtime exclusions were NOT updated`);
653
+ }
654
+ }
655
+
613
656
  /**
614
657
  * `ensureStateGitignore`, with a BootstrapError turned into exit 2. Both call
615
658
  * sites run this AFTER `seedPolicy` on purpose: it creates `.tyran/` when
@@ -68,7 +68,7 @@ export function validateConfig(doc) {
68
68
  const errors = [];
69
69
  if (!isPlainObject(doc)) return ['config must be a mapping'];
70
70
 
71
- const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths'];
71
+ const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths', 'limits'];
72
72
  for (const key of Object.keys(doc)) {
73
73
  if (!known.includes(key)) errors.push(`${key}: unknown top-level key`);
74
74
  }
@@ -145,9 +145,70 @@ export function validateConfig(doc) {
145
145
  }
146
146
  }
147
147
 
148
+ // Overnight mode: usage-limit pause/resume. Optional; absent = feature off.
149
+ // Operator-written policy, never scanner-inferred — no provenance wrapper.
150
+ if ('limits' in doc) {
151
+ if (!isPlainObject(doc.limits)) errors.push('limits: must be a mapping');
152
+ else {
153
+ const limits = doc.limits;
154
+ if (!LIMITS_MODES.includes(limits.mode)) {
155
+ errors.push(`limits.mode: required, one of ${LIMITS_MODES.join(' | ')}`);
156
+ }
157
+ // Floor of 50 catches the classic footgun: 0.97 (a fraction pasted where
158
+ // a percent belongs) would otherwise pause on the first tool call of
159
+ // every session.
160
+ for (const key of ['pause_at_percent', 'weekly_pause_at_percent']) {
161
+ if (key in limits && (typeof limits[key] !== 'number' || limits[key] < 50 || limits[key] > 100)) {
162
+ errors.push(`limits.${key}: must be a number in [50, 100]`);
163
+ }
164
+ }
165
+ if ('wait_max_hours' in limits && (typeof limits.wait_max_hours !== 'number' || limits.wait_max_hours <= 0 || limits.wait_max_hours > 24)) {
166
+ errors.push('limits.wait_max_hours: must be a number in (0, 24]');
167
+ }
168
+ if ('long_wait' in limits && !LIMITS_LONG_WAIT.includes(limits.long_wait)) {
169
+ errors.push(`limits.long_wait: must be one of ${LIMITS_LONG_WAIT.join(' | ')}`);
170
+ }
171
+ if ('resume_margin_minutes' in limits && (typeof limits.resume_margin_minutes !== 'number' || limits.resume_margin_minutes <= 0 || limits.resume_margin_minutes > 240)) {
172
+ errors.push('limits.resume_margin_minutes: must be a number in (0, 240]');
173
+ }
174
+ const knownLimits = ['mode', 'pause_at_percent', 'weekly_pause_at_percent', 'wait_max_hours', 'long_wait', 'resume_margin_minutes'];
175
+ for (const key of Object.keys(limits)) {
176
+ if (!knownLimits.includes(key)) errors.push(`limits.${key}: unknown key`);
177
+ }
178
+ }
179
+ }
180
+
148
181
  return errors;
149
182
  }
150
183
 
184
+ export const LIMITS_MODES = Object.freeze(['off', 'warn', 'pause']);
185
+ export const LIMITS_LONG_WAIT = Object.freeze(['hold', 'resume']);
186
+
187
+ /**
188
+ * The limits block with defaults applied — the ONE place the defaults AND the
189
+ * accepted ranges live. `doc` is a parsed config (or null); an absent or
190
+ * invalid block is `off`. A value outside validateConfig's range is treated
191
+ * as absent (the default applies): the gate must never ENFORCE a value the
192
+ * schema rejects — `pause_at_percent: 0.97` enforced verbatim is a permanent
193
+ * false pause, the exact footgun the validator's floor of 50 exists to catch.
194
+ */
195
+ export function limitsOf(doc) {
196
+ const limits = isPlainObject(doc) && isPlainObject(doc.limits) ? doc.limits : {};
197
+ const mode = LIMITS_MODES.includes(limits.mode) ? limits.mode : 'off';
198
+ const inRange = (value, min, max, { minExclusive = false } = {}) =>
199
+ typeof value === 'number' && Number.isFinite(value) && (minExclusive ? value > min : value >= min) && value <= max;
200
+ return {
201
+ mode,
202
+ pause_at_percent: inRange(limits.pause_at_percent, 50, 100) ? limits.pause_at_percent : 97,
203
+ weekly_pause_at_percent:
204
+ inRange(limits.weekly_pause_at_percent, 50, 100) ? limits.weekly_pause_at_percent : 97,
205
+ wait_max_hours: inRange(limits.wait_max_hours, 0, 24, { minExclusive: true }) ? limits.wait_max_hours : 5,
206
+ long_wait: LIMITS_LONG_WAIT.includes(limits.long_wait) ? limits.long_wait : 'hold',
207
+ resume_margin_minutes:
208
+ inRange(limits.resume_margin_minutes, 0, 240, { minExclusive: true }) ? limits.resume_margin_minutes : 5,
209
+ };
210
+ }
211
+
151
212
  /**
152
213
  * Validate a knowledge file: `entries:` list of learned facts.
153
214
  * Schema adapted from the best pattern found in the wild (metaswarm):
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * statusline — tees the platform's rate-limit telemetry into the sidecar the
4
+ * usage gate reads.
5
+ *
6
+ * Measured on Claude Code 2.1.197: the PreToolUse hook payload does NOT carry
7
+ * `rate_limits` (recorded in hooks/HOOK-CONTRACT-MEASURED.md), so the ONLY
8
+ * place a session's subscription usage is programmatically visible is the
9
+ * statusline JSON — which a plugin cannot install; the operator registers this
10
+ * command in their user settings (`/tyran:setup` prints the snippet). Each
11
+ * time the statusline fires, this writes `.tyran/state/usage.json`
12
+ * atomically; the usage gate treats a sidecar older than its staleness window
13
+ * as absent and fails open.
14
+ *
15
+ * Trust boundary: the payload is platform-produced but this writer is
16
+ * deliberately a filter, not a copier — ONLY finite numbers and a
17
+ * shape-validated session id reach the sidecar, never free strings, so
18
+ * nothing downstream has to sanitize what it reads back.
19
+ *
20
+ * A statusline is a UI element: it must never break the UI. Every failure
21
+ * path exits 0, silently. `--sidecar-only` prints nothing at all, so an
22
+ * operator with an existing statusline can tee the platform's JSON payload
23
+ * into this writer BEFORE their own statusline consumes it:
24
+ * tee >(node .../statusline.mjs --sidecar-only) | existing-statusline.sh
25
+ * The order matters: this writer parses the platform payload, and what an
26
+ * existing statusline emits is a rendered display line, not JSON — teeing
27
+ * after it would silently never update the sidecar.
28
+ *
29
+ * CLI: node statusline.mjs [--sidecar-only] # payload on stdin
30
+ * Exit: always 0
31
+ */
32
+ import { existsSync, mkdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
33
+ import { join, resolve } from 'node:path';
34
+
35
+ export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
36
+ const MAX_INPUT_BYTES = 1024 * 1024;
37
+ const SESSION_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
38
+
39
+ /** Own-property read on a prototype-free view of foreign JSON. */
40
+ function field(obj, name) {
41
+ return obj !== null && typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, name)
42
+ ? obj[name]
43
+ : undefined;
44
+ }
45
+
46
+ function finiteNumber(value) {
47
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
48
+ }
49
+
50
+ /** One rate-limit window ({used_percentage, resets_at}) — numbers only. */
51
+ function windowOf(node) {
52
+ if (node === null || typeof node !== 'object') return null;
53
+ const used = finiteNumber(field(node, 'used_percentage'));
54
+ const resets = finiteNumber(field(node, 'resets_at'));
55
+ if (used === null && resets === null) return null;
56
+ const out = {};
57
+ if (used !== null) out.used_percentage = used;
58
+ if (resets !== null) out.resets_at = resets;
59
+ return out;
60
+ }
61
+
62
+ /**
63
+ * The sidecar document, or null when the payload carries nothing usable.
64
+ * `now` is injected so tests are deterministic.
65
+ */
66
+ export function sidecarOf(payload, nowIso) {
67
+ if (payload === null || typeof payload !== 'object') return null;
68
+ const limits = field(payload, 'rate_limits');
69
+ const fiveHour = windowOf(field(limits, 'five_hour'));
70
+ const sevenDay = windowOf(field(limits, 'seven_day'));
71
+ if (fiveHour === null && sevenDay === null) return null;
72
+ const doc = { written_at: nowIso };
73
+ const sessionId = field(payload, 'session_id');
74
+ if (typeof sessionId === 'string' && SESSION_ID_RE.test(sessionId)) doc.session_id = sessionId;
75
+ if (fiveHour !== null) doc.five_hour = fiveHour;
76
+ if (sevenDay !== null) doc.seven_day = sevenDay;
77
+ return doc;
78
+ }
79
+
80
+ /** Where the repo is, per the payload; last resort is the process cwd. */
81
+ export function repoRootOf(payload, cwd = process.cwd()) {
82
+ const workspace = field(payload, 'workspace');
83
+ for (const candidate of [field(workspace, 'project_dir'), field(workspace, 'current_dir'), field(payload, 'cwd')]) {
84
+ if (typeof candidate === 'string' && candidate !== '' && existsSync(candidate)) return candidate;
85
+ }
86
+ return cwd;
87
+ }
88
+
89
+ /** Atomic create-or-replace: temp in the same directory, then rename. */
90
+ export function writeSidecar(root, doc) {
91
+ const target = join(resolve(root), SIDECAR_RELPATH);
92
+ const dir = join(resolve(root), '.tyran', 'state');
93
+ if (!existsSync(join(resolve(root), '.tyran'))) return false; // not a Tyran repo — write nothing
94
+ mkdirSync(dir, { recursive: true });
95
+ const temp = join(dir, `.usage-${process.pid}.tmp`);
96
+ writeFileSync(temp, JSON.stringify(doc, null, 2) + '\n');
97
+ renameSync(temp, target);
98
+ return true;
99
+ }
100
+
101
+ /** The one visible line. Only numbers formatted here — nothing foreign. */
102
+ export function statusLineOf(doc) {
103
+ const parts = [];
104
+ const fmt = (label, w) => {
105
+ if (!w) return;
106
+ let text = `${label}`;
107
+ if (typeof w.used_percentage === 'number') text += ` ${Math.round(w.used_percentage)}%`;
108
+ if (typeof w.resets_at === 'number') {
109
+ const at = new Date(w.resets_at * 1000);
110
+ if (!Number.isNaN(at.getTime())) {
111
+ text += ` resets ${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`;
112
+ }
113
+ }
114
+ parts.push(text);
115
+ };
116
+ fmt('5h', doc.five_hour);
117
+ fmt('7d', doc.seven_day);
118
+ return parts.join(' · ');
119
+ }
120
+
121
+ async function readStdin(limit = MAX_INPUT_BYTES) {
122
+ const chunks = [];
123
+ let size = 0;
124
+ for await (const chunk of process.stdin) {
125
+ size += chunk.length;
126
+ if (size > limit) return null;
127
+ chunks.push(chunk);
128
+ }
129
+ return Buffer.concat(chunks).toString('utf8');
130
+ }
131
+
132
+ async function main() {
133
+ const sidecarOnly = process.argv.includes('--sidecar-only');
134
+ try {
135
+ const raw = await readStdin();
136
+ if (raw === null) return;
137
+ const payload = JSON.parse(raw);
138
+ const doc = sidecarOf(payload, new Date().toISOString());
139
+ if (doc === null) return;
140
+ writeSidecar(repoRootOf(payload), doc);
141
+ if (!sidecarOnly) process.stdout.write(statusLineOf(doc) + '\n');
142
+ } catch {
143
+ // A statusline that breaks the UI is worse than one that says nothing.
144
+ }
145
+ }
146
+
147
+ import { fileURLToPath } from 'node:url';
148
+ import { realpathSync } from 'node:fs';
149
+ function canonicalPath(path) {
150
+ const abs = resolve(path);
151
+ try {
152
+ return realpathSync(abs);
153
+ } catch {
154
+ return abs;
155
+ }
156
+ }
157
+ function isMainModule(moduleUrl) {
158
+ if (!process.argv[1]) return false;
159
+ return canonicalPath(process.argv[1]) === canonicalPath(fileURLToPath(moduleUrl));
160
+ }
161
+ if (isMainModule(import.meta.url)) await main();
@@ -164,10 +164,28 @@ open one.
164
164
  list: decide and record. Without this you ask a second time for consent
165
165
  you already have, which is the most common reason an operator ends up
166
166
  chasing you instead of reading reports.
167
+ - **Operator messages mid-run queue; none is dropped silently.** Triage
168
+ each at the next natural pause: which initiative (or a new one), what
169
+ size, then a `ticket.created` carrying `id` — the one key `append` does
170
+ NOT issue for you, so read it from the journal and never from memory:
171
+ `journal.mjs next-id <abs-journal> T` returns the next one, continuing
172
+ the plan's numbering — plus `title`, `deps` and `files_predicted`; or a
173
+ `decision` when it changes course rather than adds work. Confirm in one
174
+ line — "queued as T-9". A thought that never reached the journal does
175
+ not exist. `ticket.status` is your lane override for the three states no
176
+ lifecycle event can derive (`blocked`, `waiting-operator`, `parked`);
177
+ the next report, review or merge clears it.
178
+ - **Scout `DURABLE:` findings, you journal** as `finding` events — the
179
+ required keys are `area` + `claim` (the area is the path or subsystem the
180
+ scout's proof points at), plus that `proof` — scouts write nothing
181
+ themselves. Implementers and reviewers append their own.
167
182
  2. **Fresh context per task.** Handoffs are SELF-CONTAINED; the agent
168
183
  disappears afterwards. Never ask the operator to compact. **Every handoff
169
184
  carries eight things:** (1) the role and one story, one goal; (2) paths to
170
- the files of record; (3) the iron rules copied VERBATIM, not linked;
185
+ the files of record — including the ABSOLUTE path of the initiative
186
+ journal in the MAIN checkout and the initiative slug, because worktree
187
+ agents append their `progress` and `finding` events there;
188
+ (3) the iron rules copied VERBATIM, not linked;
171
189
  (4) the lease protocol (rule 7); (5) the **evidence contract** — the report
172
190
  must contain raw command output (exit codes, `X passed / Y failed`); a
173
191
  paraphrase like "tests are green" with no log is a REJECTED report. Final
@@ -252,6 +270,12 @@ open one.
252
270
  (XL); product, visual and irreversible decisions, put in plain language
253
271
  with your recommendation; anything hard to undo or visible outside the
254
272
  repo. **"Shall I continue?" is forbidden.**
273
+ **Every question to the operator lands in the journal before (or as) you
274
+ ask it**: a `gate` event, `result: WAITING_ON_OPERATOR`, `data` carrying
275
+ `question`, `recommendation`, `default` and `ticket` when it has one — a
276
+ question that lives only in chat has to be re-litigated after every
277
+ compaction. When answered, append the same `kind` with `result: answered`
278
+ plus a `decision` recording the answer in the operator's words.
255
279
  **Check the brake before every spawn and every merge:**
256
280
  `node ${CLAUDE_PLUGIN_ROOT}/scripts/stop-check.mjs` — exit 1 means the
257
281
  operator created `.tyran/STOP`. Halt, report where you got to, and do not
@@ -373,3 +397,12 @@ open one.
373
397
  a lease still held by an agent that has already reported. An orphaned lease
374
398
  blocks the next initiative from a resource nobody is using, and the person
375
399
  who hits it has no way to know it is stale.
400
+ - **A usage-gate refusal is a wind-down order, not an obstacle.** Near the
401
+ subscription window the gate refuses everything except checkpointing;
402
+ its refusal text IS the checklist — follow it verbatim, in order, then
403
+ stop. Never route around the allowlist: the point of pausing at 97% is
404
+ that the last 3% pays for a clean checkpoint instead of a corpse. The
405
+ scheduler resumes the session after the reset (or notifies and holds on a
406
+ long, weekly-shaped wait — `docs/overnight.md`); a resumed session starts
407
+ from the `usage-limit-pause` checkpoint and first closes the open
408
+ usage-limit gate with `result: passed`.