claude-code-session-manager 0.25.0 → 0.26.0

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.
@@ -0,0 +1,304 @@
1
+ /**
2
+ * dod-report.test.cjs — unit tests for flagRiskySurfaces + writeReport.
3
+ *
4
+ * Run: timeout 120 node --test src/main/__tests__/dod-report.test.cjs
5
+ *
6
+ * Fixtures: os.tmpdir() only — never writes into real runs/.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const { test } = require('node:test');
12
+ const assert = require('node:assert/strict');
13
+ const os = require('node:os');
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const { flagRiskySurfaces, writeReport } = require('../lib/definitionOfDone.cjs');
17
+
18
+ // ─── helpers ──────────────────────────────────────────────────────────────────
19
+
20
+ function makeTmpDir() {
21
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'dod-report-test-'));
22
+ }
23
+
24
+ function rmdir(dir) {
25
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* */ }
26
+ }
27
+
28
+ function writePrd(prdsDir, slug, implNotes, cwd) {
29
+ const body = [
30
+ '---',
31
+ `title: ${slug}`,
32
+ `cwd: ${cwd}`,
33
+ 'estimateMinutes: 5',
34
+ '---',
35
+ '',
36
+ '# Goal',
37
+ '',
38
+ 'Test fixture.',
39
+ '',
40
+ '# Acceptance criteria',
41
+ '',
42
+ '- [ ] `timeout 10 node -e "process.exit(0)"` passes.',
43
+ '',
44
+ '# Implementation notes',
45
+ '',
46
+ implNotes,
47
+ '',
48
+ '# Out of scope',
49
+ '',
50
+ '- N/A',
51
+ ].join('\n');
52
+ fs.writeFileSync(path.join(prdsDir, `${slug}.md`), body);
53
+ return { slug, cwd };
54
+ }
55
+
56
+ // ─── flagRiskySurfaces: money-path ────────────────────────────────────────────
57
+
58
+ test('flagRiskySurfaces: flags money-path when impl notes reference payment', () => {
59
+ const tmpDir = makeTmpDir();
60
+ const prdsDir = path.join(tmpDir, 'prds');
61
+ const cwd = path.join(tmpDir, 'project');
62
+ fs.mkdirSync(prdsDir);
63
+ fs.mkdirSync(cwd);
64
+ const job = writePrd(prdsDir, '201-billing', '- Edit `src/payment-processor.js`\n- Update order schema', cwd);
65
+ try {
66
+ const flags = flagRiskySurfaces([job], { prdsDir });
67
+ assert.strictEqual(flags.length, 1);
68
+ assert.strictEqual(flags[0].slug, '201-billing');
69
+ assert.ok(flags[0].surfaces.includes('money-path'), `expected money-path in ${JSON.stringify(flags[0].surfaces)}`);
70
+ } finally {
71
+ rmdir(tmpDir);
72
+ }
73
+ });
74
+
75
+ test('flagRiskySurfaces: flags auth when impl notes reference auth/token', () => {
76
+ const tmpDir = makeTmpDir();
77
+ const prdsDir = path.join(tmpDir, 'prds');
78
+ const cwd = path.join(tmpDir, 'project');
79
+ fs.mkdirSync(prdsDir);
80
+ fs.mkdirSync(cwd);
81
+ const job = writePrd(prdsDir, '202-auth', '- Modify `src/auth-middleware.py`\n- Update token refresh logic', cwd);
82
+ try {
83
+ const flags = flagRiskySurfaces([job], { prdsDir });
84
+ assert.strictEqual(flags.length, 1);
85
+ assert.ok(flags[0].surfaces.includes('auth'));
86
+ } finally {
87
+ rmdir(tmpDir);
88
+ }
89
+ });
90
+
91
+ test('flagRiskySurfaces: flags migration when impl notes reference .sql file', () => {
92
+ const tmpDir = makeTmpDir();
93
+ const prdsDir = path.join(tmpDir, 'prds');
94
+ const cwd = path.join(tmpDir, 'project');
95
+ fs.mkdirSync(prdsDir);
96
+ fs.mkdirSync(cwd);
97
+ const job = writePrd(prdsDir, '203-schema', '- Run `db/migrations/0042_users.sql`', cwd);
98
+ try {
99
+ const flags = flagRiskySurfaces([job], { prdsDir });
100
+ assert.strictEqual(flags.length, 1);
101
+ assert.ok(flags[0].surfaces.includes('migration'));
102
+ } finally {
103
+ rmdir(tmpDir);
104
+ }
105
+ });
106
+
107
+ test('flagRiskySurfaces: clean job is not returned', () => {
108
+ const tmpDir = makeTmpDir();
109
+ const prdsDir = path.join(tmpDir, 'prds');
110
+ const cwd = path.join(tmpDir, 'project');
111
+ fs.mkdirSync(prdsDir);
112
+ fs.mkdirSync(cwd);
113
+ const job = writePrd(prdsDir, '204-clean', '- Update `src/ui/button.tsx`\n- Add tooltip component', cwd);
114
+ try {
115
+ const flags = flagRiskySurfaces([job], { prdsDir });
116
+ assert.strictEqual(flags.length, 0);
117
+ } finally {
118
+ rmdir(tmpDir);
119
+ }
120
+ });
121
+
122
+ test('flagRiskySurfaces: job with no PRD file is skipped (not thrown)', () => {
123
+ const tmpDir = makeTmpDir();
124
+ const prdsDir = path.join(tmpDir, 'prds');
125
+ const cwd = path.join(tmpDir, 'project');
126
+ fs.mkdirSync(prdsDir);
127
+ fs.mkdirSync(cwd);
128
+ try {
129
+ const flags = flagRiskySurfaces([{ slug: '205-missing', cwd }], { prdsDir });
130
+ assert.strictEqual(flags.length, 0);
131
+ } finally {
132
+ rmdir(tmpDir);
133
+ }
134
+ });
135
+
136
+ test('flagRiskySurfaces: mixed batch returns only risky jobs', () => {
137
+ const tmpDir = makeTmpDir();
138
+ const prdsDir = path.join(tmpDir, 'prds');
139
+ const cwd = path.join(tmpDir, 'project');
140
+ fs.mkdirSync(prdsDir);
141
+ fs.mkdirSync(cwd);
142
+ const jobRisky = writePrd(prdsDir, '206-risky', '- Modify `src/trade-engine.js`', cwd);
143
+ const jobClean = writePrd(prdsDir, '207-clean', '- Update `src/tooltip.tsx`', cwd);
144
+ try {
145
+ const flags = flagRiskySurfaces([jobRisky, jobClean], { prdsDir });
146
+ assert.strictEqual(flags.length, 1);
147
+ assert.strictEqual(flags[0].slug, '206-risky');
148
+ } finally {
149
+ rmdir(tmpDir);
150
+ }
151
+ });
152
+
153
+ // ─── writeReport: structure ────────────────────────────────────────────────────
154
+
155
+ test('writeReport: all three jobs appear in AC table', () => {
156
+ const tmpDir = makeTmpDir();
157
+ const runsDir = path.join(tmpDir, 'runs');
158
+ const acResults = [
159
+ { slug: '101-pass', status: 'pass', code: 0, ms: 500 },
160
+ { slug: '102-fail', status: 'fail', code: 1, ms: 300 },
161
+ { slug: '103-risky', status: 'pass', code: 0, ms: 400 },
162
+ ];
163
+ const riskFlags = [{ slug: '103-risky', surfaces: ['money-path'] }];
164
+ try {
165
+ const reportPath = writeReport('abcd1234', { acResults, riskFlags, runsDir });
166
+ assert.ok(fs.existsSync(reportPath), `report missing at ${reportPath}`);
167
+ const content = fs.readFileSync(reportPath, 'utf8');
168
+ assert.ok(content.includes('101-pass'), 'missing 101-pass in table');
169
+ assert.ok(content.includes('102-fail'), 'missing 102-fail in table');
170
+ assert.ok(content.includes('103-risky'), 'missing 103-risky in table');
171
+ } finally {
172
+ rmdir(tmpDir);
173
+ }
174
+ });
175
+
176
+ test('writeReport: fail and risky slug both appear in needs-attention list', () => {
177
+ const tmpDir = makeTmpDir();
178
+ const runsDir = path.join(tmpDir, 'runs');
179
+ const acResults = [
180
+ { slug: '101-pass', status: 'pass', code: 0, ms: 500 },
181
+ { slug: '102-fail', status: 'fail', code: 1, ms: 300 },
182
+ { slug: '103-risky', status: 'pass', code: 0, ms: 400 },
183
+ ];
184
+ const riskFlags = [{ slug: '103-risky', surfaces: ['money-path'] }];
185
+ try {
186
+ const reportPath = writeReport('abcd1234', { acResults, riskFlags, runsDir });
187
+ const content = fs.readFileSync(reportPath, 'utf8');
188
+ // Both should appear in the Needs Human Attention section
189
+ const attentionIdx = content.indexOf('## Needs Human Attention');
190
+ assert.ok(attentionIdx !== -1, 'missing Needs Human Attention section');
191
+ const attentionSection = content.slice(attentionIdx);
192
+ assert.ok(attentionSection.includes('102-fail'), '102-fail missing from attention list');
193
+ assert.ok(attentionSection.includes('103-risky'), '103-risky missing from attention list');
194
+ // Clean pass should NOT be in attention list
195
+ const passInAttention = attentionSection.includes('101-pass');
196
+ assert.ok(!passInAttention, '101-pass should not appear in attention list');
197
+ } finally {
198
+ rmdir(tmpDir);
199
+ }
200
+ });
201
+
202
+ test('writeReport: report states review is recommended, not auto-run', () => {
203
+ const tmpDir = makeTmpDir();
204
+ const runsDir = path.join(tmpDir, 'runs');
205
+ try {
206
+ const reportPath = writeReport('abcd1234', { acResults: [], riskFlags: [], runsDir });
207
+ const content = fs.readFileSync(reportPath, 'utf8');
208
+ assert.ok(
209
+ content.toLowerCase().includes('recommended') && content.toLowerCase().includes('not auto-run'),
210
+ 'report must state review is recommended, not auto-run'
211
+ );
212
+ } finally {
213
+ rmdir(tmpDir);
214
+ }
215
+ });
216
+
217
+ test('writeReport: no .tmp files left after write', () => {
218
+ const tmpDir = makeTmpDir();
219
+ const runsDir = path.join(tmpDir, 'runs');
220
+ const acResults = [{ slug: '101-pass', status: 'pass', code: 0, ms: 100 }];
221
+ try {
222
+ writeReport('deadbeef', { acResults, riskFlags: [], runsDir });
223
+ // Walk all files in runsDir recursively, check none end in .tmp-*
224
+ function findTmps(dir) {
225
+ const hits = [];
226
+ try {
227
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
228
+ const full = path.join(dir, e.name);
229
+ if (e.isDirectory()) hits.push(...findTmps(full));
230
+ else if (e.name.includes('.tmp-')) hits.push(full);
231
+ }
232
+ } catch { /* */ }
233
+ return hits;
234
+ }
235
+ const tmps = findTmps(runsDir);
236
+ assert.deepStrictEqual(tmps, [], `found leftover tmp files: ${tmps.join(', ')}`);
237
+ } finally {
238
+ rmdir(tmpDir);
239
+ }
240
+ });
241
+
242
+ test('writeReport: second call with same batchKey produces clean report, no tmp files', () => {
243
+ const tmpDir = makeTmpDir();
244
+ const runsDir = path.join(tmpDir, 'runs');
245
+ const acResults = [
246
+ { slug: '101-pass', status: 'pass', code: 0, ms: 100 },
247
+ { slug: '102-fail', status: 'fail', code: 1, ms: 200 },
248
+ ];
249
+ const riskFlags = [{ slug: '101-pass', surfaces: ['auth'] }];
250
+ try {
251
+ writeReport('cafebabe', { acResults, riskFlags, runsDir });
252
+ // Small delay to guarantee different timestamp dir
253
+ const t = Date.now() + 2;
254
+ while (Date.now() < t) { /* busy wait 2ms */ }
255
+ const report2 = writeReport('cafebabe', { acResults, riskFlags, runsDir });
256
+
257
+ // Second report must exist and be valid
258
+ assert.ok(fs.existsSync(report2));
259
+ const content = fs.readFileSync(report2, 'utf8');
260
+
261
+ // No duplicate rows in the AC table — slice only the AC table section.
262
+ const acStart = content.indexOf('## AC Results');
263
+ const riskStart = content.indexOf('## Risk Flags');
264
+ const acSection = content.slice(acStart, riskStart === -1 ? undefined : riskStart);
265
+ const passCount = (acSection.match(/101-pass/g) || []).length;
266
+ const failCount = (acSection.match(/102-fail/g) || []).length;
267
+ assert.strictEqual(passCount, 1, `101-pass appears ${passCount} times in AC table`);
268
+ assert.strictEqual(failCount, 1, `102-fail appears ${failCount} times in AC table`);
269
+
270
+ // No tmp files anywhere
271
+ function findTmps(dir) {
272
+ const hits = [];
273
+ try {
274
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
275
+ const full = path.join(dir, e.name);
276
+ if (e.isDirectory()) hits.push(...findTmps(full));
277
+ else if (e.name.includes('.tmp-')) hits.push(full);
278
+ }
279
+ } catch { /* */ }
280
+ return hits;
281
+ }
282
+ assert.deepStrictEqual(findTmps(runsDir), []);
283
+ } finally {
284
+ rmdir(tmpDir);
285
+ }
286
+ });
287
+
288
+ test('writeReport: report filename contains the batchKey', () => {
289
+ const tmpDir = makeTmpDir();
290
+ const runsDir = path.join(tmpDir, 'runs');
291
+ try {
292
+ const reportPath = writeReport('feed1234', { acResults: [], riskFlags: [], runsDir });
293
+ assert.ok(path.basename(reportPath).includes('feed1234'));
294
+ } finally {
295
+ rmdir(tmpDir);
296
+ }
297
+ });
298
+
299
+ test('writeReport: invalid batchKey throws', () => {
300
+ assert.throws(
301
+ () => writeReport('not-hex!!', { acResults: [], riskFlags: [] }),
302
+ /invalid batchKey/
303
+ );
304
+ });
@@ -0,0 +1,285 @@
1
+ /**
2
+ * dod-reverify.test.cjs — unit tests for extractAcCommand / reverifyAc / reverifyBatch.
3
+ *
4
+ * Run: timeout 180 node --test src/main/__tests__/dod-reverify.test.cjs
5
+ *
6
+ * Fixtures: os.tmpdir() only — never touches the real prds dir or scheduler queue.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const { test } = require('node:test');
12
+ const assert = require('node:assert/strict');
13
+ const os = require('node:os');
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const { extractAcCommand, reverifyAc, reverifyBatch } = require('../lib/definitionOfDone.cjs');
17
+
18
+ // ─── helpers ──────────────────────────────────────────────────────────────────
19
+
20
+ function makeTmpDir() {
21
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'dod-reverify-test-'));
22
+ }
23
+
24
+ function rmdir(dir) {
25
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* */ }
26
+ }
27
+
28
+ /** Write a minimal PRD file and return the job object. */
29
+ function writePrd(prdsDir, slug, acLine, cwd) {
30
+ const body = [
31
+ '---',
32
+ `title: ${slug}`,
33
+ `cwd: ${cwd}`,
34
+ 'estimateMinutes: 5',
35
+ '---',
36
+ '',
37
+ '# Goal',
38
+ '',
39
+ 'Test fixture.',
40
+ '',
41
+ '# Acceptance criteria',
42
+ '',
43
+ acLine,
44
+ '',
45
+ '# Out of scope',
46
+ '',
47
+ '- N/A',
48
+ ].join('\n');
49
+ fs.writeFileSync(path.join(prdsDir, `${slug}.md`), body);
50
+ return { slug, cwd };
51
+ }
52
+
53
+ // ─── extractAcCommand: backtick-quoted timeout ─────────────────────────────
54
+
55
+ test('extractAcCommand: extracts timeout from backtick-quoted inline code', () => {
56
+ const body = [
57
+ '# Acceptance criteria',
58
+ '',
59
+ '- [ ] Test `timeout 120 node --test src/main/__tests__/foo.test.cjs` passes.',
60
+ ].join('\n');
61
+ assert.strictEqual(extractAcCommand(body), 'timeout 120 node --test src/main/__tests__/foo.test.cjs');
62
+ });
63
+
64
+ test('extractAcCommand: extracts timeout from raw (non-backtick) AC line', () => {
65
+ const body = [
66
+ '# Acceptance criteria',
67
+ '',
68
+ '- [ ] timeout 60 node -c src/main/lib/definitionOfDone.cjs',
69
+ ].join('\n');
70
+ assert.strictEqual(extractAcCommand(body), 'timeout 60 node -c src/main/lib/definitionOfDone.cjs');
71
+ });
72
+
73
+ test('extractAcCommand: returns first timeout command when multiple AC lines match', () => {
74
+ const body = [
75
+ '# Acceptance criteria',
76
+ '',
77
+ '- [ ] `timeout 60 node -c foo.cjs` parses clean.',
78
+ '- [ ] `timeout 120 node --test bar.test.cjs` passes.',
79
+ ].join('\n');
80
+ assert.strictEqual(extractAcCommand(body), 'timeout 60 node -c foo.cjs');
81
+ });
82
+
83
+ test('extractAcCommand: returns null when no timeout command in AC section', () => {
84
+ const body = [
85
+ '# Acceptance criteria',
86
+ '',
87
+ '- [ ] The widget renders without errors.',
88
+ '- [ ] The config file is valid JSON.',
89
+ ].join('\n');
90
+ assert.strictEqual(extractAcCommand(body), null);
91
+ });
92
+
93
+ test('extractAcCommand: returns null for null/empty body', () => {
94
+ assert.strictEqual(extractAcCommand(null), null);
95
+ assert.strictEqual(extractAcCommand(''), null);
96
+ assert.strictEqual(extractAcCommand(undefined), null);
97
+ });
98
+
99
+ test('extractAcCommand: skips commands with shell pipes (needs shell:true)', () => {
100
+ const body = [
101
+ '# Acceptance criteria',
102
+ '',
103
+ '- [ ] `timeout 150 python -m pytest 2>&1 | tail -15` passes.',
104
+ '- [ ] `timeout 60 node -c src/lib/foo.cjs` parses clean.',
105
+ ].join('\n');
106
+ // Pipe command is rejected; falls back to the second clean command.
107
+ assert.strictEqual(extractAcCommand(body), 'timeout 60 node -c src/lib/foo.cjs');
108
+ });
109
+
110
+ test('extractAcCommand: works when body contains frontmatter strip artifact', () => {
111
+ const body = [
112
+ '# Goal',
113
+ '',
114
+ 'Do something.',
115
+ '',
116
+ '# Acceptance criteria',
117
+ '',
118
+ '- [ ] `timeout 30 node --test tests/foo.test.cjs` passes.',
119
+ ].join('\n');
120
+ assert.strictEqual(extractAcCommand(body), 'timeout 30 node --test tests/foo.test.cjs');
121
+ });
122
+
123
+ // ─── reverifyAc: pass ─────────────────────────────────────────────────────────
124
+
125
+ test('reverifyAc: returns pass when AC command exits 0', async () => {
126
+ const tmpDir = makeTmpDir();
127
+ const prdsDir = path.join(tmpDir, 'prds');
128
+ const cwd = path.join(tmpDir, 'project');
129
+ fs.mkdirSync(prdsDir);
130
+ fs.mkdirSync(cwd);
131
+ // Write a tiny node script that exits 0
132
+ fs.writeFileSync(path.join(cwd, 'ok.cjs'), 'process.exit(0);');
133
+
134
+ const job = writePrd(prdsDir, '101-pass', '- [ ] `timeout 10 node ok.cjs` succeeds.', cwd);
135
+ try {
136
+ const result = await reverifyAc(job, { timeoutMs: 15_000, prdsDir });
137
+ assert.strictEqual(result.slug, '101-pass');
138
+ assert.strictEqual(result.status, 'pass');
139
+ assert.strictEqual(result.code, 0);
140
+ assert.ok(typeof result.ms === 'number' && result.ms >= 0, `ms should be >= 0, got ${result.ms}`);
141
+ } finally {
142
+ rmdir(tmpDir);
143
+ }
144
+ });
145
+
146
+ // ─── reverifyAc: fail ─────────────────────────────────────────────────────────
147
+
148
+ test('reverifyAc: returns fail when AC command exits non-zero', async () => {
149
+ const tmpDir = makeTmpDir();
150
+ const prdsDir = path.join(tmpDir, 'prds');
151
+ const cwd = path.join(tmpDir, 'project');
152
+ fs.mkdirSync(prdsDir);
153
+ fs.mkdirSync(cwd);
154
+ fs.writeFileSync(path.join(cwd, 'fail.cjs'), 'process.exit(1);');
155
+
156
+ const job = writePrd(prdsDir, '102-fail', '- [ ] `timeout 10 node fail.cjs` succeeds.', cwd);
157
+ try {
158
+ const result = await reverifyAc(job, { timeoutMs: 15_000, prdsDir });
159
+ assert.strictEqual(result.slug, '102-fail');
160
+ assert.strictEqual(result.status, 'fail');
161
+ assert.strictEqual(result.code, 1);
162
+ assert.ok(typeof result.ms === 'number' && result.ms >= 0);
163
+ } finally {
164
+ rmdir(tmpDir);
165
+ }
166
+ });
167
+
168
+ // ─── reverifyAc: unverifiable ─────────────────────────────────────────────────
169
+
170
+ test('reverifyAc: returns unverifiable when PRD has no parseable AC command', async () => {
171
+ const tmpDir = makeTmpDir();
172
+ const prdsDir = path.join(tmpDir, 'prds');
173
+ const cwd = path.join(tmpDir, 'project');
174
+ fs.mkdirSync(prdsDir);
175
+ fs.mkdirSync(cwd);
176
+
177
+ const job = writePrd(prdsDir, '103-nocmd', '- [ ] The widget renders correctly.', cwd);
178
+ try {
179
+ const result = await reverifyAc(job, { timeoutMs: 15_000, prdsDir });
180
+ assert.strictEqual(result.slug, '103-nocmd');
181
+ assert.strictEqual(result.status, 'unverifiable');
182
+ assert.strictEqual(result.code, null);
183
+ } finally {
184
+ rmdir(tmpDir);
185
+ }
186
+ });
187
+
188
+ test('reverifyAc: returns unverifiable when cwd does not exist', async () => {
189
+ const tmpDir = makeTmpDir();
190
+ const prdsDir = path.join(tmpDir, 'prds');
191
+ fs.mkdirSync(prdsDir);
192
+ const missingCwd = path.join(tmpDir, 'nonexistent-project');
193
+
194
+ const job = writePrd(prdsDir, '104-nocwd', '- [ ] `timeout 5 node -e "process.exit(0)"` passes.', missingCwd);
195
+ try {
196
+ const result = await reverifyAc(job, { timeoutMs: 15_000, prdsDir });
197
+ assert.strictEqual(result.status, 'unverifiable');
198
+ } finally {
199
+ rmdir(tmpDir);
200
+ }
201
+ });
202
+
203
+ test('reverifyAc: returns unverifiable when PRD file does not exist', async () => {
204
+ const tmpDir = makeTmpDir();
205
+ const prdsDir = path.join(tmpDir, 'prds');
206
+ const cwd = path.join(tmpDir, 'project');
207
+ fs.mkdirSync(prdsDir);
208
+ fs.mkdirSync(cwd);
209
+
210
+ // job.slug points to a missing .md file
211
+ const job = { slug: '105-missing-prd', cwd };
212
+ try {
213
+ const result = await reverifyAc(job, { timeoutMs: 15_000, prdsDir });
214
+ assert.strictEqual(result.status, 'unverifiable');
215
+ } finally {
216
+ rmdir(tmpDir);
217
+ }
218
+ });
219
+
220
+ // ─── reverifyBatch: all three statuses ────────────────────────────────────────
221
+
222
+ test('reverifyBatch: returns pass/fail/unverifiable for a mixed batch', async () => {
223
+ const tmpDir = makeTmpDir();
224
+ const prdsDir = path.join(tmpDir, 'prds');
225
+ const cwd = path.join(tmpDir, 'project');
226
+ fs.mkdirSync(prdsDir);
227
+ fs.mkdirSync(cwd);
228
+
229
+ fs.writeFileSync(path.join(cwd, 'ok.cjs'), 'process.exit(0);');
230
+ fs.writeFileSync(path.join(cwd, 'fail.cjs'), 'process.exit(1);');
231
+
232
+ const jobPass = writePrd(prdsDir, '201-pass', '- [ ] `timeout 10 node ok.cjs` passes.', cwd);
233
+ const jobFail = writePrd(prdsDir, '202-fail', '- [ ] `timeout 10 node fail.cjs` passes.', cwd);
234
+ const jobNone = writePrd(prdsDir, '203-noop', '- [ ] The result is correct.', cwd);
235
+
236
+ try {
237
+ const results = await reverifyBatch([jobPass, jobFail, jobNone], {
238
+ timeoutMs: 15_000,
239
+ batchTimeoutMs: 120_000,
240
+ prdsDir,
241
+ });
242
+ assert.strictEqual(results.length, 3);
243
+
244
+ const bySlug = Object.fromEntries(results.map((r) => [r.slug, r]));
245
+ assert.strictEqual(bySlug['201-pass'].status, 'pass');
246
+ assert.strictEqual(bySlug['202-fail'].status, 'fail');
247
+ assert.strictEqual(bySlug['203-noop'].status, 'unverifiable');
248
+ } finally {
249
+ rmdir(tmpDir);
250
+ }
251
+ });
252
+
253
+ // ─── reverifyBatch: batch wall-time cap ───────────────────────────────────────
254
+
255
+ test('reverifyBatch: marks remaining jobs unverifiable when batch cap is hit', async () => {
256
+ const tmpDir = makeTmpDir();
257
+ const prdsDir = path.join(tmpDir, 'prds');
258
+ const cwd = path.join(tmpDir, 'project');
259
+ fs.mkdirSync(prdsDir);
260
+ fs.mkdirSync(cwd);
261
+
262
+ // Slow job — sleeps longer than batchTimeoutMs
263
+ fs.writeFileSync(path.join(cwd, 'slow.cjs'), 'setTimeout(() => process.exit(0), 30_000);');
264
+ const jobSlow = writePrd(prdsDir, '301-slow', '- [ ] `timeout 60 node slow.cjs` passes.', cwd);
265
+ fs.writeFileSync(path.join(cwd, 'ok.cjs'), 'process.exit(0);');
266
+ const jobAfter = writePrd(prdsDir, '302-after', '- [ ] `timeout 10 node ok.cjs` passes.', cwd);
267
+
268
+ try {
269
+ // Kill the slow job after 500ms; the batch cap (200ms) ensures jobAfter
270
+ // is never started. Total test wall-time ≈ 500ms.
271
+ const results = await reverifyBatch([jobSlow, jobAfter], {
272
+ timeoutMs: 500,
273
+ batchTimeoutMs: 200,
274
+ prdsDir,
275
+ });
276
+ assert.strictEqual(results.length, 2);
277
+ // The slow job ran but the batch cap check fires before jobAfter starts.
278
+ // (The slow job itself may finish or not within the timeoutMs; we only care
279
+ // that jobAfter is unverifiable due to the batch cap.)
280
+ const after = results.find((r) => r.slug === '302-after');
281
+ assert.strictEqual(after.status, 'unverifiable');
282
+ } finally {
283
+ rmdir(tmpDir);
284
+ }
285
+ });
@@ -57,6 +57,9 @@ let powerBlockerId = -1;
57
57
  // `systemd-inhibit` child, which talks straight to logind and is
