@jjanczur/tyran 0.1.9 → 0.1.10

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.
@@ -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();
@@ -373,3 +373,12 @@ open one.
373
373
  a lease still held by an agent that has already reported. An orphaned lease
374
374
  blocks the next initiative from a resource nobody is using, and the person
375
375
  who hits it has no way to know it is stale.
376
+ - **A usage-gate refusal is a wind-down order, not an obstacle.** Near the
377
+ subscription window the gate refuses everything except checkpointing;
378
+ its refusal text IS the checklist — follow it verbatim, in order, then
379
+ stop. Never route around the allowlist: the point of pausing at 97% is
380
+ that the last 3% pays for a clean checkpoint instead of a corpse. The
381
+ scheduler resumes the session after the reset (or notifies and holds on a
382
+ long, weekly-shaped wait — `docs/overnight.md`); a resumed session starts
383
+ from the `usage-limit-pause` checkpoint and first closes the open
384
+ usage-limit gate with `result: passed`.
@@ -135,3 +135,23 @@ Until it is committed there is a second hazard worth naming in your report: an
135
135
  agent that runs `git add -A` on a story branch sweeps the untracked `.tyran/`
136
136
  into that branch, and a four-way parallel run ends with four conflicting
137
137
  copies of the config. Stage explicit paths until this commit exists.
138
+
139
+ ## 7. Offer overnight mode — and say plainly what the operator must do
140
+
141
+ Overnight mode (`docs/overnight.md`) pauses autonomous work near the
142
+ subscription usage limit and resumes after the window resets. It is OFF by
143
+ default because its telemetry is a statusline the plugin cannot install:
144
+ `.claude/settings.json` in user scope is the operator's file, and the policy
145
+ gate refuses agents writing the in-repo one — so print the snippet with the
146
+ plugin path RESOLVED and let the human paste it:
147
+
148
+ ```json
149
+ { "statusLine": { "type": "command",
150
+ "command": "node <resolved-plugin-root>/scripts/statusline.mjs" } }
151
+ ```
152
+
153
+ Then show the `limits:` block to enable (`mode: 'pause'` — quoted, bare
154
+ `off`/`on` are YAML booleans) and note that `doctor --state` reports
155
+ `limit-telemetry-missing` if the pause is configured while the statusline is
156
+ not installed. Do not attempt the settings write yourself; the refusal is
157
+ the boundary working.
@@ -15,14 +15,18 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/journal.mjs" open-spawns "$J"
15
15
 
16
16
  Then report, in this order and no longer than a screen:
17
17
 
18
- 1. The progress line: `PROGRESS: NN% · X/Y tickets · phase: <name> · last merge: <sha>`.
19
- 2. **Agents with no report yet** — the ones from `open-spawns`. Say how long
18
+ 1. If `.tyran/state/paused-until.json` exists, the pause comes FIRST: which
19
+ window, when it resumes, and `node "${CLAUDE_PLUGIN_ROOT}/scripts/overnight.mjs" status`
20
+ output. Everything below it is context for a session that is deliberately
21
+ not working.
22
+ 2. The progress line: `PROGRESS: NN% · X/Y tickets · phase: <name> · last merge: <sha>`.
23
+ 3. **Agents with no report yet** — the ones from `open-spawns`. Say how long
20
24
  each has been open. An agent that has been running for an hour is the most
21
25
  useful thing on this screen and the easiest to overlook.
22
- 3. Open gates, and who is waiting on whom.
23
- 4. Any lease released by someone who did not hold it. The projection surfaces
26
+ 4. Open gates, and who is waiting on whom.
27
+ 5. Any lease released by someone who did not hold it. The projection surfaces
24
28
  these; they mean two agents believed they owned the same worktree.
25
- 5. The resume steps from the last checkpoint.
29
+ 6. The resume steps from the last checkpoint.
26
30
 
27
31
  If there is no journal, say exactly that and suggest `/tyran:setup`. Do not
28
32
  reconstruct a status from the git log — a plausible status is worse than none,
@@ -42,3 +42,23 @@ validation:
42
42
 
43
43
  # Files multiple agents may touch: append-only, serialized by the conductor.
44
44
  shared_zones: []
45
+
46
+ # Overnight mode — pause autonomous work near the subscription usage limits
47
+ # and resume after the window resets (docs/overnight.md). Requires the
48
+ # operator-installed statusline helper (scripts/statusline.mjs), which is the
49
+ # only place the platform exposes usage telemetry; without it the gate is
50
+ # silent and doctor says so.
51
+ #
52
+ # mode: off | warn | pause warn surfaces, never denies; pause winds down
53
+ # wait_max_hours: 5 reset further away than this = a LONG pause:
54
+ # notify and hold rather than silently waiting
55
+ # days (the weekly window). Within it: schedule
56
+ # the resume and say when.
57
+ # long_wait: hold | resume what the scheduler does beyond wait_max_hours
58
+ limits:
59
+ mode: 'off' # quoted — bare off is YAML for false
60
+ pause_at_percent: 97
61
+ weekly_pause_at_percent: 97
62
+ wait_max_hours: 5
63
+ long_wait: hold
64
+ resume_margin_minutes: 5