@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,599 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* overnight — schedule and run the usage-limit resume watcher.
|
|
4
|
+
*
|
|
5
|
+
* The usage gate winds a session down and writes a pause marker
|
|
6
|
+
* (`.tyran/state/paused-until.json`); this tool is the marker's OTHER half:
|
|
7
|
+
* `schedule` decides between WAITING and HOLDING, `--wait` is the detached
|
|
8
|
+
* watcher that sleeps to the window reset and resumes the paused session,
|
|
9
|
+
* `status` and `cancel` are the operator's handles.
|
|
10
|
+
*
|
|
11
|
+
* ## Wait vs hold — the operator's 2026-08-13 policy, mechanized
|
|
12
|
+
*
|
|
13
|
+
* The deciding variable is time-until-reset, already stamped on the marker by
|
|
14
|
+
* the gate (`long_wait`, from `limits.wait_max_hours`):
|
|
15
|
+
* - short wait (the five-hour window's shape): spawn the watcher, notify the
|
|
16
|
+
* operator with the resume time, resume automatically;
|
|
17
|
+
* - long wait (the weekly window's shape): NOTIFY and, under the default
|
|
18
|
+
* `limits.long_wait: hold`, schedule NOTHING — a resume days out that
|
|
19
|
+
* nobody asked for reads as "working soon" when the truth is "parked".
|
|
20
|
+
* `--force-resume` (or `long_wait: resume` in config) opts into true
|
|
21
|
+
* multi-day autonomy, still with the loud notification.
|
|
22
|
+
*
|
|
23
|
+
* ## What the watcher defends against (measured platform facts)
|
|
24
|
+
*
|
|
25
|
+
* - Machine sleep: chunked sleeps re-read the wall clock; an overslept
|
|
26
|
+
* laptop fires late, never never. Reboot kills the watcher — the marker
|
|
27
|
+
* then goes stale, doctor reports it, and the gate self-heals it.
|
|
28
|
+
* - Blind resumed sessions: statuslines do not run under `claude -p`
|
|
29
|
+
* (measured 2.1.197), so a resumed session has NO fresh telemetry. The
|
|
30
|
+
* watcher BABYSITS: it waits for the child and, if the journal shows no
|
|
31
|
+
* movement — the classic sign the window was still exhausted — backs off
|
|
32
|
+
* and retries on a fixed ladder instead of dying with it.
|
|
33
|
+
* - Double resume: before spawning it checks the STOP brake, the marker
|
|
34
|
+
* still existing, and the journal (a closed usage-limit gate or a
|
|
35
|
+
* post-pause checkpoint means the conductor already came back).
|
|
36
|
+
* - The weekly wall behind the five-hour refill: at wake, fresh telemetry
|
|
37
|
+
* showing the seven-day window still over threshold reschedules to THAT
|
|
38
|
+
* reset (or holds, beyond wait_max) instead of burning the refill.
|
|
39
|
+
*
|
|
40
|
+
* Nothing read from the marker or sidecar ever reaches a shell: every child
|
|
41
|
+
* is an argv array with shell:false, and the session id is shape-validated
|
|
42
|
+
* before it becomes an argument. Notifications carry only our own words and
|
|
43
|
+
* numbers.
|
|
44
|
+
*
|
|
45
|
+
* CLI:
|
|
46
|
+
* node overnight.mjs schedule [--dir <repo>] [--prompt <text>] [--cmd <exe>] [--force-resume]
|
|
47
|
+
* node overnight.mjs status [--dir <repo>]
|
|
48
|
+
* node overnight.mjs cancel [--dir <repo>] [--clear]
|
|
49
|
+
* node overnight.mjs --wait [--dir <repo>] # internal (the watcher)
|
|
50
|
+
* Exit: 0 ok/held · 1 refused (no marker, already scheduled, STOP) · 2 usage/IO
|
|
51
|
+
*/
|
|
52
|
+
import { spawn, spawnSync, execFile } from 'node:child_process';
|
|
53
|
+
import { existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
54
|
+
import { join, resolve } from 'node:path';
|
|
55
|
+
import { realpathSync } from 'node:fs';
|
|
56
|
+
import { fileURLToPath } from 'node:url';
|
|
57
|
+
import { checkStop } from './stop-check.mjs';
|
|
58
|
+
import { readJournal } from './journal.mjs';
|
|
59
|
+
import { limitsOf } from './schema.mjs';
|
|
60
|
+
import { parse } from './yaml-lite.mjs';
|
|
61
|
+
import { escapeInvisible } from './invisible.mjs';
|
|
62
|
+
|
|
63
|
+
export const MARKER_RELPATH = join('.tyran', 'state', 'paused-until.json');
|
|
64
|
+
export const RESUME_STATE_RELPATH = join('.tyran', 'state', 'resume.json');
|
|
65
|
+
export const RESUME_LOG_RELPATH = join('.tyran', 'state', 'resume.log');
|
|
66
|
+
export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
|
|
67
|
+
|
|
68
|
+
export const SESSION_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
|
|
69
|
+
/** Short enough that an overslept machine fires soon after waking. */
|
|
70
|
+
export const MAX_SLEEP_CHUNK_MS = 15 * 60 * 1000;
|
|
71
|
+
/** Telemetry older than this is unknown; unknown means proceed. */
|
|
72
|
+
export const SIDECAR_FRESH_MS = 10 * 60 * 1000;
|
|
73
|
+
/** Babysitting ladder after a resume that visibly did not take. */
|
|
74
|
+
export const RESUME_BACKOFFS_MS = Object.freeze([5 * 60 * 1000, 30 * 60 * 1000, 60 * 60 * 1000]);
|
|
75
|
+
/** Hard ceiling on a single `claude -p` attempt before the babysitter reclaims it. */
|
|
76
|
+
export const RESUME_ATTEMPT_TIMEOUT_MS = 6 * 60 * 60 * 1000;
|
|
77
|
+
/**
|
|
78
|
+
* The longest a live watcher can legitimately still be running past its
|
|
79
|
+
* resume_at: every attempt on the ladder may consume the full per-attempt
|
|
80
|
+
* timeout, plus the backoff sleeps between attempts. Derived from those
|
|
81
|
+
* constants so a ladder change cannot leave this window stale.
|
|
82
|
+
*/
|
|
83
|
+
export const WATCHER_MAX_OVERRUN_MS =
|
|
84
|
+
(RESUME_BACKOFFS_MS.length + 1) * RESUME_ATTEMPT_TIMEOUT_MS + RESUME_BACKOFFS_MS.reduce((a, b) => a + b, 0);
|
|
85
|
+
|
|
86
|
+
class UsageError extends Error {}
|
|
87
|
+
|
|
88
|
+
// ------------------------------------------------------------ pure helpers
|
|
89
|
+
|
|
90
|
+
export function nextSleepMs(nowMs, resumeAtMs, chunk = MAX_SLEEP_CHUNK_MS) {
|
|
91
|
+
const remaining = resumeAtMs - nowMs;
|
|
92
|
+
return remaining <= 0 ? 0 : Math.min(remaining, chunk);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Should the watcher skip resuming, and why. Deterministic over its inputs:
|
|
97
|
+
* the STOP brake, marker existence, and the journal's own record.
|
|
98
|
+
*/
|
|
99
|
+
export function skipReason({ stopped, markerExists, journalEvents, pausedAtIso }) {
|
|
100
|
+
if (stopped) return 'stop-brake';
|
|
101
|
+
if (!markerExists) return 'marker-gone';
|
|
102
|
+
const pausedAt = Date.parse(pausedAtIso ?? '') || 0;
|
|
103
|
+
let gateOpen = null;
|
|
104
|
+
let laterCheckpoint = false;
|
|
105
|
+
for (const e of journalEvents ?? []) {
|
|
106
|
+
const ts = Date.parse(e?.ts ?? '') || 0;
|
|
107
|
+
// Only this pause's gate events count: a gate closed before pausedAt
|
|
108
|
+
// belongs to an earlier cycle and says nothing about the current one.
|
|
109
|
+
if (e?.ev === 'gate' && e?.data?.kind === 'usage-limit' && ts > pausedAt) {
|
|
110
|
+
const result = String(e?.data?.result ?? '').toLowerCase();
|
|
111
|
+
gateOpen = !['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered'].includes(result);
|
|
112
|
+
}
|
|
113
|
+
if (e?.ev === 'checkpoint' && ts > pausedAt && e?.data?.phase !== 'usage-limit-pause') laterCheckpoint = true;
|
|
114
|
+
}
|
|
115
|
+
if (gateOpen === false) return 'gate-already-closed';
|
|
116
|
+
if (laterCheckpoint) return 'resumed-manually';
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* At wake time: does fresh telemetry say the WEEKLY window is still over
|
|
122
|
+
* threshold, and if so when could work actually resume. Stale or absent
|
|
123
|
+
* telemetry is unknown, and unknown means proceed — blocking a resume on
|
|
124
|
+
* missing data would strand every run whose operator closed the laptop lid.
|
|
125
|
+
*/
|
|
126
|
+
export function weeklyDeferral(sidecar, nowMs, { weeklyPausePercent, marginMs, freshMs = SIDECAR_FRESH_MS }) {
|
|
127
|
+
if (!sidecar || typeof sidecar !== 'object') return null;
|
|
128
|
+
const writtenAt = Date.parse(typeof sidecar.written_at === 'string' ? sidecar.written_at : '');
|
|
129
|
+
if (!Number.isFinite(writtenAt) || nowMs - writtenAt > freshMs) return null;
|
|
130
|
+
const weekly = sidecar.seven_day;
|
|
131
|
+
if (!weekly || typeof weekly.used_percentage !== 'number') return null;
|
|
132
|
+
if (weekly.used_percentage < weeklyPausePercent) return null;
|
|
133
|
+
if (typeof weekly.resets_at !== 'number') return null;
|
|
134
|
+
return weekly.resets_at * 1000 + marginMs;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The resume argv. Nothing here ever passes through a shell. */
|
|
138
|
+
export function resumeArgv(sessionId, prompt, { cmd = 'claude', permissionMode = 'acceptEdits' } = {}) {
|
|
139
|
+
if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) {
|
|
140
|
+
throw new UsageError('the marker carries no usable session id — resume the session by hand');
|
|
141
|
+
}
|
|
142
|
+
return [cmd, '-p', '--resume', sessionId, '--permission-mode', permissionMode, prompt];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function defaultPrompt(init) {
|
|
146
|
+
const where = init ? `.tyran/state/${init}/STATE.md` : 'the newest .tyran/state/*/STATE.md';
|
|
147
|
+
return (
|
|
148
|
+
`Usage-limit pause is over. Read ${where} and the journal tail, then continue from the ` +
|
|
149
|
+
`'usage-limit-pause' checkpoint. First close the open usage-limit gate: append a gate event, ` +
|
|
150
|
+
`kind "usage-limit", result "passed".`
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Did the resume TAKE? Journal movement, not the child's exit code: a session
|
|
156
|
+
* that hit the still-exhausted window exits "cleanly" having appended nothing,
|
|
157
|
+
* and that silence is exactly the failure the babysitter exists to catch.
|
|
158
|
+
*/
|
|
159
|
+
export function resumeTook({ eventsBefore, eventsAfter }) {
|
|
160
|
+
return eventsAfter > eventsBefore;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function humanWait(waitMs) {
|
|
164
|
+
if (!Number.isFinite(waitMs) || waitMs <= 0) return 'now';
|
|
165
|
+
const hours = Math.floor(waitMs / 3600000);
|
|
166
|
+
if (hours >= 48) return `~${Math.round(hours / 24)} days`;
|
|
167
|
+
const minutes = Math.round((waitMs % 3600000) / 60000);
|
|
168
|
+
return hours > 0 ? `~${hours}h ${minutes}m` : `~${minutes}m`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* What `schedule` should do, given the marker and an operator override.
|
|
173
|
+
* Pure, so the hold-vs-watch policy is testable without a filesystem.
|
|
174
|
+
*/
|
|
175
|
+
export function scheduleDecision(marker, { forceResume = false } = {}) {
|
|
176
|
+
if (marker.long_wait && marker.long_wait_policy !== 'resume' && !forceResume) {
|
|
177
|
+
return { action: 'hold' };
|
|
178
|
+
}
|
|
179
|
+
return { action: 'watch' };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// --------------------------------------------------------------- plumbing
|
|
183
|
+
|
|
184
|
+
function readSmallJson(path) {
|
|
185
|
+
try {
|
|
186
|
+
if (!existsSync(path) || statSync(path).size > 64 * 1024) return null;
|
|
187
|
+
const doc = JSON.parse(readFileSync(path, 'utf8'));
|
|
188
|
+
return doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : null;
|
|
189
|
+
} catch {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function writeStateFile(repo, doc) {
|
|
195
|
+
const dir = join(repo, '.tyran', 'state');
|
|
196
|
+
mkdirSync(dir, { recursive: true });
|
|
197
|
+
const temp = join(dir, `.resume-${process.pid}.tmp`);
|
|
198
|
+
writeFileSync(temp, JSON.stringify(doc, null, 2) + '\n');
|
|
199
|
+
renameSync(temp, join(repo, RESUME_STATE_RELPATH));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function log(repo, message) {
|
|
203
|
+
try {
|
|
204
|
+
mkdirSync(join(repo, '.tyran', 'state'), { recursive: true });
|
|
205
|
+
writeFileSync(join(repo, RESUME_LOG_RELPATH), `${new Date().toISOString()} ${message}\n`, { flag: 'a' });
|
|
206
|
+
} catch {
|
|
207
|
+
/* a log that cannot be written must not stop the watcher */
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function pidAlive(pid) {
|
|
212
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
213
|
+
try {
|
|
214
|
+
process.kill(pid, 0);
|
|
215
|
+
return true;
|
|
216
|
+
} catch {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** A heartbeat older than this cannot be the live watcher's: it stamps every
|
|
222
|
+
* loop iteration, and the sleep chunk is capped at MAX_SLEEP_CHUNK_MS. */
|
|
223
|
+
export const HEARTBEAT_FRESH_MS = 2 * MAX_SLEEP_CHUNK_MS;
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Whether resume.json's recorded watcher can still BE the watcher. A pid
|
|
227
|
+
* check alone survives reboots: recycling can hand the number to an unrelated
|
|
228
|
+
* process. The heartbeat is liveness the clock cannot fake — a recycled pid
|
|
229
|
+
* never writes one, while a real watcher that overslept a day stamps it again
|
|
230
|
+
* on its first iteration after the machine wakes. States from an older Tyran
|
|
231
|
+
* carry no heartbeat; for those, past resume_at + WATCHER_MAX_OVERRUN_MS no
|
|
232
|
+
* real watcher can still be running. Within those windows a recycled pid is
|
|
233
|
+
* indistinguishable from ours — full process identity is not portable in
|
|
234
|
+
* zero-dependency Node; this is the floor.
|
|
235
|
+
*/
|
|
236
|
+
export function watcherAlive(state, nowMs = Date.now()) {
|
|
237
|
+
if (state?.state !== 'waiting' || !pidAlive(state?.pid)) return false;
|
|
238
|
+
const heartbeatMs = Date.parse(typeof state.heartbeat_at === 'string' ? state.heartbeat_at : '');
|
|
239
|
+
if (Number.isFinite(heartbeatMs)) return nowMs - heartbeatMs <= HEARTBEAT_FRESH_MS;
|
|
240
|
+
const resumeAtMs = Date.parse(typeof state.resume_at === 'string' ? state.resume_at : '');
|
|
241
|
+
return !(Number.isFinite(resumeAtMs) && nowMs > resumeAtMs + WATCHER_MAX_OVERRUN_MS);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Best-effort desktop notification — macOS osascript, then notify-send.
|
|
246
|
+
* Text is OUR OWN words and numbers only; nothing foreign is interpolated.
|
|
247
|
+
* Every failure is silent: a notification is a courtesy, not a channel the
|
|
248
|
+
* design depends on (the journal, the log and doctor are the record).
|
|
249
|
+
*/
|
|
250
|
+
export function notifyDesktop(title, body, { run = execFile } = {}) {
|
|
251
|
+
const quiet = () => {};
|
|
252
|
+
try {
|
|
253
|
+
if (process.platform === 'darwin') {
|
|
254
|
+
run('osascript', ['-e', `display notification ${JSON.stringify(body)} with title ${JSON.stringify(title)}`], quiet);
|
|
255
|
+
} else {
|
|
256
|
+
run('notify-send', [title, body], quiet);
|
|
257
|
+
}
|
|
258
|
+
} catch {
|
|
259
|
+
/* a notification is a courtesy; its absence is never a failure */
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function journalPathFor(repo, init) {
|
|
264
|
+
return init ? join(repo, '.tyran', 'state', init, 'journal.jsonl') : null;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function journalEventCount(path) {
|
|
268
|
+
if (path === null || !existsSync(path)) return null;
|
|
269
|
+
try {
|
|
270
|
+
return readJournal(path).events.length;
|
|
271
|
+
} catch {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function readLimitsFile(repo) {
|
|
277
|
+
try {
|
|
278
|
+
return limitsOf(parse(readFileSync(join(repo, '.tyran', 'config.yaml'), 'utf8')));
|
|
279
|
+
} catch {
|
|
280
|
+
return limitsOf(null);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// ------------------------------------------------------------ subcommands
|
|
285
|
+
|
|
286
|
+
function doSchedule(repo, flags) {
|
|
287
|
+
const marker = readSmallJson(join(repo, MARKER_RELPATH));
|
|
288
|
+
if (marker === null) {
|
|
289
|
+
console.error('overnight: no pause marker at .tyran/state/paused-until.json — nothing to schedule');
|
|
290
|
+
process.exit(1);
|
|
291
|
+
}
|
|
292
|
+
const state = readSmallJson(join(repo, RESUME_STATE_RELPATH));
|
|
293
|
+
if (watcherAlive(state)) {
|
|
294
|
+
console.error(`overnight: a watcher is already waiting (pid ${state.pid}, resumes ${state.resume_at}) — cancel it first`);
|
|
295
|
+
process.exit(1);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const resumeAt = typeof marker.resume_at === 'string' ? marker.resume_at : null;
|
|
299
|
+
const waitMs = resumeAt !== null ? Date.parse(resumeAt) - Date.now() : NaN;
|
|
300
|
+
const windowName = marker.window === 'seven_day' ? 'weekly' : 'five-hour';
|
|
301
|
+
|
|
302
|
+
if (scheduleDecision(marker, { forceResume: flags['force-resume'] === true }).action === 'hold') {
|
|
303
|
+
writeStateFile(repo, {
|
|
304
|
+
state: 'holding',
|
|
305
|
+
window: marker.window ?? null,
|
|
306
|
+
resume_at: resumeAt,
|
|
307
|
+
held_at: new Date().toISOString(),
|
|
308
|
+
});
|
|
309
|
+
const body = `Paused on the ${windowName} usage limit; the window resets ${resumeAt ?? 'at an unknown time'} (${humanWait(waitMs)}). Holding — nothing resumes without you.`;
|
|
310
|
+
notifyDesktop('Tyran: long pause', body);
|
|
311
|
+
log(repo, `hold window=${marker.window} resume_at=${resumeAt}`);
|
|
312
|
+
console.log(
|
|
313
|
+
`overnight: LONG pause on the ${windowName} window — holding, per limits.long_wait.\n` +
|
|
314
|
+
` window resets: ${resumeAt ?? 'unknown'} (${humanWait(waitMs)})\n` +
|
|
315
|
+
` resume later: node "${SELF}" schedule --force-resume # spawns the watcher despite the hold\n` +
|
|
316
|
+
` or simply start a new session after the reset — the gate self-clears the marker.`,
|
|
317
|
+
);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// The gate legally writes session_id: null (a pause with no live session).
|
|
322
|
+
// A watcher spawned for such a marker has nothing it could ever resume.
|
|
323
|
+
if (typeof marker.session_id !== 'string' || !SESSION_ID_RE.test(marker.session_id)) {
|
|
324
|
+
console.error('overnight: the marker carries no usable session id — resume by hand');
|
|
325
|
+
process.exit(1);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const logFd = openSync(join(repo, RESUME_LOG_RELPATH), 'a');
|
|
329
|
+
const watcherArgv = [
|
|
330
|
+
SELF,
|
|
331
|
+
'--wait',
|
|
332
|
+
'--dir',
|
|
333
|
+
repo,
|
|
334
|
+
...(typeof flags.prompt === 'string' ? ['--prompt', flags.prompt] : []),
|
|
335
|
+
...(typeof flags.cmd === 'string' ? ['--cmd', flags.cmd] : []),
|
|
336
|
+
...(typeof flags['chunk-ms'] === 'number' ? ['--chunk-ms', String(flags['chunk-ms'])] : []),
|
|
337
|
+
...(typeof flags['backoff-ms'] === 'number' ? ['--backoff-ms', String(flags['backoff-ms'])] : []),
|
|
338
|
+
];
|
|
339
|
+
const child = spawn(process.execPath, watcherArgv, {
|
|
340
|
+
detached: true,
|
|
341
|
+
stdio: ['ignore', logFd, logFd],
|
|
342
|
+
});
|
|
343
|
+
child.unref();
|
|
344
|
+
writeStateFile(repo, {
|
|
345
|
+
state: 'waiting',
|
|
346
|
+
pid: child.pid,
|
|
347
|
+
window: marker.window ?? null,
|
|
348
|
+
resume_at: resumeAt,
|
|
349
|
+
session_id: marker.session_id,
|
|
350
|
+
started_at: new Date().toISOString(),
|
|
351
|
+
});
|
|
352
|
+
const body = `Paused on the ${windowName} usage limit; resuming automatically ${resumeAt ?? 'after the reset'} (${humanWait(waitMs)}).`;
|
|
353
|
+
notifyDesktop('Tyran: paused, resume scheduled', body);
|
|
354
|
+
log(repo, `scheduled pid=${child.pid} window=${marker.window} resume_at=${resumeAt}`);
|
|
355
|
+
console.log(`overnight: watcher pid ${child.pid} resumes this session at ${resumeAt ?? 'the reset'} (${humanWait(waitMs)})`);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
async function doWait(repo, flags) {
|
|
359
|
+
// Capped: the heartbeat's freshness window is derived from the maximum
|
|
360
|
+
// chunk, so a longer custom sleep would make a live watcher look dead.
|
|
361
|
+
const chunkMs = Math.min(typeof flags['chunk-ms'] === 'number' ? flags['chunk-ms'] : MAX_SLEEP_CHUNK_MS, MAX_SLEEP_CHUNK_MS);
|
|
362
|
+
// --backoff-ms replaces every rung: the real ladder's first rung is minutes,
|
|
363
|
+
// which puts the retry path beyond the reach of any test that keeps it real.
|
|
364
|
+
const backoffs =
|
|
365
|
+
typeof flags['backoff-ms'] === 'number' ? RESUME_BACKOFFS_MS.map(() => flags['backoff-ms']) : RESUME_BACKOFFS_MS;
|
|
366
|
+
const prompt = typeof flags.prompt === 'string' ? flags.prompt : null;
|
|
367
|
+
const cmd = typeof flags.cmd === 'string' ? flags.cmd : 'claude';
|
|
368
|
+
|
|
369
|
+
for (;;) {
|
|
370
|
+
const marker = readSmallJson(join(repo, MARKER_RELPATH));
|
|
371
|
+
if (marker === null) {
|
|
372
|
+
log(repo, 'skip: marker-gone');
|
|
373
|
+
writeStateFile(repo, { state: 'skipped', reason: 'marker-gone', at: new Date().toISOString() });
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const resumeAtMs = Date.parse(typeof marker.resume_at === 'string' ? marker.resume_at : '');
|
|
377
|
+
if (!Number.isFinite(resumeAtMs)) {
|
|
378
|
+
log(repo, 'skip: marker has no usable resume_at');
|
|
379
|
+
writeStateFile(repo, { state: 'failed', reason: 'bad-marker', at: new Date().toISOString() });
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const sleepMs = nextSleepMs(Date.now(), resumeAtMs, chunkMs);
|
|
383
|
+
if (sleepMs > 0) {
|
|
384
|
+
// The heartbeat is what lets schedule/cancel trust an alive pid: a
|
|
385
|
+
// recycled pid never stamps one, and a watcher that overslept a day
|
|
386
|
+
// stamps it again the instant the machine wakes.
|
|
387
|
+
const state = readSmallJson(join(repo, RESUME_STATE_RELPATH)) ?? {};
|
|
388
|
+
writeStateFile(repo, { ...state, state: 'waiting', pid: process.pid, resume_at: marker.resume_at ?? null, heartbeat_at: new Date().toISOString() });
|
|
389
|
+
await new Promise((r) => setTimeout(r, sleepMs));
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// Reset time reached. Re-check the world before spawning anything.
|
|
394
|
+
const init = typeof marker.init === 'string' && /^[A-Za-z0-9._-]{1,80}$/.test(marker.init) ? marker.init : null;
|
|
395
|
+
const journalPath = journalPathFor(repo, init);
|
|
396
|
+
let events = [];
|
|
397
|
+
try {
|
|
398
|
+
events = journalPath !== null && existsSync(journalPath) ? readJournal(journalPath).events : [];
|
|
399
|
+
} catch {
|
|
400
|
+
events = [];
|
|
401
|
+
}
|
|
402
|
+
const reason = skipReason({
|
|
403
|
+
stopped: checkStop(repo).stopped,
|
|
404
|
+
markerExists: true,
|
|
405
|
+
journalEvents: events,
|
|
406
|
+
pausedAtIso: marker.paused_at,
|
|
407
|
+
});
|
|
408
|
+
if (reason !== null) {
|
|
409
|
+
log(repo, `skip: ${reason}`);
|
|
410
|
+
writeStateFile(repo, { state: reason === 'stop-brake' ? 'aborted-stop' : 'skipped', reason, at: new Date().toISOString() });
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const limits = readLimitsFile(repo);
|
|
415
|
+
const deferral = weeklyDeferral(readSmallJson(join(repo, SIDECAR_RELPATH)), Date.now(), {
|
|
416
|
+
weeklyPausePercent: limits.weekly_pause_at_percent,
|
|
417
|
+
marginMs: limits.resume_margin_minutes * 60 * 1000,
|
|
418
|
+
});
|
|
419
|
+
if (deferral !== null && deferral > Date.now()) {
|
|
420
|
+
const deferredIso = new Date(deferral).toISOString();
|
|
421
|
+
const longAgain = deferral - Date.now() > limits.wait_max_hours * 3600 * 1000;
|
|
422
|
+
if (longAgain && limits.long_wait !== 'resume') {
|
|
423
|
+
log(repo, `hold-at-wake: weekly still over threshold, resets ${deferredIso}`);
|
|
424
|
+
notifyDesktop('Tyran: still limited', `The weekly window is still exhausted; it resets ${deferredIso}. Holding — nothing resumes without you.`);
|
|
425
|
+
writeStateFile(repo, { state: 'holding', reason: 'weekly-still-exhausted', resume_at: deferredIso, at: new Date().toISOString() });
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
log(repo, `weekly-deferral: rescheduling to ${deferredIso}`);
|
|
429
|
+
writeFileSync(join(repo, MARKER_RELPATH), JSON.stringify({ ...marker, resume_at: deferredIso, window: 'seven_day' }, null, 2) + '\n');
|
|
430
|
+
writeStateFile(repo, { state: 'waiting', pid: process.pid, resume_at: deferredIso, window: 'seven_day', started_at: new Date().toISOString() });
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Build the argv BEFORE touching the marker: the gate legally writes
|
|
435
|
+
// session_id: null, and a marker that cannot be resumed must survive on
|
|
436
|
+
// disk so doctor's stale-pause warning has its evidence.
|
|
437
|
+
let argv;
|
|
438
|
+
try {
|
|
439
|
+
argv = resumeArgv(marker.session_id, prompt ?? defaultPrompt(init), { cmd });
|
|
440
|
+
} catch (err) {
|
|
441
|
+
if (!(err instanceof UsageError)) throw err;
|
|
442
|
+
log(repo, 'failed: bad-session-id');
|
|
443
|
+
writeStateFile(repo, { state: 'failed', reason: 'bad-session-id', at: new Date().toISOString() });
|
|
444
|
+
notifyDesktop('Tyran: resume FAILED', 'The pause marker carries no usable session id — resume the session by hand.');
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
// Go. Clear the marker so the resumed session's gate starts clean.
|
|
448
|
+
try {
|
|
449
|
+
unlinkSync(join(repo, MARKER_RELPATH));
|
|
450
|
+
} catch {
|
|
451
|
+
/* best effort */
|
|
452
|
+
}
|
|
453
|
+
const eventsBefore = journalEventCount(journalPath);
|
|
454
|
+
for (let attempt = 0; ; attempt++) {
|
|
455
|
+
log(repo, `resuming attempt=${attempt + 1} argv=${argv[0]} session=${marker.session_id}`);
|
|
456
|
+
writeStateFile(repo, { state: 'resuming', attempt: attempt + 1, at: new Date().toISOString() });
|
|
457
|
+
notifyDesktop('Tyran: resuming', `The usage window has reset; resuming the paused session${init ? ` (${init})` : ''}.`);
|
|
458
|
+
const child = spawnSync(argv[0], argv.slice(1), { cwd: repo, encoding: 'utf8', timeout: RESUME_ATTEMPT_TIMEOUT_MS });
|
|
459
|
+
const eventsAfter = journalEventCount(journalPath);
|
|
460
|
+
const took =
|
|
461
|
+
eventsBefore === null || eventsAfter === null
|
|
462
|
+
? child.status === 0
|
|
463
|
+
: resumeTook({ eventsBefore, eventsAfter });
|
|
464
|
+
log(repo, `claude exited status=${child.status} signal=${child.signal ?? 'none'} took=${took}`);
|
|
465
|
+
if (took) {
|
|
466
|
+
writeStateFile(repo, { state: 'done', at: new Date().toISOString() });
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
if (attempt >= backoffs.length) {
|
|
470
|
+
writeStateFile(repo, { state: 'failed', reason: 'resume-did-not-take', exit: child.status, at: new Date().toISOString() });
|
|
471
|
+
notifyDesktop('Tyran: resume FAILED', 'The scheduled resume did not take (no journal movement). See .tyran/state/resume.log.');
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
if (checkStop(repo).stopped) {
|
|
475
|
+
log(repo, 'abort during backoff: stop-brake');
|
|
476
|
+
writeStateFile(repo, { state: 'aborted-stop', at: new Date().toISOString() });
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
await new Promise((r) => setTimeout(r, backoffs[attempt]));
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function doStatus(repo) {
|
|
485
|
+
const marker = readSmallJson(join(repo, MARKER_RELPATH));
|
|
486
|
+
const state = readSmallJson(join(repo, RESUME_STATE_RELPATH));
|
|
487
|
+
if (marker === null && state === null) {
|
|
488
|
+
console.log('overnight: no pause marker and no watcher state — nothing scheduled');
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (marker !== null) {
|
|
492
|
+
const waitMs = Date.parse(marker.resume_at ?? '') - Date.now();
|
|
493
|
+
console.log(
|
|
494
|
+
`paused: window=${escapeInvisible(String(marker.window))} used=${marker.used_percentage}% ` +
|
|
495
|
+
`resume_at=${escapeInvisible(String(marker.resume_at))} (${humanWait(waitMs)}) long_wait=${marker.long_wait}`,
|
|
496
|
+
);
|
|
497
|
+
} else {
|
|
498
|
+
console.log('no active pause marker');
|
|
499
|
+
}
|
|
500
|
+
if (state !== null) {
|
|
501
|
+
const alive = state.state === 'waiting' ? ` (pid ${state.pid} ${watcherAlive(state) ? 'alive' : 'DEAD'})` : '';
|
|
502
|
+
console.log(`watcher: ${escapeInvisible(String(state.state))}${alive}`);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function doCancel(repo, flags) {
|
|
507
|
+
const state = readSmallJson(join(repo, RESUME_STATE_RELPATH));
|
|
508
|
+
if (watcherAlive(state)) {
|
|
509
|
+
try {
|
|
510
|
+
process.kill(state.pid, 'SIGTERM');
|
|
511
|
+
console.log(`overnight: watcher pid ${state.pid} cancelled`);
|
|
512
|
+
} catch (err) {
|
|
513
|
+
console.error(`overnight: could not signal pid ${state.pid} (${err.code ?? err.message})`);
|
|
514
|
+
}
|
|
515
|
+
} else {
|
|
516
|
+
console.log('overnight: no live watcher to cancel');
|
|
517
|
+
}
|
|
518
|
+
writeStateFile(repo, { state: 'cancelled', at: new Date().toISOString() });
|
|
519
|
+
if (flags.clear === true) {
|
|
520
|
+
try {
|
|
521
|
+
unlinkSync(join(repo, MARKER_RELPATH));
|
|
522
|
+
console.log('overnight: pause marker cleared — the operator has taken over');
|
|
523
|
+
} catch {
|
|
524
|
+
console.log('overnight: no marker to clear');
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// ------------------------------------------------------------------- CLI
|
|
530
|
+
|
|
531
|
+
const BOOLEAN_FLAGS = ['force-resume', 'clear', 'wait'];
|
|
532
|
+
const NUMERIC_FLAGS = ['chunk-ms', 'backoff-ms'];
|
|
533
|
+
const VALUE_FLAGS = ['dir', 'prompt', 'cmd', ...NUMERIC_FLAGS];
|
|
534
|
+
|
|
535
|
+
function parseArgs(argv) {
|
|
536
|
+
const flags = {};
|
|
537
|
+
const positionals = [];
|
|
538
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
539
|
+
const arg = argv[i];
|
|
540
|
+
if (!arg.startsWith('--')) {
|
|
541
|
+
positionals.push(arg);
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
const name = arg.slice(2);
|
|
545
|
+
if (BOOLEAN_FLAGS.includes(name)) flags[name] = true;
|
|
546
|
+
else if (VALUE_FLAGS.includes(name)) {
|
|
547
|
+
const value = argv[i + 1];
|
|
548
|
+
if (value === undefined) throw new UsageError(`flag --${name} needs a value`);
|
|
549
|
+
if (NUMERIC_FLAGS.includes(name)) {
|
|
550
|
+
// NaN or a non-positive number would make nextSleepMs fire the watcher
|
|
551
|
+
// immediately — hours early — instead of failing here, loudly.
|
|
552
|
+
const ms = Number(value);
|
|
553
|
+
if (!Number.isFinite(ms) || ms <= 0) throw new UsageError(`flag --${name} needs a positive number of milliseconds`);
|
|
554
|
+
flags[name] = ms;
|
|
555
|
+
} else flags[name] = value;
|
|
556
|
+
i += 1;
|
|
557
|
+
} else throw new UsageError(`unknown flag --${name}`);
|
|
558
|
+
}
|
|
559
|
+
return { flags, positionals };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
563
|
+
|
|
564
|
+
async function main() {
|
|
565
|
+
const usage = 'usage: overnight.mjs <schedule|status|cancel> [--dir <repo>] · schedule [--force-resume] [--prompt <t>] [--cmd <exe>] · cancel [--clear]';
|
|
566
|
+
let parsed;
|
|
567
|
+
try {
|
|
568
|
+
parsed = parseArgs(process.argv.slice(2));
|
|
569
|
+
} catch (err) {
|
|
570
|
+
console.error(`overnight: ${err.message}`);
|
|
571
|
+
console.error(usage);
|
|
572
|
+
process.exit(2);
|
|
573
|
+
}
|
|
574
|
+
const { flags, positionals } = parsed;
|
|
575
|
+
const repo = resolve(typeof flags.dir === 'string' ? flags.dir : process.cwd());
|
|
576
|
+
const command = flags.wait === true ? '--wait' : positionals[0];
|
|
577
|
+
if (command === 'schedule') return doSchedule(repo, flags);
|
|
578
|
+
if (command === '--wait') return doWait(repo, flags);
|
|
579
|
+
if (command === 'status') return doStatus(repo);
|
|
580
|
+
if (command === 'cancel') return doCancel(repo, flags);
|
|
581
|
+
console.error(usage);
|
|
582
|
+
process.exit(2);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function canonicalPath(path) {
|
|
586
|
+
const abs = resolve(path);
|
|
587
|
+
try {
|
|
588
|
+
return realpathSync(abs);
|
|
589
|
+
} catch {
|
|
590
|
+
return abs;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function isMainModule(moduleUrl) {
|
|
595
|
+
if (!process.argv[1]) return false;
|
|
596
|
+
return canonicalPath(process.argv[1]) === canonicalPath(fileURLToPath(moduleUrl));
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
if (isMainModule(import.meta.url)) await main();
|