@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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +58 -0
- package/README.md +4 -1
- package/agents/implementer.md +23 -6
- package/agents/retro.md +4 -0
- package/agents/reviewer.md +4 -0
- package/agents/scout.md +4 -1
- package/bin/tyran.mjs +8 -0
- package/hooks/HOOK-CONTRACT-MEASURED.md +50 -3
- package/hooks/hooks.json +10 -0
- package/hooks/scripts/policy-gate.mjs +3 -4
- package/hooks/scripts/session-start.mjs +43 -4
- package/hooks/scripts/usage-gate.mjs +465 -0
- package/package.json +1 -1
- package/scripts/doctor.mjs +181 -4
- package/scripts/hooks-check.mjs +41 -4
- package/scripts/journal.mjs +73 -2
- package/scripts/overnight.mjs +599 -0
- package/scripts/project.mjs +178 -24
- package/scripts/scan-repo.mjs +59 -16
- package/scripts/schema.mjs +62 -1
- package/scripts/statusline.mjs +161 -0
- package/skills/run/SKILL.md +34 -1
- package/skills/setup/SKILL.md +20 -0
- package/skills/status/SKILL.md +9 -5
- package/templates/config.yaml +20 -0
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* usage-gate — pause autonomous work BEFORE the subscription window is gone.
|
|
4
|
+
*
|
|
5
|
+
* The platform's own behaviour at the limit is abrupt: API calls start
|
|
6
|
+
* failing mid-flight, agents die between a write and its commit, and the
|
|
7
|
+
* session survives only by luck of where it was standing. Measured twice on
|
|
8
|
+
* 2026-08-13 while this gate was being designed: a four-agent review fleet
|
|
9
|
+
* killed first by the five-hour window and then by the weekly one. This gate
|
|
10
|
+
* converts that cliff into a wind-down: near the threshold it refuses
|
|
11
|
+
* everything EXCEPT the closed set of actions needed to checkpoint state and
|
|
12
|
+
* schedule a resume, and its refusal text IS the wind-down checklist.
|
|
13
|
+
*
|
|
14
|
+
* ## Where the numbers come from (and where they cannot)
|
|
15
|
+
*
|
|
16
|
+
* Measured on Claude Code 2.1.197 (hooks/HOOK-CONTRACT-MEASURED.md): the
|
|
17
|
+
* PreToolUse stdin payload does NOT carry rate-limit telemetry. The only
|
|
18
|
+
* programmatic source is the statusline JSON, which a plugin cannot install —
|
|
19
|
+
* so the operator registers `scripts/statusline.mjs` (setup prints the
|
|
20
|
+
* snippet), and that helper tees the platform's `rate_limits` into
|
|
21
|
+
* `.tyran/state/usage.json`. This gate reads that sidecar and NOTHING else:
|
|
22
|
+
* no transcript parsing, no estimation. A sidecar older than
|
|
23
|
+
* `SIDECAR_FRESH_MS` is unknown, and unknown FAILS OPEN — a repo that never
|
|
24
|
+
* installed the statusline must never see a false pause (doctor reports the
|
|
25
|
+
* missing telemetry instead).
|
|
26
|
+
*
|
|
27
|
+
* ## Two windows, one policy knob (operator-decided 2026-08-13)
|
|
28
|
+
*
|
|
29
|
+
* The deciding variable is TIME UNTIL RESET, not which window tripped:
|
|
30
|
+
* - reset within `wait_max_hours` (default 5) — the five-hour window's shape
|
|
31
|
+
* — wind down and schedule the resume; the operator is told when.
|
|
32
|
+
* - reset beyond it — the weekly window's shape — this is a LONG pause:
|
|
33
|
+
* wind down, NOTIFY, and by default HOLD (`long_wait: hold`). Nobody
|
|
34
|
+
* should read "resuming soon" when the truth is days; silent multi-day
|
|
35
|
+
* waits are the expectation failure this knob exists to prevent.
|
|
36
|
+
* The gate stamps the marker with everything the scheduler needs to act on
|
|
37
|
+
* that policy; `overnight.mjs schedule` is where hold-vs-resume happens.
|
|
38
|
+
*
|
|
39
|
+
* ## Who it binds
|
|
40
|
+
*
|
|
41
|
+
* Subagents and the UNSUPERVISED main loop only. A supervised operator
|
|
42
|
+
* (permission_mode default/plan) is never bound: the statusline is already
|
|
43
|
+
* telling them the same number, and pausing a human's own interactive work
|
|
44
|
+
* is how a control gets uninstalled. The known `permission_mode` limit is
|
|
45
|
+
* inherited from policy-gate and stated there.
|
|
46
|
+
*
|
|
47
|
+
* ## Failure directions, chosen on purpose
|
|
48
|
+
*
|
|
49
|
+
* No `.tyran/` → silent pass. Config absent/malformed or `mode: off` → pass
|
|
50
|
+
* (this is a budget nicety, not a boundary; a broken config must not stop
|
|
51
|
+
* work — doctor already reports config-invalid). No/stale telemetry → pass.
|
|
52
|
+
* Marker present and expired → self-heals (unlinked) even when the watcher
|
|
53
|
+
* died with the machine. The one sticky direction: an ACTIVE marker binds
|
|
54
|
+
* without re-reading telemetry, so a paused session cannot un-pause itself
|
|
55
|
+
* by out-waiting the sidecar's staleness window.
|
|
56
|
+
*/
|
|
57
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
58
|
+
import { basename, join, resolve, sep } from 'node:path';
|
|
59
|
+
import { realpathSync } from 'node:fs';
|
|
60
|
+
import { fileURLToPath } from 'node:url';
|
|
61
|
+
|
|
62
|
+
import { limitsOf } from '../../scripts/schema.mjs';
|
|
63
|
+
import { parse } from '../../scripts/yaml-lite.mjs';
|
|
64
|
+
import { forJournal, locateJournal } from './evidence-gate.mjs';
|
|
65
|
+
import { resolveRepoRoot } from './session-start.mjs';
|
|
66
|
+
import { isUnsupervised, actorOf, stripMessageArguments, MESSAGE_ARGUMENT_RE } from './policy-gate.mjs';
|
|
67
|
+
import { splitSegments, tokensOf } from './secrets-gate.mjs';
|
|
68
|
+
import { PASS, field, main, runGate } from './hook-io.mjs';
|
|
69
|
+
|
|
70
|
+
/** Own budget, below the 8 s hooks.json timeout. All I/O here is small local
|
|
71
|
+
* files; the margin absorbs a cold filesystem, not real work. */
|
|
72
|
+
export const DEADLINE_MS = 4000;
|
|
73
|
+
|
|
74
|
+
export const MARKER_RELPATH = join('.tyran', 'state', 'paused-until.json');
|
|
75
|
+
export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
|
|
76
|
+
|
|
77
|
+
/** Telemetry older than this is unknown, and unknown fails open. */
|
|
78
|
+
export const SIDECAR_FRESH_MS = 10 * 60 * 1000;
|
|
79
|
+
|
|
80
|
+
const MAX_SMALL_FILE_BYTES = 64 * 1024;
|
|
81
|
+
const MAX_CONFIG_BYTES = 256 * 1024;
|
|
82
|
+
const SESSION_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
|
|
83
|
+
|
|
84
|
+
/** Scripts a wind-down may run (argv: node <script> ...), by basename. */
|
|
85
|
+
export const WIND_DOWN_SCRIPTS = Object.freeze([
|
|
86
|
+
'journal.mjs',
|
|
87
|
+
'project.mjs',
|
|
88
|
+
'overnight.mjs',
|
|
89
|
+
'stop-check.mjs',
|
|
90
|
+
]);
|
|
91
|
+
|
|
92
|
+
/** Git subcommands a wind-down may run. Push is absent on purpose: local
|
|
93
|
+
* durability is the goal; the resumed session pushes, and the policy gate
|
|
94
|
+
* governs push reach anyway. */
|
|
95
|
+
export const WIND_DOWN_GIT = Object.freeze(['status', 'add', 'commit', 'diff', 'log']);
|
|
96
|
+
|
|
97
|
+
const READ_ONLY_TOOLS = Object.freeze(['Read', 'Grep', 'Glob', 'NotebookRead', 'TaskOutput']);
|
|
98
|
+
const WRITE_TOOLS = Object.freeze(['Write', 'Edit', 'NotebookEdit']);
|
|
99
|
+
|
|
100
|
+
// ------------------------------------------------------------ small readers
|
|
101
|
+
|
|
102
|
+
function readSmallJson(path, cap = MAX_SMALL_FILE_BYTES) {
|
|
103
|
+
try {
|
|
104
|
+
if (!existsSync(path) || statSync(path).size > cap) return null;
|
|
105
|
+
const doc = JSON.parse(readFileSync(path, 'utf8'));
|
|
106
|
+
return doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : null;
|
|
107
|
+
} catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The limits block for this repo, defaults applied; null = feature off. */
|
|
113
|
+
export function readLimits(repoRoot) {
|
|
114
|
+
const configPath = join(repoRoot, '.tyran', 'config.yaml');
|
|
115
|
+
try {
|
|
116
|
+
if (!existsSync(configPath) || statSync(configPath).size > MAX_CONFIG_BYTES) return null;
|
|
117
|
+
const limits = limitsOf(parse(readFileSync(configPath, 'utf8')));
|
|
118
|
+
return limits.mode === 'off' ? null : limits;
|
|
119
|
+
} catch {
|
|
120
|
+
// A config this gate cannot read is doctor's finding, not a reason to
|
|
121
|
+
// stop the repo's work.
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The sidecar, or null when absent/stale/garbage. `nowMs` injected. */
|
|
127
|
+
export function readSidecar(repoRoot, nowMs, freshMs = SIDECAR_FRESH_MS) {
|
|
128
|
+
const doc = readSmallJson(join(repoRoot, SIDECAR_RELPATH));
|
|
129
|
+
if (doc === null) return null;
|
|
130
|
+
const writtenAt = Date.parse(typeof doc.written_at === 'string' ? doc.written_at : '');
|
|
131
|
+
if (!Number.isFinite(writtenAt) || nowMs - writtenAt > freshMs) return null;
|
|
132
|
+
return doc;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function windowOf(doc, key) {
|
|
136
|
+
const node = doc?.[key];
|
|
137
|
+
if (node === null || typeof node !== 'object') return null;
|
|
138
|
+
const used = typeof node.used_percentage === 'number' && Number.isFinite(node.used_percentage) ? node.used_percentage : null;
|
|
139
|
+
const resets = typeof node.resets_at === 'number' && Number.isFinite(node.resets_at) ? node.resets_at : null;
|
|
140
|
+
return used === null ? null : { used_percentage: used, resets_at: resets };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Which window trips the thresholds, if any. When both trip, the WEEKLY one
|
|
145
|
+
* governs: its reset is the binding constraint — waiting out the five-hour
|
|
146
|
+
* refill just hits the weekly wall again.
|
|
147
|
+
*/
|
|
148
|
+
export function trippedWindow(sidecar, limits) {
|
|
149
|
+
const weekly = windowOf(sidecar, 'seven_day');
|
|
150
|
+
if (weekly !== null && weekly.used_percentage >= limits.weekly_pause_at_percent) {
|
|
151
|
+
return { window: 'seven_day', ...weekly };
|
|
152
|
+
}
|
|
153
|
+
const fiveHour = windowOf(sidecar, 'five_hour');
|
|
154
|
+
if (fiveHour !== null && fiveHour.used_percentage >= limits.pause_at_percent) {
|
|
155
|
+
return { window: 'five_hour', ...fiveHour };
|
|
156
|
+
}
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ------------------------------------------------------------------ marker
|
|
161
|
+
|
|
162
|
+
export function markerOf(tripped, limits, nowMs, sessionId, init) {
|
|
163
|
+
const resetsMs = tripped.resets_at !== null ? tripped.resets_at * 1000 : null;
|
|
164
|
+
// No resets_at from the platform: the window is known-exhausted but the
|
|
165
|
+
// reset time is unknown. A null resume_at would be a marker nothing can
|
|
166
|
+
// self-heal — a permanent false pause — so bound it at wait_max_hours from
|
|
167
|
+
// now instead: the pause still protects the remainder, and the marker
|
|
168
|
+
// expires on its own even if every watcher dies.
|
|
169
|
+
const resumeAtMs =
|
|
170
|
+
resetsMs !== null ? resetsMs + limits.resume_margin_minutes * 60 * 1000 : nowMs + limits.wait_max_hours * 3600 * 1000;
|
|
171
|
+
const waitMs = resumeAtMs - nowMs;
|
|
172
|
+
const longWait = waitMs > limits.wait_max_hours * 3600 * 1000;
|
|
173
|
+
return {
|
|
174
|
+
paused_at: new Date(nowMs).toISOString(),
|
|
175
|
+
window: tripped.window,
|
|
176
|
+
used_percentage: tripped.used_percentage,
|
|
177
|
+
resets_at: tripped.resets_at,
|
|
178
|
+
resume_at: new Date(resumeAtMs).toISOString(),
|
|
179
|
+
long_wait: longWait,
|
|
180
|
+
// What the scheduler should DO about a long wait — copied from config at
|
|
181
|
+
// pause time so the decision is auditable next to its inputs.
|
|
182
|
+
long_wait_policy: limits.long_wait,
|
|
183
|
+
session_id: typeof sessionId === 'string' && SESSION_ID_RE.test(sessionId) ? sessionId : null,
|
|
184
|
+
init: init ?? null,
|
|
185
|
+
source: 'sidecar',
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function writeMarker(repoRoot, marker) {
|
|
190
|
+
const dir = join(repoRoot, '.tyran', 'state');
|
|
191
|
+
mkdirSync(dir, { recursive: true });
|
|
192
|
+
const temp = join(dir, `.paused-${process.pid}.tmp`);
|
|
193
|
+
writeFileSync(temp, JSON.stringify(marker, null, 2) + '\n');
|
|
194
|
+
renameSync(temp, join(repoRoot, MARKER_RELPATH));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** No marker shape is immortal: one without a parseable resume_at (hand-made
|
|
198
|
+
* or from an older Tyran) expires this long after paused_at. */
|
|
199
|
+
export const MARKER_MAX_AGE_MS = 24 * 3600 * 1000;
|
|
200
|
+
|
|
201
|
+
/** An active marker, or null. Expired markers self-heal (best-effort unlink):
|
|
202
|
+
* the watcher may have died with the machine, and a pause that outlives its
|
|
203
|
+
* own resume time is a stall, not a protection. */
|
|
204
|
+
export function readMarker(repoRoot, nowMs, { unlink = unlinkSync } = {}) {
|
|
205
|
+
const path = join(repoRoot, MARKER_RELPATH);
|
|
206
|
+
const doc = readSmallJson(path);
|
|
207
|
+
if (doc === null) return null;
|
|
208
|
+
const resumeAt = Date.parse(typeof doc.resume_at === 'string' ? doc.resume_at : '');
|
|
209
|
+
const pausedAt = Date.parse(typeof doc.paused_at === 'string' ? doc.paused_at : '');
|
|
210
|
+
const expired = Number.isFinite(resumeAt)
|
|
211
|
+
? nowMs >= resumeAt
|
|
212
|
+
: !Number.isFinite(pausedAt) || nowMs >= pausedAt + MARKER_MAX_AGE_MS;
|
|
213
|
+
if (expired) {
|
|
214
|
+
try {
|
|
215
|
+
unlink(path);
|
|
216
|
+
} catch {
|
|
217
|
+
/* the next reader tries again */
|
|
218
|
+
}
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
return doc;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// --------------------------------------------------------------- allowlist
|
|
225
|
+
|
|
226
|
+
/** Is this repo-root-relative-or-absolute path under `.tyran/state/`?
|
|
227
|
+
* Backslashes are separators only on Windows; on POSIX `.tyran\state\x` is a
|
|
228
|
+
* literal FILENAME the Write tool would create at the repo root, so rewriting
|
|
229
|
+
* it here would allow a write that lands outside the state dir. */
|
|
230
|
+
function underState(repoRoot, rawPath) {
|
|
231
|
+
if (typeof rawPath !== 'string' || rawPath === '') return false;
|
|
232
|
+
const normalized = process.platform === 'win32' ? rawPath.replace(/\\/g, '/') : rawPath;
|
|
233
|
+
const abs = resolve(repoRoot, normalized);
|
|
234
|
+
const stateDir = join(resolve(repoRoot), '.tyran', 'state');
|
|
235
|
+
return abs === stateDir || abs.startsWith(stateDir + sep);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* In an ALLOWLIST context the message-argument strip must not blind the
|
|
240
|
+
* check: the real shell still expands `$( )` and backticks inside a
|
|
241
|
+
* double-quoted or bare `--data`/`-m` value, so a substitution smuggled there
|
|
242
|
+
* would run while the lexer sees only the allowed carrier command.
|
|
243
|
+
* Single-quoted values are shell-inert and stay allowed — the wind-down
|
|
244
|
+
* checklist's own appends use them. Same bounded shape as the strip itself
|
|
245
|
+
* (MESSAGE_ARGUMENT_RE), not a second parser.
|
|
246
|
+
*/
|
|
247
|
+
function messageArgumentsInert(command) {
|
|
248
|
+
for (const match of String(command).matchAll(MESSAGE_ARGUMENT_RE)) {
|
|
249
|
+
const value = match[4];
|
|
250
|
+
if (value.startsWith("'")) continue;
|
|
251
|
+
if (value.includes('$') || value.includes('`')) return false;
|
|
252
|
+
}
|
|
253
|
+
return true;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** `git add` flags that sweep the whole tree — the refusal promises explicit
|
|
257
|
+
* paths, so the gate enforces exactly that. */
|
|
258
|
+
const GIT_ADD_SWEEPERS = Object.freeze(['-A', '--all', '-u', '--update', '.']);
|
|
259
|
+
|
|
260
|
+
function bashAllowed(command, repoRoot) {
|
|
261
|
+
if (!messageArgumentsInert(command)) return false;
|
|
262
|
+
let segments;
|
|
263
|
+
try {
|
|
264
|
+
// Message arguments are DATA, not program: a journal append's --data blob
|
|
265
|
+
// carries JSON whose braces the shared lexer treats as segment
|
|
266
|
+
// separators. Same strip, same reason, as policy-gate's commandTokens.
|
|
267
|
+
segments = splitSegments(stripMessageArguments(String(command)));
|
|
268
|
+
} catch {
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
if (segments.length === 0) return false;
|
|
272
|
+
for (const segment of segments) {
|
|
273
|
+
let tokens;
|
|
274
|
+
try {
|
|
275
|
+
tokens = tokensOf(segment);
|
|
276
|
+
} catch {
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
const argv = tokens.filter((t) => typeof t === 'string' && t !== '');
|
|
280
|
+
if (argv.length === 0) return false;
|
|
281
|
+
const program = basename(argv[0]);
|
|
282
|
+
if (program === 'node') {
|
|
283
|
+
// node <script> …: the script decides. Basename on purpose — both the
|
|
284
|
+
// ${CLAUDE_PLUGIN_ROOT} expansion and an absolute path must pass, and
|
|
285
|
+
// the declared floor (commands, never effects) is stated in the
|
|
286
|
+
// refusal: a path assembled at runtime is invisible to this check.
|
|
287
|
+
if (argv.length < 2 || !WIND_DOWN_SCRIPTS.includes(basename(argv[1]))) return false;
|
|
288
|
+
// Wind-down Writes may land under .tyran/state/**, so a script THERE
|
|
289
|
+
// with an allowed basename would close the loop on arbitrary code:
|
|
290
|
+
// Write .tyran/state/journal.mjs, then run it. Scripts under the
|
|
291
|
+
// adopted repo's .tyran/ are never the plugin's own.
|
|
292
|
+
const scriptAbs = resolve(repoRoot, argv[1]);
|
|
293
|
+
const tyranDir = join(resolve(repoRoot), '.tyran');
|
|
294
|
+
if (scriptAbs === tyranDir || scriptAbs.startsWith(tyranDir + sep)) return false;
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (program === 'git') {
|
|
298
|
+
const sub = argv.find((t, i) => i > 0 && !t.startsWith('-'));
|
|
299
|
+
if (!WIND_DOWN_GIT.includes(sub)) return false;
|
|
300
|
+
// `--output` turns read-only log/diff into a file write anywhere on
|
|
301
|
+
// disk; `git add -A`/`.` sweeps the whole tree into the pause commit.
|
|
302
|
+
if (argv.some((t, i) => i > 0 && t.startsWith('--output'))) return false;
|
|
303
|
+
if (sub === 'add' && argv.some((t, i) => i > 0 && GIT_ADD_SWEEPERS.includes(t))) return false;
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
return true;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** May this tool call proceed during wind-down? Pure given its inputs. */
|
|
312
|
+
export function allowedDuringWindDown(toolName, toolInput, repoRoot) {
|
|
313
|
+
if (READ_ONLY_TOOLS.includes(toolName)) return true;
|
|
314
|
+
if (WRITE_TOOLS.includes(toolName)) {
|
|
315
|
+
const path = field(toolInput, 'file_path') ?? field(toolInput, 'notebook_path') ?? field(toolInput, 'path');
|
|
316
|
+
return underState(repoRoot, path);
|
|
317
|
+
}
|
|
318
|
+
if (toolName === 'Bash') return bashAllowed(field(toolInput, 'command'), repoRoot);
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ----------------------------------------------------------------- refusal
|
|
323
|
+
|
|
324
|
+
function humanWait(waitMs) {
|
|
325
|
+
if (waitMs === null || !Number.isFinite(waitMs) || waitMs <= 0) return 'unknown';
|
|
326
|
+
const hours = Math.floor(waitMs / 3600000);
|
|
327
|
+
const minutes = Math.round((waitMs % 3600000) / 60000);
|
|
328
|
+
if (hours >= 48) return `~${Math.round(hours / 24)} days`;
|
|
329
|
+
return hours > 0 ? `~${hours}h ${minutes}m` : `~${minutes}m`;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const WINDOW_NAMES = Object.freeze({ five_hour: 'five-hour', seven_day: 'SEVEN-DAY' });
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* The plugin's scripts directory, absolute. The checklist prints ABSOLUTE
|
|
336
|
+
* paths on purpose: the shared shell lexer treats `{`/`}` as segment
|
|
337
|
+
* separators, so a `${CLAUDE_PLUGIN_ROOT}` spelling can never satisfy the
|
|
338
|
+
* per-segment allowlist — the refusal must hand out commands the allowlist
|
|
339
|
+
* itself will pass.
|
|
340
|
+
*/
|
|
341
|
+
export const PLUGIN_SCRIPTS_DIR = resolve(fileURLToPath(new URL('../../scripts/', import.meta.url)));
|
|
342
|
+
|
|
343
|
+
export function buildRefusal(marker, { subagent = false, waitMaxHours, scriptsDir = PLUGIN_SCRIPTS_DIR }) {
|
|
344
|
+
const windowName = WINDOW_NAMES[marker.window] ?? String(marker.window ?? 'usage');
|
|
345
|
+
const resumeAt = typeof marker.resume_at === 'string' ? marker.resume_at : 'unknown';
|
|
346
|
+
const waitMs = typeof marker.resume_at === 'string' ? Date.parse(marker.resume_at) - Date.parse(marker.paused_at ?? marker.resume_at) : null;
|
|
347
|
+
const used = typeof marker.used_percentage === 'number' ? marker.used_percentage.toFixed(1) : '?';
|
|
348
|
+
|
|
349
|
+
const head = marker.long_wait
|
|
350
|
+
? `tyran usage-gate: ${used}% of the ${windowName} window is used and it resets at ${resumeAt} — ` +
|
|
351
|
+
`${humanWait(waitMs)} away, beyond wait_max_hours=${waitMaxHours}. This is a LONG pause: after the ` +
|
|
352
|
+
`wind-down, the scheduler will ${marker.long_wait_policy === 'resume' ? 'schedule the resume AND notify the operator of the long wait' : 'NOTIFY the operator and HOLD (limits.long_wait: hold) — nothing resumes without them'}.`
|
|
353
|
+
: `tyran usage-gate: ${used}% of the ${windowName} window is used (resets ${resumeAt}, ${humanWait(waitMs)}). ` +
|
|
354
|
+
`Pausing instead of burning the remainder; the scheduler resumes this session after the reset.`;
|
|
355
|
+
|
|
356
|
+
if (subagent) {
|
|
357
|
+
return (
|
|
358
|
+
`${head}\n` +
|
|
359
|
+
`Report what you have NOW, honestly marked as interrupted. If the story is unfinished, the legitimate ` +
|
|
360
|
+
`evidence hatch is:\nEVIDENCE: none-required — usage-limit pause interrupted this story`
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const sid = marker.session_id ?? '<session-id>';
|
|
365
|
+
return (
|
|
366
|
+
`${head}\n` +
|
|
367
|
+
`Allowed until then: reads; writes under .tyran/state/**; node runs of the journal/project/overnight/` +
|
|
368
|
+
`stop-check scripts (absolute paths as printed below — the allowlist reads commands, never effects, and ` +
|
|
369
|
+
`cannot read a \${VAR} spelling); git status/add/commit/diff/log (explicit paths, never -A; push is ` +
|
|
370
|
+
`denied — the resumed session pushes).\n` +
|
|
371
|
+
`Wind down IN THIS ORDER, then stop:\n` +
|
|
372
|
+
` 1. node "${scriptsDir}/journal.mjs" append <journal> checkpoint <init> --actor conductor ` +
|
|
373
|
+
`--data '{"phase":"usage-limit-pause","next_steps":["re-read STATE.md","close the usage-limit gate with result passed","check open leases and spawns","continue from this checkpoint"]}'\n` +
|
|
374
|
+
` 2. node "${scriptsDir}/journal.mjs" append <journal> gate <init> --actor conductor ` +
|
|
375
|
+
`--data '{"kind":"usage-limit","result":"WAITING_ON_RESET","window":"${marker.window}","resume_at":"${resumeAt}","used_percentage":${JSON.stringify(marker.used_percentage ?? null)},"session_id":"${sid}"}'\n` +
|
|
376
|
+
` 3. node "${scriptsDir}/project.mjs" <journal> --out-dir <dir>\n` +
|
|
377
|
+
` 4. git add <explicit .tyran/state paths> && git commit\n` +
|
|
378
|
+
` 5. node "${scriptsDir}/overnight.mjs" schedule\n` +
|
|
379
|
+
` 6. Stop. If the Stop gate asks for a retrospective, record a retro.entry ` +
|
|
380
|
+
`(--data '{"kind":"skipped","target":"<init>","reason":"usage-limit pause"}' — target is required).\n` +
|
|
381
|
+
`The pause marker is .tyran/state/paused-until.json; an operator takes over with ` +
|
|
382
|
+
`node "${scriptsDir}/overnight.mjs" cancel.`
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// ------------------------------------------------------------------ decide
|
|
387
|
+
|
|
388
|
+
/** The verdict. Everything injected so the whole decision is testable. */
|
|
389
|
+
export function decide(
|
|
390
|
+
input,
|
|
391
|
+
{
|
|
392
|
+
now = () => Date.now(),
|
|
393
|
+
locate = locateJournal,
|
|
394
|
+
readLimitsFn = readLimits,
|
|
395
|
+
readSidecarFn = readSidecar,
|
|
396
|
+
readMarkerFn = readMarker,
|
|
397
|
+
writeMarkerFn = writeMarker,
|
|
398
|
+
} = {},
|
|
399
|
+
) {
|
|
400
|
+
const repoRoot = resolveRepoRoot(input);
|
|
401
|
+
if (repoRoot === null || !existsSync(join(repoRoot, '.tyran'))) return PASS;
|
|
402
|
+
|
|
403
|
+
const limits = readLimitsFn(repoRoot);
|
|
404
|
+
if (limits === null) return PASS;
|
|
405
|
+
|
|
406
|
+
const nowMs = now();
|
|
407
|
+
let marker = readMarkerFn(repoRoot, nowMs);
|
|
408
|
+
|
|
409
|
+
if (marker === null) {
|
|
410
|
+
const sidecar = readSidecarFn(repoRoot, nowMs);
|
|
411
|
+
if (sidecar === null) return PASS; // no telemetry = unknown = open
|
|
412
|
+
const tripped = trippedWindow(sidecar, limits);
|
|
413
|
+
if (tripped === null) return PASS;
|
|
414
|
+
if (limits.mode === 'warn') return PASS; // surfacing is doctor's job
|
|
415
|
+
if (!isUnsupervised(input)) return PASS; // never bind the operator
|
|
416
|
+
const journal = locate(repoRoot);
|
|
417
|
+
marker = markerOf(tripped, limits, nowMs, field(input, 'session_id'), journal.init ? forJournal(journal.init) : null);
|
|
418
|
+
try {
|
|
419
|
+
writeMarkerFn(repoRoot, marker);
|
|
420
|
+
} catch {
|
|
421
|
+
// A marker that cannot be written is a pause that cannot be durable —
|
|
422
|
+
// still refuse this call (the refusal text works without the file),
|
|
423
|
+
// and the next call retries the write.
|
|
424
|
+
}
|
|
425
|
+
} else if (!isUnsupervised(input)) {
|
|
426
|
+
// Marker active, but a supervised operator is at the keyboard: their own
|
|
427
|
+
// interactive work is never bound. The marker stays for the autonomous
|
|
428
|
+
// path; `overnight.mjs cancel` clears it deliberately.
|
|
429
|
+
return PASS;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
if (allowedDuringWindDown(field(input, 'tool_name'), field(input, 'tool_input'), repoRoot)) return PASS;
|
|
433
|
+
|
|
434
|
+
return {
|
|
435
|
+
decision: 'deny',
|
|
436
|
+
reason: buildRefusal(marker, {
|
|
437
|
+
subagent: actorOf(input) === 'subagent',
|
|
438
|
+
waitMaxHours: limits.wait_max_hours,
|
|
439
|
+
}),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function canonicalPath(path) {
|
|
444
|
+
const abs = resolve(path);
|
|
445
|
+
try {
|
|
446
|
+
return realpathSync(abs);
|
|
447
|
+
} catch {
|
|
448
|
+
return abs;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function isMainModule(moduleUrl) {
|
|
453
|
+
if (!process.argv[1]) return false;
|
|
454
|
+
return canonicalPath(process.argv[1]) === canonicalPath(fileURLToPath(moduleUrl));
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
if (isMainModule(import.meta.url)) {
|
|
458
|
+
await main(() =>
|
|
459
|
+
runGate({
|
|
460
|
+
event: 'PreToolUse',
|
|
461
|
+
deadlineMs: DEADLINE_MS,
|
|
462
|
+
handler: ({ input }) => decide(input),
|
|
463
|
+
}),
|
|
464
|
+
);
|
|
465
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jjanczur/tyran",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.11",
|
|
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": {
|