@jjanczur/tyran 0.1.13 → 0.1.15
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 +135 -0
- package/README.md +7 -1
- package/agents/implementer.md +15 -3
- package/agents/retro.md +17 -2
- package/agents/reviewer.md +7 -0
- package/bin/tyran.mjs +8 -0
- package/hooks/scripts/session-start.mjs +69 -2
- package/package.json +1 -1
- package/scripts/answer.mjs +896 -0
- package/scripts/board.mjs +4 -1
- package/scripts/doctor.mjs +169 -0
- package/scripts/journal.mjs +79 -1
- package/scripts/keepawake.mjs +187 -0
- package/scripts/mistakes.mjs +1005 -0
- package/scripts/overnight.mjs +92 -5
- package/scripts/project.mjs +15 -3
- package/scripts/scan-repo.mjs +107 -1
- package/scripts/schema.mjs +10 -1
- package/scripts/tiers.mjs +17 -0
- package/skills/retro/SKILL.md +80 -1
- package/skills/run/SKILL.md +33 -7
- 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
package/scripts/board.mjs
CHANGED
|
@@ -98,7 +98,10 @@ export function readInitiativeBoards(tyranDir) {
|
|
|
98
98
|
errors.push({ name, error: `0 readable events and ${damage} — the journal is damaged` });
|
|
99
99
|
continue;
|
|
100
100
|
}
|
|
101
|
-
|
|
101
|
+
// `journal` is returned, not re-derived by consumers: answer.mjs writes
|
|
102
|
+
// to the file this function already located, so there is one rule for
|
|
103
|
+
// where an initiative's journal lives (ADR-21).
|
|
104
|
+
initiatives.push({ name, journal, state, board: boardOf(state) });
|
|
102
105
|
} catch (err) {
|
|
103
106
|
errors.push({ name, error: String(err?.message ?? err) });
|
|
104
107
|
}
|
package/scripts/doctor.mjs
CHANGED
|
@@ -41,7 +41,9 @@ import { fileURLToPath } from 'node:url';
|
|
|
41
41
|
import { checkHooks, DEFAULT_PLUGIN_ROOT } from './hooks-check.mjs';
|
|
42
42
|
import { readJournal, validateJournal, pairSpawns, tail } from './journal.mjs';
|
|
43
43
|
import {
|
|
44
|
+
boardOf,
|
|
44
45
|
checkFile,
|
|
46
|
+
fold,
|
|
45
47
|
inline,
|
|
46
48
|
naturalCompare,
|
|
47
49
|
renderProjections,
|
|
@@ -52,6 +54,7 @@ import {
|
|
|
52
54
|
} from './project.mjs';
|
|
53
55
|
import { classifyPath, normalizePath, validateFile, knowledgeWarnings, MANDATORY_KERNEL_PATHS } from './schema.mjs';
|
|
54
56
|
import { gitRunner } from './scan-repo.mjs';
|
|
57
|
+
import { parseMistakes, countSignatures, fenceState, KNOWLEDGE_THRESHOLD, MISTAKES_FILE, CLAUDE_MD_FILE } from './mistakes.mjs';
|
|
55
58
|
|
|
56
59
|
/** Severity order is also the report order. `info` never fails the check. */
|
|
57
60
|
export const SEVERITIES = Object.freeze(['error', 'warning', 'info']);
|
|
@@ -160,6 +163,9 @@ export const SEVERITY_BY_CODE = Object.freeze(
|
|
|
160
163
|
'spawn-duplicate': 'warning',
|
|
161
164
|
'spawn-orphan-report': 'warning',
|
|
162
165
|
'agent-name-unusable': 'warning',
|
|
166
|
+
// operator asks
|
|
167
|
+
'ask-open': 'info',
|
|
168
|
+
'ask-stale': 'warning',
|
|
163
169
|
// leases
|
|
164
170
|
'lease-open': 'info',
|
|
165
171
|
'lease-orphan': 'warning',
|
|
@@ -200,6 +206,17 @@ export const SEVERITY_BY_CODE = Object.freeze(
|
|
|
200
206
|
'state-stray-file': 'warning',
|
|
201
207
|
'state-legacy-initiatives-dir': 'warning',
|
|
202
208
|
'lease-file-tracked': 'warning',
|
|
209
|
+
// the mistakes ledger. `mistakes-unreadable` is a WARNING, not the `error`
|
|
210
|
+
// that `knowledge-unreadable` and `config-unreadable` carry: nothing
|
|
211
|
+
// mechanical consumes MISTAKES.md at write time, so an unreadable one
|
|
212
|
+
// degrades learning without stopping work, and exiting 1 on it would be a
|
|
213
|
+
// false alarm about a repository that is fine. The other two are `info`
|
|
214
|
+
// for the same reason `spawn-open` is: a warning would go red on every
|
|
215
|
+
// healthy repo between a breakage and its next retro, and a check that is
|
|
216
|
+
// red during normal operation is a check people learn to skip.
|
|
217
|
+
'mistakes-unreadable': 'warning',
|
|
218
|
+
'mistakes-repeat-unpromoted': 'info',
|
|
219
|
+
'claude-md-fence-missing': 'info',
|
|
203
220
|
// overnight mode
|
|
204
221
|
'limit-pause-active': 'info',
|
|
205
222
|
'limit-pause-stale': 'warning',
|
|
@@ -500,6 +517,7 @@ function checkInitiative(stateDir, name, { now, staleHours }) {
|
|
|
500
517
|
guard('journal integrity', () => journalIntegrity(journalPath, at, read));
|
|
501
518
|
guard('one initiative per file', () => initiativeScope(journalPath, at, name, events));
|
|
502
519
|
guard('open spawns', () => spawnFindings(journalPath, at, name, events, reference, staleHours));
|
|
520
|
+
guard('operator asks', () => askFindings(journalPath, at, read, reference));
|
|
503
521
|
guard('leases', () => leaseFindings(journalPath, at, events, reference));
|
|
504
522
|
guard('projections', () => projectionFindings(journalPath, dir, at, read));
|
|
505
523
|
|
|
@@ -748,6 +766,53 @@ function spawnFindings(journalPath, at, dirName, events, reference, staleHours)
|
|
|
748
766
|
return findings;
|
|
749
767
|
}
|
|
750
768
|
|
|
769
|
+
/**
|
|
770
|
+
* How long an operator ask may stand before it is a finding. A module
|
|
771
|
+
* constant, not a config key: the threshold is measured in journal time and
|
|
772
|
+
* nobody has yet needed a different one.
|
|
773
|
+
*/
|
|
774
|
+
export const DEFAULT_ASK_STALE_HOURS = 72;
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* Questions waiting on a human. The queue is `boardOf`'s — the same one
|
|
778
|
+
* BOARD.md prints and `answer.mjs` closes — so doctor cannot disagree with
|
|
779
|
+
* the board about what is still open (ADR-18).
|
|
780
|
+
*
|
|
781
|
+
* Same reference clock as spawns: the journal's own last event unless `--now`
|
|
782
|
+
* says otherwise, which is what the SessionStart probe passes it for.
|
|
783
|
+
*/
|
|
784
|
+
function askFindings(journalPath, at, read, reference) {
|
|
785
|
+
const findings = [];
|
|
786
|
+
const { asks } = boardOf(fold(read));
|
|
787
|
+
// The trailer is a `#` comment, not a parenthetical: a fix string is pasted
|
|
788
|
+
// into a shell verbatim, and `(…)` is a subshell whose parse fails before
|
|
789
|
+
// anything runs — the operator gets a syntax error instead of the sheet.
|
|
790
|
+
const answerHint =
|
|
791
|
+
`node scripts/answer.mjs render --dir ${sq(dirname(dirname(dirname(resolve(journalPath)))))}` +
|
|
792
|
+
' # fill the answer: lines, then apply';
|
|
793
|
+
for (const ask of [...asks].sort((a, b) => naturalCompare(String(a.kind), String(b.kind)))) {
|
|
794
|
+
const question = ask.question == null ? '' : ` — "${show(ask.question)}"`;
|
|
795
|
+
const waited = reference === null || ask.since == null ? null : hoursBetween(String(ask.since), reference);
|
|
796
|
+
if (waited !== null && waited >= DEFAULT_ASK_STALE_HOURS) {
|
|
797
|
+
findings.push(
|
|
798
|
+
finding(
|
|
799
|
+
'ask-stale',
|
|
800
|
+
at,
|
|
801
|
+
`${show(ask.kind)} has been waiting on the operator for ${waited.toFixed(1)} h of journal time ` +
|
|
802
|
+
`(asked ${show(ask.since)}, journal now at ${show(reference)}; threshold ${DEFAULT_ASK_STALE_HOURS} h)` +
|
|
803
|
+
question,
|
|
804
|
+
answerHint,
|
|
805
|
+
),
|
|
806
|
+
);
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
findings.push(
|
|
810
|
+
finding('ask-open', at, `${show(ask.kind)} is waiting on the operator (asked ${show(ask.since)})${question}`, answerHint),
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
return findings;
|
|
814
|
+
}
|
|
815
|
+
|
|
751
816
|
const EXPIRY_KEYS = Object.freeze(['expires', 'expires_at', 'until']);
|
|
752
817
|
|
|
753
818
|
function leaseFindings(journalPath, at, events, reference) {
|
|
@@ -1113,6 +1178,98 @@ export function trackedLeaseFiles(run, tyranDirName = '.tyran') {
|
|
|
1113
1178
|
return listing.split('\n').filter((line) => line !== '' && lease.test(line));
|
|
1114
1179
|
}
|
|
1115
1180
|
|
|
1181
|
+
/**
|
|
1182
|
+
* The mistakes ledger at the repository root: is it readable, has a lesson
|
|
1183
|
+
* earned promotion, and can a promoted rule actually land?
|
|
1184
|
+
*
|
|
1185
|
+
* ABSENCE PRODUCES NO FINDING AT ALL. Deleting the file is the documented
|
|
1186
|
+
* opt-out, and a tool that nags about a file you deliberately removed is a
|
|
1187
|
+
* tool you disable. The `checked` line still records what was looked at, so
|
|
1188
|
+
* "nothing was said about it" and "it is not there" stay distinguishable.
|
|
1189
|
+
*
|
|
1190
|
+
* `parseMistakes` is imported rather than re-implemented: the entry shape is
|
|
1191
|
+
* owned by `mistakes.mjs`, the same discipline doctor already follows for
|
|
1192
|
+
* `validateKnowledge` and `pairSpawns` (ADR-18).
|
|
1193
|
+
*/
|
|
1194
|
+
export function mistakesFindings(repoRoot) {
|
|
1195
|
+
const path = join(repoRoot, MISTAKES_FILE);
|
|
1196
|
+
if (!existsSync(path)) return { findings: [], checked: `${MISTAKES_FILE}: absent` };
|
|
1197
|
+
|
|
1198
|
+
let parsed;
|
|
1199
|
+
try {
|
|
1200
|
+
parsed = parseMistakes(readFileSync(path, 'utf8'));
|
|
1201
|
+
} catch (err) {
|
|
1202
|
+
return {
|
|
1203
|
+
findings: [
|
|
1204
|
+
finding(
|
|
1205
|
+
'mistakes-unreadable',
|
|
1206
|
+
show(path),
|
|
1207
|
+
`the mistakes ledger could not be read or parsed (${errText(err)}) — nothing in it was counted`,
|
|
1208
|
+
`ls -la ${sq(path)} # this file is prose, not a projection: open it and repair it by hand`,
|
|
1209
|
+
),
|
|
1210
|
+
],
|
|
1211
|
+
checked: `${MISTAKES_FILE}: UNREADABLE`,
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
const findings = [];
|
|
1216
|
+
const rows = countSignatures(parsed.entries);
|
|
1217
|
+
for (const row of rows) {
|
|
1218
|
+
if (row.open < KNOWLEDGE_THRESHOLD) continue;
|
|
1219
|
+
findings.push(
|
|
1220
|
+
finding(
|
|
1221
|
+
'mistakes-repeat-unpromoted',
|
|
1222
|
+
show(path),
|
|
1223
|
+
`\`${show(row.signature)}\` has ${row.open} open entries (${show(row.dates.join(', '))}) — ` +
|
|
1224
|
+
'a failure that recurred this often is evidence a rule is missing, not a coincidence',
|
|
1225
|
+
`node scripts/mistakes.mjs repeats --file ${sq(path)} --threshold ${KNOWLEDGE_THRESHOLD} # then /tyran:retro promotes them into .tyran/knowledge/`,
|
|
1226
|
+
),
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// A law entry says a rule was earned; the fence is where such a rule lives.
|
|
1231
|
+
// Info in both directions: a repo whose law predates the fence is fine, and
|
|
1232
|
+
// a repo that has never promoted anything must never see this at all.
|
|
1233
|
+
const lawEntries = parsed.entries.filter((entry) => entry.statusKind === 'law').length;
|
|
1234
|
+
if (lawEntries > 0) {
|
|
1235
|
+
const claudePath = join(repoRoot, CLAUDE_MD_FILE);
|
|
1236
|
+
let state = { start: null, problem: null };
|
|
1237
|
+
let claudeExists = existsSync(claudePath);
|
|
1238
|
+
if (claudeExists) {
|
|
1239
|
+
try {
|
|
1240
|
+
state = fenceState(readFileSync(claudePath, 'utf8'));
|
|
1241
|
+
} catch {
|
|
1242
|
+
claudeExists = false;
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
if (!claudeExists || state.problem !== null || state.start === null) {
|
|
1246
|
+
// The two branches fail differently, so they say different things: a
|
|
1247
|
+
// missing fence is written by the next promotion (writeRuleToFence
|
|
1248
|
+
// creates it), a malformed one refuses every promotion until it is
|
|
1249
|
+
// repaired by hand.
|
|
1250
|
+
const why = state.problem !== null
|
|
1251
|
+
? `the tyran:rules fence is malformed (${show(state.problem)}) — ` +
|
|
1252
|
+
'the next promotion cannot land where an earned rule is supposed to live'
|
|
1253
|
+
: `${CLAUDE_MD_FILE} carries no tyran:rules fence — ` +
|
|
1254
|
+
'the earned rule is not in force in any session';
|
|
1255
|
+
findings.push(
|
|
1256
|
+
finding(
|
|
1257
|
+
'claude-md-fence-missing',
|
|
1258
|
+
show(claudePath),
|
|
1259
|
+
`${lawEntries} entr${lawEntries === 1 ? 'y' : 'ies'} in ${MISTAKES_FILE} ` +
|
|
1260
|
+
`claim${lawEntries === 1 ? 's' : ''} status \`law\`, and ${why}`,
|
|
1261
|
+
`node scripts/mistakes.mjs repeats --file ${sq(path)} # see docs/self-improvement.md for the fence`,
|
|
1262
|
+
),
|
|
1263
|
+
);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
return {
|
|
1268
|
+
findings,
|
|
1269
|
+
checked: `${MISTAKES_FILE}: ${parsed.entries.length} entries, ${rows.length} signatures`,
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1116
1273
|
/** The repo-global overnight runtime files that legally live at state/ level. */
|
|
1117
1274
|
/** The cross-initiative board artefacts board.mjs writes at state/ level. */
|
|
1118
1275
|
export const CROSS_BOARD_FILES = Object.freeze(['BOARD.md', 'board.json', 'board.html']);
|
|
@@ -1124,6 +1281,13 @@ export const OVERNIGHT_RUNTIME_FILES = Object.freeze([
|
|
|
1124
1281
|
'usage.json',
|
|
1125
1282
|
]);
|
|
1126
1283
|
|
|
1284
|
+
/**
|
|
1285
|
+
* The ask queue's own two files at state/ level: the sheet the operator edits
|
|
1286
|
+
* and the session record the SessionStart probe writes. Repo-global by
|
|
1287
|
+
* nature — the sheet spans every initiative — so they cannot live inside one.
|
|
1288
|
+
*/
|
|
1289
|
+
export const ASK_QUEUE_FILES = Object.freeze(['ANSWERS.md', 'conductor.json']);
|
|
1290
|
+
|
|
1127
1291
|
/**
|
|
1128
1292
|
* Overnight-mode consistency: the pause marker, the resume watcher, and the
|
|
1129
1293
|
* telemetry a configured gate depends on. Deterministic: staleness questions
|
|
@@ -1346,6 +1510,7 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
|
|
|
1346
1510
|
// gitignored) and are checked by overnightFindings instead.
|
|
1347
1511
|
if (OVERNIGHT_RUNTIME_FILES.includes(name)) continue;
|
|
1348
1512
|
if (CROSS_BOARD_FILES.includes(name)) continue; // generated by board.mjs at this level, by design
|
|
1513
|
+
if (ASK_QUEUE_FILES.includes(name)) continue; // the sheet and the session record, by design
|
|
1349
1514
|
findings.push(
|
|
1350
1515
|
finding(
|
|
1351
1516
|
'state-stray-file',
|
|
@@ -1379,6 +1544,10 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
|
|
|
1379
1544
|
}
|
|
1380
1545
|
checked.push(`initiatives/ (legacy): ${isDirectory(legacyDir) ? 'PRESENT' : 'absent'}`);
|
|
1381
1546
|
|
|
1547
|
+
const mistakes = mistakesFindings(repoRoot);
|
|
1548
|
+
findings.push(...mistakes.findings);
|
|
1549
|
+
checked.push(mistakes.checked);
|
|
1550
|
+
|
|
1382
1551
|
findings.push(...overnightFindings(dir, { now, configDoc }));
|
|
1383
1552
|
checked.push('overnight: checked');
|
|
1384
1553
|
|
package/scripts/journal.mjs
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* node journal.mjs tail <file> # last checkpoint + open items
|
|
18
18
|
* node journal.mjs open-spawns <file> # agents with no report or review yet
|
|
19
19
|
* node journal.mjs close-spawn <file> <init> <agent> --reason R [--verdict V]
|
|
20
|
+
* node journal.mjs ask <file> <init> --question Q [--default D] [--ticket T]
|
|
20
21
|
* Exit: 0 ok · 1 validation/finding error · 2 usage/IO error
|
|
21
22
|
*/
|
|
22
23
|
import {
|
|
@@ -104,7 +105,17 @@ export const DATA_ENUMS = Object.freeze({
|
|
|
104
105
|
* material belongs in NOTES.md with a reference here. `validateJournal`
|
|
105
106
|
* reports historical oversizes as warnings only (no retroactive errors).
|
|
106
107
|
*/
|
|
107
|
-
export const CAPPED_DATA_KEYS = Object.freeze({
|
|
108
|
+
export const CAPPED_DATA_KEYS = Object.freeze({
|
|
109
|
+
detail: 2000,
|
|
110
|
+
claim: 2000,
|
|
111
|
+
proof: 2000,
|
|
112
|
+
// The ask fields. They reach BOARD.md, board.html and the answer sheet, so
|
|
113
|
+
// an uncapped one is a document-sized cell in three artefacts at once.
|
|
114
|
+
question: 2000,
|
|
115
|
+
recommendation: 2000,
|
|
116
|
+
default: 2000,
|
|
117
|
+
answer: 2000,
|
|
118
|
+
});
|
|
108
119
|
|
|
109
120
|
/**
|
|
110
121
|
* A journal-derived value on its way into a HUMAN-READABLE MESSAGE.
|
|
@@ -580,6 +591,55 @@ export function closeSpawn(file, { init, agent, actor = 'conductor', verdict = '
|
|
|
580
591
|
});
|
|
581
592
|
}
|
|
582
593
|
|
|
594
|
+
// ------------------------------------------------------- operator asks
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* An ask is a `gate` whose `kind` IS its id. One kind, one question, forever.
|
|
598
|
+
*
|
|
599
|
+
* Anchored on purpose: `fold()` keys gates by kind with last-write-wins, so a
|
|
600
|
+
* kind that merely CONTAINS `Q-<n>` (`usage-limit-Q-99`) must not raise the
|
|
601
|
+
* next id — it would leave the true maximum free and the next ask would
|
|
602
|
+
* overwrite an older question on that Map with nothing objecting.
|
|
603
|
+
*/
|
|
604
|
+
export const ASK_KIND_RE = /^Q-(\d+)$/;
|
|
605
|
+
|
|
606
|
+
/** Pure: the next free ask id over a journal's own gate kinds. */
|
|
607
|
+
export function nextAskKind(events) {
|
|
608
|
+
let max = 0;
|
|
609
|
+
for (const e of events) {
|
|
610
|
+
if (e?.ev !== 'gate') continue;
|
|
611
|
+
const m = ASK_KIND_RE.exec(String(e?.data?.kind ?? ''));
|
|
612
|
+
if (m) max = Math.max(max, Number(m[1]));
|
|
613
|
+
}
|
|
614
|
+
return `Q-${max + 1}`;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Raise an operator ask: mint the id and append the gate under ONE lock.
|
|
619
|
+
*
|
|
620
|
+
* The id is NOT `data.id` and is not issued by `ID_ISSUED_FOR`: it is the gate
|
|
621
|
+
* `kind`, so no new event type exists and the closed set stays as it is. Two
|
|
622
|
+
* agents asking in the same millisecond get two ids because the read, the
|
|
623
|
+
* mint and the write share this lock; minting outside it gives them one, and
|
|
624
|
+
* the second question then replaces the first on the fold's kind-keyed Map —
|
|
625
|
+
* silent loss, in an append-only file that can never be corrected.
|
|
626
|
+
*/
|
|
627
|
+
export function raiseAsk(file, { init, actor = 'conductor', question, recommendation = null, default: dflt = null, ticket = null }) {
|
|
628
|
+
if (typeof question !== 'string' || question.trim().length === 0) {
|
|
629
|
+
throw new Error('ask requires a non-empty --question (what is the operator being asked?)');
|
|
630
|
+
}
|
|
631
|
+
mkdirSync(dirname(resolve(file)), { recursive: true });
|
|
632
|
+
return withLock(file, () => {
|
|
633
|
+
const snapshot = readJournal(file);
|
|
634
|
+
const data = { kind: nextAskKind(snapshot.events), result: 'WAITING_ON_OPERATOR' };
|
|
635
|
+
if (ticket != null) data.ticket = ticket;
|
|
636
|
+
data.question = question;
|
|
637
|
+
if (recommendation != null) data.recommendation = recommendation;
|
|
638
|
+
if (dflt != null) data.default = dflt;
|
|
639
|
+
return appendUnderLock(file, { ev: 'gate', init, actor, data }, snapshot);
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
|
|
583
643
|
/**
|
|
584
644
|
* Read all events. A truncated (crash-interrupted) FINAL line is discarded
|
|
585
645
|
* and reported via `truncatedTail`; a malformed line anywhere else is a
|
|
@@ -753,6 +813,7 @@ const CMD_FLAGS = {
|
|
|
753
813
|
tail: [],
|
|
754
814
|
'open-spawns': [],
|
|
755
815
|
'close-spawn': ['actor', 'verdict', 'reason'],
|
|
816
|
+
ask: ['actor', 'ticket', 'question', 'recommendation', 'default'],
|
|
756
817
|
};
|
|
757
818
|
|
|
758
819
|
/**
|
|
@@ -835,6 +896,22 @@ function main() {
|
|
|
835
896
|
console.log(emit(openSpawns(file), 2));
|
|
836
897
|
return;
|
|
837
898
|
}
|
|
899
|
+
case 'ask': {
|
|
900
|
+
const [file, init] = rest;
|
|
901
|
+
if (!file || !init) throw new UsageError();
|
|
902
|
+
// a missing --question gets raiseAsk's specific message, not a usage
|
|
903
|
+
// dump: the flag is the whole content of the command.
|
|
904
|
+
const written = raiseAsk(file, {
|
|
905
|
+
init,
|
|
906
|
+
actor: flags.actor ?? 'conductor',
|
|
907
|
+
question: flags.question ?? '',
|
|
908
|
+
recommendation: flags.recommendation ?? null,
|
|
909
|
+
default: flags.default ?? null,
|
|
910
|
+
ticket: flags.ticket ?? null,
|
|
911
|
+
});
|
|
912
|
+
console.log(emit(written));
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
838
915
|
case 'close-spawn': {
|
|
839
916
|
const [file, init, agent] = rest;
|
|
840
917
|
if (!file || !init || !agent) throw new UsageError();
|
|
@@ -858,6 +935,7 @@ function main() {
|
|
|
858
935
|
' journal.mjs validate <file> · next-id <file> <prefix> · tail <file>\n' +
|
|
859
936
|
' journal.mjs open-spawns <file>\n' +
|
|
860
937
|
' journal.mjs close-spawn <file> <init> <agent> --reason R [--verdict V] [--actor A]\n' +
|
|
938
|
+
' journal.mjs ask <file> <init> --question Q [--recommendation R] [--default D] [--ticket T] [--actor A]\n' +
|
|
861
939
|
'\n' +
|
|
862
940
|
// The `--data` contract varies per event and lived only in a table no
|
|
863
941
|
// command printed. A field run discovered it by rejection, one failed
|
|
@@ -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
|
+
}
|