@jjanczur/tyran 0.1.13 → 0.1.14
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 +88 -0
- package/README.md +5 -0
- package/agents/retro.md +17 -2
- package/bin/tyran.mjs +4 -0
- package/package.json +1 -1
- package/scripts/doctor.mjs +108 -0
- package/scripts/keepawake.mjs +187 -0
- package/scripts/mistakes.mjs +1005 -0
- package/scripts/overnight.mjs +88 -3
- package/scripts/scan-repo.mjs +101 -1
- package/scripts/schema.mjs +10 -1
- package/skills/retro/SKILL.md +80 -1
- package/skills/run/SKILL.md +6 -1
- package/skills/setup/SKILL.md +27 -1
- package/templates/MISTAKES.md +39 -0
- package/templates/config.yaml +5 -0
- package/templates/policies/autonomy.yaml +18 -0
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
{
|
|
12
12
|
"name": "tyran",
|
|
13
13
|
"description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
|
|
14
|
-
"version": "0.1.
|
|
14
|
+
"version": "0.1.14",
|
|
15
15
|
"source": "./",
|
|
16
16
|
"author": {
|
|
17
17
|
"name": "Jacek Janczura",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tyran",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
4
4
|
"description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Jacek Janczura",
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,93 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.14 — 2026-08-14
|
|
4
|
+
|
|
5
|
+
### The repository remembers what went wrong — and eventually writes it into law
|
|
6
|
+
|
|
7
|
+
Tyran had three places a lesson could land and not one of them answered *how
|
|
8
|
+
often*. A journal `finding` dies with its initiative, correctly: it is that
|
|
9
|
+
run's discovery. A `.tyran/knowledge/` entry says what an agent must know
|
|
10
|
+
before touching a path. `CLAUDE.md` is law. Recurrence was counted nowhere, so
|
|
11
|
+
"this has burned us three times" was something a human had to remember, and on
|
|
12
|
+
the fourth time it was argued from scratch.
|
|
13
|
+
|
|
14
|
+
`MISTAKES.md` at your repository root is the store that was missing: what
|
|
15
|
+
happened, the root cause, the consequence, the prevention — newest first, plain
|
|
16
|
+
prose, yours to edit. The retrospective is its only writer, and it writes an
|
|
17
|
+
entry only for a breakage the initiative actually paid for. Every entry carries
|
|
18
|
+
a **signature**, and the signature is the whole point: the model decides
|
|
19
|
+
whether two failures are the *same* failure, and `scripts/mistakes.mjs`
|
|
20
|
+
(`add` · `repeats` · `promote`) does the counting.
|
|
21
|
+
|
|
22
|
+
**Three open entries under one signature** graduate the lesson into
|
|
23
|
+
`.tyran/knowledge/`, where every handoff touching those paths already delivers
|
|
24
|
+
it. **Five, still recurring after the knowledge entry shipped**, is evidence
|
|
25
|
+
the delivered rule was not enough — the strongest argument for law there is —
|
|
26
|
+
and at five `mistakes.mjs promote --law` **writes the rule into your
|
|
27
|
+
`CLAUDE.md`**. Not a proposal, not a queue: an autonomous write, between
|
|
28
|
+
`<!-- tyran:rules start -->` and `<!-- tyran:rules end -->` and never a byte
|
|
29
|
+
outside those markers. The line names the rule, its signature and the dated
|
|
30
|
+
entries that earned it; a `decision` event records the act; `--dry-run` prints
|
|
31
|
+
the line and writes nothing. You say no by deleting the line — the entries are
|
|
32
|
+
already at status `law`, so nothing puts it back. A fence that is absent is
|
|
33
|
+
appended once at the end, with its heading, and existing prose is never
|
|
34
|
+
reflowed; a fence that is malformed is refused by name, with nothing written.
|
|
35
|
+
|
|
36
|
+
The safety story is a boundary rather than a sentence. The shipped policy now
|
|
37
|
+
classes `CLAUDE.md` as **GATED**, which bans the hand and not the mechanism: a
|
|
38
|
+
subagent's free-hand `Write` is denied, while the script that demands five
|
|
39
|
+
recorded occurrences passes. Until this rule, the gate was silent on repo-root
|
|
40
|
+
files — its governed namespace is `.tyran/`, `.claude/` and the enforcement
|
|
41
|
+
scripts — so a subagent could rewrite the law it was bound by and nothing had
|
|
42
|
+
an opinion. An explicit rule outranks that namespace test, which is why one
|
|
43
|
+
line is enough. Seeding has always been create-only, so existing installs keep
|
|
44
|
+
their own policy untouched.
|
|
45
|
+
|
|
46
|
+
Seeding `MISTAKES.md` is create-only too, and **deleting the file is the whole
|
|
47
|
+
opt-out** — no knob for a file you can remove. `doctor --state` grew three
|
|
48
|
+
codes, 54 → **57**: `mistakes-repeat-unpromoted` (info — a lesson has earned
|
|
49
|
+
promotion), `mistakes-unreadable` (warning), and `claude-md-fence-missing`
|
|
50
|
+
(info — entries claim `law` but no fence exists to hold the rule). An absent
|
|
51
|
+
ledger is never a finding.
|
|
52
|
+
|
|
53
|
+
Stated rather than discovered: `MISTAKES.md` is **authored, not a byte-checked
|
|
54
|
+
projection**. A projection would report a hand edit as drift and destroy it on
|
|
55
|
+
the next render, and a human correcting a wrong root cause is the most valuable
|
|
56
|
+
edit this file will ever get. The cost is that nothing compares it to the
|
|
57
|
+
journal, so it can drift. Every entry cites its initiative and the event id
|
|
58
|
+
that proves it, which makes drift auditable by a human and **not** enforced by
|
|
59
|
+
a gate — a weaker guarantee than the projections carry, and both docs surfaces
|
|
60
|
+
say so instead of leaving you to assume parity.
|
|
61
|
+
|
|
62
|
+
This repository ships its own `MISTAKES.md`, five entries, one of them earned
|
|
63
|
+
during this release: the control-character write-guard refused an edit twice
|
|
64
|
+
because the editing tool turns `\uXXXX` escape text into the character itself,
|
|
65
|
+
so a regex class typed as escapes reached disk as raw C0 and bidi codepoints.
|
|
66
|
+
The guard was working; the author was the attacker.
|
|
67
|
+
|
|
68
|
+
### Keep the machine awake while the watcher waits
|
|
69
|
+
|
|
70
|
+
The overnight resume watcher's whole job is to be asleep for hours, which is
|
|
71
|
+
exactly the interval a laptop chooses to suspend in — and a suspended machine
|
|
72
|
+
takes the watcher and the network with it. `limits.keep_awake` (a real boolean,
|
|
73
|
+
default `false`) wraps the wait in a system-sleep inhibitor: `caffeinate -is`
|
|
74
|
+
on macOS, `systemd-inhibit --what=idle:sleep` on Linux. **Never `caffeinate
|
|
75
|
+
-d`**: that blocks the display sleep and with it the screen lock, and a machine
|
|
76
|
+
left running overnight that never locks is a security regression. The inhibitor
|
|
77
|
+
is released on every exit path including `SIGINT` and `SIGTERM`, an unsupported
|
|
78
|
+
platform degrades to a no-op instead of refusing to wait, and
|
|
79
|
+
`overnight.mjs schedule` tells you which way the knob is set — as a warning,
|
|
80
|
+
never a refusal.
|
|
81
|
+
|
|
82
|
+
### Measured
|
|
83
|
+
|
|
84
|
+
`node --test "tests/**/*.test.mjs"`: **1133 unit tests, 0 failures** — 34 of
|
|
85
|
+
them new in `tests/unit/mistakes.test.mjs` (the entry format, the counting
|
|
86
|
+
thresholds, the fence, and every refusal), 11 in `keepawake.test.mjs`.
|
|
87
|
+
`scan-control-chars`: clean over 185 tracked text files. The skill description
|
|
88
|
+
budget is unchanged at **4352 / 5000** — this release adds no skill and no
|
|
89
|
+
agent.
|
|
90
|
+
|
|
3
91
|
## 0.1.13 — 2026-08-13
|
|
4
92
|
|
|
5
93
|
### Six concurrent decisions, two ids
|
package/README.md
CHANGED
|
@@ -443,6 +443,11 @@ underlying script does.
|
|
|
443
443
|
- [x] Read-only dashboard: the kanban board — `BOARD.md`/`board.json` next to
|
|
444
444
|
every journal, one cross-initiative `board.html` in the landing page's
|
|
445
445
|
own palette, refreshed on every subagent stop, plus `board.mjs --serve`
|
|
446
|
+
- [x] The mistakes ledger: `MISTAKES.md` at your repo root — what went wrong
|
|
447
|
+
here and how often — where three occurrences of one signature graduate a
|
|
448
|
+
lesson into `.tyran/knowledge/` and five write a rule into your
|
|
449
|
+
`CLAUDE.md`, inside Tyran's own fence — see
|
|
450
|
+
[docs/self-improvement.md](docs/self-improvement.md)
|
|
446
451
|
|
|
447
452
|
## Where this came from
|
|
448
453
|
|
package/agents/retro.md
CHANGED
|
@@ -21,6 +21,10 @@ to disk is in English.**
|
|
|
21
21
|
--ev finding`) — the claims agents recorded WITH proof, mid-run. Promote
|
|
22
22
|
the recurring ones into `.tyran/knowledge/` through the filter below; the
|
|
23
23
|
rest die with the initiative, which is correct.
|
|
24
|
+
Alongside them, `MISTAKES.md` at the repository root — the durable record of
|
|
25
|
+
what has gone WRONG here, newest first. You are its only writer: read it
|
|
26
|
+
before you decide anything, so a candidate that has already burned this repo
|
|
27
|
+
repeatedly is recognised as evidence rather than argued about again.
|
|
24
28
|
3. `git log` for the initiative: reverts, fixes of your own regressions,
|
|
25
29
|
repeated phases.
|
|
26
30
|
4. The current state of `skills/`, `agents/`, `scripts/` and the docs — **so
|
|
@@ -69,11 +73,22 @@ next retro relitigating the same idea.
|
|
|
69
73
|
report generators. A one-off harness from an initiative either becomes a
|
|
70
74
|
general tool or gets deleted; do not leave dead files behind.
|
|
71
75
|
- **Knowledge upkeep:** fold the reports' knowledge-brief verdicts into the
|
|
72
|
-
entries' counters (the fold procedure lives in `skills/retro/SKILL.md`,
|
|
73
|
-
|
|
76
|
+
entries' counters (the fold procedure lives in `skills/retro/SKILL.md`, under
|
|
77
|
+
"Write down what is true about THIS repo" — one home, not two), and retire or
|
|
78
|
+
split entries
|
|
74
79
|
`doctor --state` flags as `knowledge-entry-oversized`. An entry whose
|
|
75
80
|
counters say it stopped earning its keep is a deletion candidate, which
|
|
76
81
|
satisfies the deletion preference.
|
|
82
|
+
- **The mistakes ledger:** append an entry to `MISTAKES.md` for every breakage
|
|
83
|
+
this initiative actually paid for — what happened, the root cause, the
|
|
84
|
+
consequence, the prevention — and give it a **signature** you reuse for the
|
|
85
|
+
same failure rather than a near-synonym, because the signature is what makes
|
|
86
|
+
recurrence countable. Then promote what recurred: `mistakes.mjs repeats` says
|
|
87
|
+
which signatures crossed a graduation threshold and what each one has earned
|
|
88
|
+
— a `.tyran/knowledge/` entry, or a line you write into the `tyran:rules`
|
|
89
|
+
fence of the host `CLAUDE.md`. A discovery is not a mistake; if nothing
|
|
90
|
+
broke, write nothing. The procedure is the step of `skills/retro/SKILL.md`
|
|
91
|
+
that folds breakages into `MISTAKES.md` — one home, not two.
|
|
77
92
|
- **Documentation that pays forward:** the repo's detected configuration,
|
|
78
93
|
protocols, runbooks. **Every initiative should leave the repo better
|
|
79
94
|
described than it found it** — that is the part that makes each next
|
package/bin/tyran.mjs
CHANGED
|
@@ -72,6 +72,10 @@ export const COMMANDS = {
|
|
|
72
72
|
'knowledge.mjs',
|
|
73
73
|
'Select the knowledge entries that apply to a set of paths and print a paste-ready brief for a handoff.',
|
|
74
74
|
],
|
|
75
|
+
mistakes: [
|
|
76
|
+
'mistakes.mjs',
|
|
77
|
+
"Append to the repository's MISTAKES.md, count recurring signatures, and promote a recurring one into CLAUDE.md.",
|
|
78
|
+
],
|
|
75
79
|
overnight: [
|
|
76
80
|
'overnight.mjs',
|
|
77
81
|
'Schedule and run the usage-limit resume watcher: wait for the window reset, then resume the paused session.',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jjanczur/tyran",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
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": {
|
package/scripts/doctor.mjs
CHANGED
|
@@ -52,6 +52,7 @@ import {
|
|
|
52
52
|
} from './project.mjs';
|
|
53
53
|
import { classifyPath, normalizePath, validateFile, knowledgeWarnings, MANDATORY_KERNEL_PATHS } from './schema.mjs';
|
|
54
54
|
import { gitRunner } from './scan-repo.mjs';
|
|
55
|
+
import { parseMistakes, countSignatures, fenceState, KNOWLEDGE_THRESHOLD, MISTAKES_FILE, CLAUDE_MD_FILE } from './mistakes.mjs';
|
|
55
56
|
|
|
56
57
|
/** Severity order is also the report order. `info` never fails the check. */
|
|
57
58
|
export const SEVERITIES = Object.freeze(['error', 'warning', 'info']);
|
|
@@ -200,6 +201,17 @@ export const SEVERITY_BY_CODE = Object.freeze(
|
|
|
200
201
|
'state-stray-file': 'warning',
|
|
201
202
|
'state-legacy-initiatives-dir': 'warning',
|
|
202
203
|
'lease-file-tracked': 'warning',
|
|
204
|
+
// the mistakes ledger. `mistakes-unreadable` is a WARNING, not the `error`
|
|
205
|
+
// that `knowledge-unreadable` and `config-unreadable` carry: nothing
|
|
206
|
+
// mechanical consumes MISTAKES.md at write time, so an unreadable one
|
|
207
|
+
// degrades learning without stopping work, and exiting 1 on it would be a
|
|
208
|
+
// false alarm about a repository that is fine. The other two are `info`
|
|
209
|
+
// for the same reason `spawn-open` is: a warning would go red on every
|
|
210
|
+
// healthy repo between a breakage and its next retro, and a check that is
|
|
211
|
+
// red during normal operation is a check people learn to skip.
|
|
212
|
+
'mistakes-unreadable': 'warning',
|
|
213
|
+
'mistakes-repeat-unpromoted': 'info',
|
|
214
|
+
'claude-md-fence-missing': 'info',
|
|
203
215
|
// overnight mode
|
|
204
216
|
'limit-pause-active': 'info',
|
|
205
217
|
'limit-pause-stale': 'warning',
|
|
@@ -1113,6 +1125,98 @@ export function trackedLeaseFiles(run, tyranDirName = '.tyran') {
|
|
|
1113
1125
|
return listing.split('\n').filter((line) => line !== '' && lease.test(line));
|
|
1114
1126
|
}
|
|
1115
1127
|
|
|
1128
|
+
/**
|
|
1129
|
+
* The mistakes ledger at the repository root: is it readable, has a lesson
|
|
1130
|
+
* earned promotion, and can a promoted rule actually land?
|
|
1131
|
+
*
|
|
1132
|
+
* ABSENCE PRODUCES NO FINDING AT ALL. Deleting the file is the documented
|
|
1133
|
+
* opt-out, and a tool that nags about a file you deliberately removed is a
|
|
1134
|
+
* tool you disable. The `checked` line still records what was looked at, so
|
|
1135
|
+
* "nothing was said about it" and "it is not there" stay distinguishable.
|
|
1136
|
+
*
|
|
1137
|
+
* `parseMistakes` is imported rather than re-implemented: the entry shape is
|
|
1138
|
+
* owned by `mistakes.mjs`, the same discipline doctor already follows for
|
|
1139
|
+
* `validateKnowledge` and `pairSpawns` (ADR-18).
|
|
1140
|
+
*/
|
|
1141
|
+
export function mistakesFindings(repoRoot) {
|
|
1142
|
+
const path = join(repoRoot, MISTAKES_FILE);
|
|
1143
|
+
if (!existsSync(path)) return { findings: [], checked: `${MISTAKES_FILE}: absent` };
|
|
1144
|
+
|
|
1145
|
+
let parsed;
|
|
1146
|
+
try {
|
|
1147
|
+
parsed = parseMistakes(readFileSync(path, 'utf8'));
|
|
1148
|
+
} catch (err) {
|
|
1149
|
+
return {
|
|
1150
|
+
findings: [
|
|
1151
|
+
finding(
|
|
1152
|
+
'mistakes-unreadable',
|
|
1153
|
+
show(path),
|
|
1154
|
+
`the mistakes ledger could not be read or parsed (${errText(err)}) — nothing in it was counted`,
|
|
1155
|
+
`ls -la ${sq(path)} # this file is prose, not a projection: open it and repair it by hand`,
|
|
1156
|
+
),
|
|
1157
|
+
],
|
|
1158
|
+
checked: `${MISTAKES_FILE}: UNREADABLE`,
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
const findings = [];
|
|
1163
|
+
const rows = countSignatures(parsed.entries);
|
|
1164
|
+
for (const row of rows) {
|
|
1165
|
+
if (row.open < KNOWLEDGE_THRESHOLD) continue;
|
|
1166
|
+
findings.push(
|
|
1167
|
+
finding(
|
|
1168
|
+
'mistakes-repeat-unpromoted',
|
|
1169
|
+
show(path),
|
|
1170
|
+
`\`${show(row.signature)}\` has ${row.open} open entries (${show(row.dates.join(', '))}) — ` +
|
|
1171
|
+
'a failure that recurred this often is evidence a rule is missing, not a coincidence',
|
|
1172
|
+
`node scripts/mistakes.mjs repeats --file ${sq(path)} --threshold ${KNOWLEDGE_THRESHOLD} # then /tyran:retro promotes them into .tyran/knowledge/`,
|
|
1173
|
+
),
|
|
1174
|
+
);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// A law entry says a rule was earned; the fence is where such a rule lives.
|
|
1178
|
+
// Info in both directions: a repo whose law predates the fence is fine, and
|
|
1179
|
+
// a repo that has never promoted anything must never see this at all.
|
|
1180
|
+
const lawEntries = parsed.entries.filter((entry) => entry.statusKind === 'law').length;
|
|
1181
|
+
if (lawEntries > 0) {
|
|
1182
|
+
const claudePath = join(repoRoot, CLAUDE_MD_FILE);
|
|
1183
|
+
let state = { start: null, problem: null };
|
|
1184
|
+
let claudeExists = existsSync(claudePath);
|
|
1185
|
+
if (claudeExists) {
|
|
1186
|
+
try {
|
|
1187
|
+
state = fenceState(readFileSync(claudePath, 'utf8'));
|
|
1188
|
+
} catch {
|
|
1189
|
+
claudeExists = false;
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
if (!claudeExists || state.problem !== null || state.start === null) {
|
|
1193
|
+
// The two branches fail differently, so they say different things: a
|
|
1194
|
+
// missing fence is written by the next promotion (writeRuleToFence
|
|
1195
|
+
// creates it), a malformed one refuses every promotion until it is
|
|
1196
|
+
// repaired by hand.
|
|
1197
|
+
const why = state.problem !== null
|
|
1198
|
+
? `the tyran:rules fence is malformed (${show(state.problem)}) — ` +
|
|
1199
|
+
'the next promotion cannot land where an earned rule is supposed to live'
|
|
1200
|
+
: `${CLAUDE_MD_FILE} carries no tyran:rules fence — ` +
|
|
1201
|
+
'the earned rule is not in force in any session';
|
|
1202
|
+
findings.push(
|
|
1203
|
+
finding(
|
|
1204
|
+
'claude-md-fence-missing',
|
|
1205
|
+
show(claudePath),
|
|
1206
|
+
`${lawEntries} entr${lawEntries === 1 ? 'y' : 'ies'} in ${MISTAKES_FILE} ` +
|
|
1207
|
+
`claim${lawEntries === 1 ? 's' : ''} status \`law\`, and ${why}`,
|
|
1208
|
+
`node scripts/mistakes.mjs repeats --file ${sq(path)} # see docs/self-improvement.md for the fence`,
|
|
1209
|
+
),
|
|
1210
|
+
);
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
return {
|
|
1215
|
+
findings,
|
|
1216
|
+
checked: `${MISTAKES_FILE}: ${parsed.entries.length} entries, ${rows.length} signatures`,
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1116
1220
|
/** The repo-global overnight runtime files that legally live at state/ level. */
|
|
1117
1221
|
/** The cross-initiative board artefacts board.mjs writes at state/ level. */
|
|
1118
1222
|
export const CROSS_BOARD_FILES = Object.freeze(['BOARD.md', 'board.json', 'board.html']);
|
|
@@ -1379,6 +1483,10 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
|
|
|
1379
1483
|
}
|
|
1380
1484
|
checked.push(`initiatives/ (legacy): ${isDirectory(legacyDir) ? 'PRESENT' : 'absent'}`);
|
|
1381
1485
|
|
|
1486
|
+
const mistakes = mistakesFindings(repoRoot);
|
|
1487
|
+
findings.push(...mistakes.findings);
|
|
1488
|
+
checked.push(mistakes.checked);
|
|
1489
|
+
|
|
1382
1490
|
findings.push(...overnightFindings(dir, { now, configDoc }));
|
|
1383
1491
|
checked.push('overnight: checked');
|
|
1384
1492
|
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* keepawake — hold the SYSTEM awake for as long as a Tyran watcher is waiting.
|
|
3
|
+
*
|
|
4
|
+
* The measured failure: a laptop whose screensaver starts at five minutes
|
|
5
|
+
* suspends, the network goes with it, and the running session dies mid-task
|
|
6
|
+
* with an API error. The overnight resume watcher is the worst case — its
|
|
7
|
+
* whole job is to be asleep for hours waiting for a usage window to reset,
|
|
8
|
+
* which is exactly the interval a machine chooses to suspend in.
|
|
9
|
+
*
|
|
10
|
+
* Three constraints shape every line here.
|
|
11
|
+
*
|
|
12
|
+
* - **System sleep only, never the display.** `caffeinate -d` would also
|
|
13
|
+
* block the screen lock, and a machine left running overnight that never
|
|
14
|
+
* locks is a security regression. `-i` is idle sleep, `-s` is sleep while
|
|
15
|
+
* on AC power; the display and the lock stay exactly as the operator set
|
|
16
|
+
* them. The platforms are NOT symmetric behind this one knob, and the
|
|
17
|
+
* difference is documented rather than papered over: macOS still honours
|
|
18
|
+
* an explicit sleep request, while a logind `block` lock refuses the
|
|
19
|
+
* operator's own deliberate suspend too (see `inhibitorArgv`, and the
|
|
20
|
+
* `limits.keep_awake` section of docs/overnight.md).
|
|
21
|
+
* - **A leak is worse than a no-op.** An inhibitor that outlives its reason
|
|
22
|
+
* keeps someone's laptop awake indefinitely. So: the child is `unref`'d
|
|
23
|
+
* (it can never hold this process open), it is released on every exit path
|
|
24
|
+
* including SIGINT/SIGTERM, and the release is idempotent. SIGKILL is the
|
|
25
|
+
* one signal nothing can catch — stated in docs/overnight.md rather than
|
|
26
|
+
* pretended away.
|
|
27
|
+
* - **Degrade silently, never refuse.** An unsupported platform, a missing
|
|
28
|
+
* binary or a failed spawn returns a no-op release. Keeping the machine
|
|
29
|
+
* awake is an optimization on the real work; it is never a precondition
|
|
30
|
+
* for it, and it must never be the reason a run fails to start.
|
|
31
|
+
*
|
|
32
|
+
* Nothing foreign ever reaches the child: the command is an argv ARRAY, never
|
|
33
|
+
* a shell string, and `--why` is a module constant rather than an operator's,
|
|
34
|
+
* a config's or a pause marker's words.
|
|
35
|
+
*/
|
|
36
|
+
import { spawn } from 'node:child_process';
|
|
37
|
+
|
|
38
|
+
/** Our own words, deliberately: the only free text the child ever sees. */
|
|
39
|
+
export const KEEP_AWAKE_REASON = 'Tyran is waiting for a usage-limit window to reset';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* systemd-inhibit holds its lock only while its COMMAND runs, so it needs one.
|
|
43
|
+
* POSIX `sleep` takes an integer — GNU's `sleep infinity` is not portable to
|
|
44
|
+
* every userland systemd ships on, and an inhibitor whose command exits at
|
|
45
|
+
* once is a lock nobody is holding. 2^31-1 seconds is ~68 years.
|
|
46
|
+
*/
|
|
47
|
+
export const INHIBIT_SLEEP_SECONDS = '2147483647';
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Signals we release on. Each handler re-raises after releasing, so a caller's
|
|
51
|
+
* `kill` still kills: overnight's `cancel` SIGTERMs the watcher and expects it
|
|
52
|
+
* to die, and a handler that only cleaned up would make it unkillable.
|
|
53
|
+
*/
|
|
54
|
+
const RELEASE_SIGNALS = Object.freeze(['SIGINT', 'SIGTERM', 'SIGHUP']);
|
|
55
|
+
|
|
56
|
+
const NOOP_RELEASE = () => {};
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The inhibitor command for a platform, or `null` where no mechanism exists.
|
|
60
|
+
* Pure — the platform matrix is decidable without spawning anything.
|
|
61
|
+
*/
|
|
62
|
+
export function inhibitorArgv(platform = process.platform) {
|
|
63
|
+
// -i: no idle sleep. -s: no sleep while on AC power. NEVER -d: that is the
|
|
64
|
+
// DISPLAY, and blocking it blocks the screen lock.
|
|
65
|
+
if (platform === 'darwin') return ['caffeinate', '-i', '-s'];
|
|
66
|
+
if (platform === 'linux') {
|
|
67
|
+
// `sleep` is not droppable: GNOME's automatic suspend goes through
|
|
68
|
+
// logind's Suspend(), which only a `sleep` lock stops — `idle` alone
|
|
69
|
+
// would leave the laptop suspending on its own timer. The cost is that
|
|
70
|
+
// `block` refuses the operator's DELIBERATE suspend as well (lid close,
|
|
71
|
+
// `systemctl suspend`), which is stated in docs/overnight.md rather than
|
|
72
|
+
// engineered around: `delay` merely postpones by InhibitDelayMaxSec and
|
|
73
|
+
// then lets the machine go, and `block-weak` (systemd 255+) exempts
|
|
74
|
+
// privileged callers — logind itself — so it would not stop the
|
|
75
|
+
// automatic suspend this exists for. `cancel` releases the lock at once.
|
|
76
|
+
return [
|
|
77
|
+
'systemd-inhibit',
|
|
78
|
+
'--what=idle:sleep',
|
|
79
|
+
`--why=${KEEP_AWAKE_REASON}`,
|
|
80
|
+
'--mode=block',
|
|
81
|
+
'sleep',
|
|
82
|
+
INHIBIT_SLEEP_SECONDS,
|
|
83
|
+
];
|
|
84
|
+
}
|
|
85
|
+
// Windows and everything else: no mechanism, and that is not an error.
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function note(onNote, message) {
|
|
90
|
+
if (typeof onNote !== 'function') return;
|
|
91
|
+
try {
|
|
92
|
+
onNote(message);
|
|
93
|
+
} catch {
|
|
94
|
+
/* a note is a courtesy; its failure must not reach the caller */
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Acquire the inhibitor and return the function that releases it.
|
|
100
|
+
*
|
|
101
|
+
* ALWAYS returns a function — off, unsupported, or failed all return a no-op,
|
|
102
|
+
* so a caller's `finally` needs no null check and can never crash on the path
|
|
103
|
+
* where the machine was already going to be fine.
|
|
104
|
+
*
|
|
105
|
+
* `argv` and `spawnFn` are injection points for tests only. Neither is
|
|
106
|
+
* reachable from any CLI: nothing constructs them from a file, a flag or an
|
|
107
|
+
* environment variable.
|
|
108
|
+
*/
|
|
109
|
+
export function keepAwake({ enabled = false, platform = process.platform, argv = null, spawnFn = spawn, onNote = null } = {}) {
|
|
110
|
+
// Strict true: a knob that changes the operator's machine is never enabled
|
|
111
|
+
// by a truthy string that drifted in from a parser.
|
|
112
|
+
if (enabled !== true) return NOOP_RELEASE;
|
|
113
|
+
|
|
114
|
+
const command = argv ?? inhibitorArgv(platform);
|
|
115
|
+
if (command === null) {
|
|
116
|
+
note(onNote, `keep-awake: no inhibitor on ${platform} — this machine may still sleep and take the run with it`);
|
|
117
|
+
return NOOP_RELEASE;
|
|
118
|
+
}
|
|
119
|
+
note(
|
|
120
|
+
onNote,
|
|
121
|
+
`keep-awake: holding the system awake with ${command[0]} — the display and the screen lock are untouched`,
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
let child;
|
|
125
|
+
try {
|
|
126
|
+
child = spawnFn(command[0], command.slice(1), {
|
|
127
|
+
// Never the caller's stdio: the watcher's log is a record, not a pipe.
|
|
128
|
+
stdio: 'ignore',
|
|
129
|
+
// The argv above is the whole command. No shell, ever.
|
|
130
|
+
shell: false,
|
|
131
|
+
});
|
|
132
|
+
} catch {
|
|
133
|
+
// Silent degrade: the work matters, the inhibitor does not.
|
|
134
|
+
return NOOP_RELEASE;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// spawn reports a MISSING BINARY asynchronously, as an 'error' event. With
|
|
138
|
+
// no listener that event is thrown and takes the watcher down — a machine
|
|
139
|
+
// without caffeinate would lose the very run this exists to protect.
|
|
140
|
+
if (typeof child?.on === 'function') child.on('error', () => {});
|
|
141
|
+
// The inhibitor must never be the reason this process is still alive.
|
|
142
|
+
if (typeof child?.unref === 'function') child.unref();
|
|
143
|
+
|
|
144
|
+
const handlers = new Map();
|
|
145
|
+
let released = false;
|
|
146
|
+
const release = () => {
|
|
147
|
+
if (released) return; // idempotent: killing twice is harmless, by construction
|
|
148
|
+
released = true;
|
|
149
|
+
for (const [event, fn] of handlers) process.removeListener(event, fn);
|
|
150
|
+
handlers.clear();
|
|
151
|
+
try {
|
|
152
|
+
child.kill('SIGTERM');
|
|
153
|
+
} catch {
|
|
154
|
+
/* already gone, or never really there */
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
for (const signal of RELEASE_SIGNALS) {
|
|
159
|
+
const fn = () => {
|
|
160
|
+
release();
|
|
161
|
+
// release() removed this listener, so the default disposition is back:
|
|
162
|
+
// re-raising kills us exactly as it would have without the handler.
|
|
163
|
+
process.kill(process.pid, signal);
|
|
164
|
+
};
|
|
165
|
+
handlers.set(signal, fn);
|
|
166
|
+
process.on(signal, fn);
|
|
167
|
+
}
|
|
168
|
+
const onExit = () => release();
|
|
169
|
+
handlers.set('exit', onExit);
|
|
170
|
+
process.on('exit', onExit);
|
|
171
|
+
|
|
172
|
+
return release;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Run `fn` with the machine held awake. The release is in a `finally`, so it
|
|
177
|
+
* runs on the thrown path too — the path where a forgotten release would leave
|
|
178
|
+
* a laptop awake with nothing left to explain why.
|
|
179
|
+
*/
|
|
180
|
+
export async function withKeepAwake(options, fn) {
|
|
181
|
+
const release = keepAwake(options);
|
|
182
|
+
try {
|
|
183
|
+
return await fn();
|
|
184
|
+
} finally {
|
|
185
|
+
release();
|
|
186
|
+
}
|
|
187
|
+
}
|