58
58
  // desktop-agnostic. Handle to the child so we can release it on quit.
59
59
  let systemdInhibitChild = null;
60
+ // Belt-and-suspenders: re-assert the inhibitor on a slow cadence so it can never
61
+ // stay dead (idempotent — startSystemdInhibit no-ops if a live holder exists).
62
+ let inhibitReassertTimer = null;
60
63
 
61
64
  function startSystemdInhibit() {
62
65
  if (process.platform !== 'linux') return;
@@ -70,7 +73,11 @@ function startSystemdInhibit() {
70
73
  // this the child reparents to init on a hard kill and the inhibitor leaks
71
74
  // forever (one stranded lock per crash). 5s tick = worst-case 5s of stale
72
75
  // lock after death, which errs toward "stay awake" — the safe direction.
73
- const child = spawn('systemd-inhibit', [
76
+ // Absolute path — a GUI/desktop-launched Electron can boot with a minimal
77
+ // PATH that lacks /usr/bin, so a bare `systemd-inhibit` would ENOENT.
78
+ const inhibitBin = require('node:fs').existsSync('/usr/bin/systemd-inhibit')
79
+ ? '/usr/bin/systemd-inhibit' : 'systemd-inhibit';
80
+ const child = spawn(inhibitBin, [
74
81
  '--what=sleep:idle',
75
82
  '--who=Claude Session Manager',
76
83
  '--why=Scheduler polling and claude -p jobs must survive idle',
@@ -80,6 +87,17 @@ function startSystemdInhibit() {
80
87
  child.on('error', (e) => {
81
88
  logs.writeLine({ scope: 'main', level: 'warn', message: 'systemd-inhibit spawn failed', meta: { error: e?.message } });
82
89
  });
90
+ // Self-heal: if the holder ever dies while the app is alive (a missed
91
+ // suspend, an external kill, a transient spawn that didn't hold), revive it.
92
+ // Without this the lock is held exactly once at boot and never recovers —
93
+ // the machine then idle-suspends with the app open (the reported bug).
94
+ child.on('exit', (code, signal) => {
95
+ logs.writeLine({ scope: 'main', level: 'warn', message: 'systemd-inhibit holder exited', meta: { code, signal } });
96
+ if (!teardownDone && systemdInhibitChild === child) {
97
+ systemdInhibitChild = null;
98
+ setTimeout(() => { if (!teardownDone) startSystemdInhibit(); }, 2000);
99
+ }
100
+ });
83
101
  if (child.pid) {
84
102
  systemdInhibitChild = child;
85
103
  logs.writeLine({ scope: 'main', level: 'info', message: 'systemd-inhibit block lock held', meta: { pid: child.pid } });
@@ -952,6 +970,12 @@ app.whenReady().then(async () => {
952
970
  }
953
971
  // Linux backstop — Electron's blocker no-ops under COSMIC (see above).
954
972
  startSystemdInhibit();
973
+ // Re-assert every 60s so a dead holder self-revives even if its exit handler
974
+ // was missed. Idempotent; unref'd so it never holds the loop open at quit.
975
+ if (process.platform === 'linux' && !inhibitReassertTimer) {
976
+ inhibitReassertTimer = setInterval(() => { if (!teardownDone) startSystemdInhibit(); }, 60_000);
977
+ if (inhibitReassertTimer.unref) inhibitReassertTimer.unref();
978
+ }
955
979
 
956
980
  // OTEL: load persisted config and start the exporter only if `enabled`.
957
981
  // Failures are non-fatal — the app must keep working without telemetry.
@@ -987,6 +1011,7 @@ function runShutdownCleanup() {
987
1011
  try { powerSaveBlocker.stop(powerBlockerId); } catch { /* */ }
988
1012
  powerBlockerId = -1;
989
1013
  }
1014
+ if (inhibitReassertTimer) { clearInterval(inhibitReassertTimer); inhibitReassertTimer = null; }
990
1015
  stopSystemdInhibit();
991
1016
  }
992
1017