claude-code-session-manager 0.64.0 → 0.66.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.
Files changed (63) hide show
  1. package/dist/assets/AgentLibrary-Bzg89D5Y.js +3 -0
  2. package/dist/assets/{History-Dp3-_bjQ.js → History-CNH9vA0A.js} +2 -2
  3. package/dist/assets/{Hooks-DMQFgGDd.js → Hooks-CyTksPza.js} +3 -3
  4. package/dist/assets/{HostBilko-zNU1NtBh.js → HostBilko-DXQVDNHn.js} +1 -1
  5. package/dist/assets/{Library-BrODBbeL.js → Library-9E2UOIsm.js} +1 -1
  6. package/dist/assets/{ListDetail-C5vbA1gC.js → ListDetail-CQWU_Yn5.js} +1 -1
  7. package/dist/assets/{MarkdownEditor-CpzAEiiG.js → MarkdownEditor-DQgfpSef.js} +1 -1
  8. package/dist/assets/{McpServers-DWuw-flj.js → McpServers-r3qwDIj2.js} +2 -2
  9. package/dist/assets/{Memory-B4TC9SsJ.js → Memory-BaxOpj-3.js} +6 -6
  10. package/dist/assets/{Panel-Bap7G-pI.js → Panel-BhFD8Lqo.js} +1 -1
  11. package/dist/assets/{Permissions-BIpNWItH.js → Permissions-Cj-mODQQ.js} +3 -3
  12. package/dist/assets/{Plugins-DrwklmW4.js → Plugins-DEL3Fqng.js} +2 -2
  13. package/dist/assets/{ProvenanceBadge-CCp_EhjV.js → ProvenanceBadge-CIAg6-JQ.js} +1 -1
  14. package/dist/assets/Scheduler-YOuZKkES.js +14 -0
  15. package/dist/assets/{ScopeSwitcher-BlQvpyLE.js → ScopeSwitcher-DZ_3gEus.js} +1 -1
  16. package/dist/assets/{Settings-BzvmZvGa.js → Settings-B0x4oflz.js} +3 -3
  17. package/dist/assets/{SkillReferenceGraph-CGtwmCjm.js → SkillReferenceGraph-CoIwsol8.js} +1 -1
  18. package/dist/assets/{Skills-Cauvbtk7.js → Skills-CN8R6AWn.js} +2 -2
  19. package/dist/assets/{SystemPrompt-BqzM76PV.js → SystemPrompt-DceChpAi.js} +1 -1
  20. package/dist/assets/{TagLibrary-DVKPjeRu.js → TagLibrary-BKmz2W7B.js} +1 -1
  21. package/dist/assets/{TiptapBody-CUWdBAYf.js → TiptapBody-W7n5SwPM.js} +1 -1
  22. package/dist/assets/{Toggle-Bos67yDJ.js → Toggle-QuxlVHGI.js} +1 -1
  23. package/dist/assets/{index-LlWpj2VJ.css → index-14dBLqE_.css} +1 -1
  24. package/dist/assets/{index-BfPVknuV.js → index-TejhHSzN.js} +526 -525
  25. package/dist/assets/{settingsSchema-DKuyaEK5.js → settingsSchema-DNqx6BKJ.js} +1 -1
  26. package/dist/index.html +2 -2
  27. package/package.json +5 -1
  28. package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +120 -0
  29. package/plugins/session-manager-dev/skills/builder/SKILL.md +13 -3
  30. package/plugins/session-manager-dev/skills/develop/SKILL.md +41 -13
  31. package/plugins/session-manager-dev/skills/ops-sweep/SKILL.md +10 -0
  32. package/src/main/__tests__/agentLibrary.test.cjs +40 -0
  33. package/src/main/__tests__/flatPrdTickSweep.test.cjs +110 -0
  34. package/src/main/__tests__/prdAdminRouteParity.test.cjs +68 -0
  35. package/src/main/__tests__/prdAdminRoutes.test.cjs +311 -0
  36. package/src/main/__tests__/prdCreate.test.cjs +7 -2
  37. package/src/main/__tests__/prdMigration.test.cjs +17 -0
  38. package/src/main/__tests__/prdMigrationLegacyAdopt.test.cjs +91 -0
  39. package/src/main/__tests__/reconcileFlatPrdSweep.test.cjs +109 -0
  40. package/src/main/__tests__/scheduleJobSchema.test.cjs +127 -0
  41. package/src/main/__tests__/scheduleJobStatusDrift.test.cjs +65 -0
  42. package/src/main/__tests__/scheduleJobTransitions.test.cjs +152 -0
  43. package/src/main/__tests__/scheduleJobTransitionsGrep.test.cjs +59 -0
  44. package/src/main/__tests__/scheduler-reconcile-invalid-repair.test.cjs +203 -0
  45. package/src/main/__tests__/scheduler-reconcile-quarantine.test.cjs +196 -0
  46. package/src/main/agentLibrary.cjs +40 -2
  47. package/src/main/index.cjs +2 -0
  48. package/src/main/ipcSchemas.cjs +60 -0
  49. package/src/main/lib/localAdminHttp.cjs +10 -3
  50. package/src/main/lib/prdAdminRoutes.cjs +175 -0
  51. package/src/main/lib/prdCreate.cjs +37 -2
  52. package/src/main/lib/prdFrontmatter.cjs +179 -1
  53. package/src/main/lib/prdMigration.cjs +82 -5
  54. package/src/main/lib/queueStore.cjs +41 -7
  55. package/src/main/lib/scheduleJobSchema.cjs +114 -0
  56. package/src/main/lib/scheduleJobTransitions.cjs +164 -0
  57. package/src/main/scheduler/prdParser.cjs +7 -0
  58. package/src/main/scheduler.cjs +649 -137
  59. package/src/preload/api.d.ts +54 -2
  60. package/src/preload/index.cjs +12 -0
  61. package/dist/assets/AgentLibrary-9KJ4fedH.js +0 -1
  62. package/dist/assets/Scheduler-DfoTegGG.js +0 -14
  63. /package/plugins/session-manager-dev/skills/builder/{4-report → 5-report}/SKILL.md +0 -0
@@ -0,0 +1,109 @@
1
+ /**
2
+ * reconcileFlatPrdSweep.test.cjs — end-to-end proof that `reconcile()` itself
3
+ * (not just `consolidateAllFlatPrds()` in isolation) never turns a
4
+ * hand-written flat-dir PRD into a queue job, regardless of which of
5
+ * reconcile's several callers (tickQueue's poll, job completion, the
6
+ * schedule:state/schedule:rescan IPC handlers, rescheduleTimer) triggered
7
+ * the pass.
8
+ *
9
+ * A code-review pass on this PRD flagged that gating only `tickQueue()` left
10
+ * every OTHER caller of `reconcile()` free to still turn a freshly
11
+ * hand-written flat-dir PRD into a `pending` job — the fix moved the sweep
12
+ * inside `reconcile()` itself instead. This test exercises the real
13
+ * `reconcile()` (not a stand-in) against a real on-disk flat-dir PRD with no
14
+ * pre-existing queue row (exactly the state of a file dropped there moments
15
+ * ago) and asserts it never appears in `state.jobs` afterward.
16
+ *
17
+ * HOME-isolated (mirrors scheduler-reconcile-invalid-repair.test.cjs): stub
18
+ * HOME to a mkdtemp dir before requiring scheduler.cjs, and register the
19
+ * fixture project as "active" via a fake ~/.claude/projects transcript —
20
+ * reconcile's PRD discovery (prdLocations.cjs) only scans cwds it can find
21
+ * that way.
22
+ *
23
+ * Run: timeout 120 npx vitest run src/main/__tests__/reconcileFlatPrdSweep.test.cjs
24
+ */
25
+
26
+ 'use strict';
27
+
28
+ import { test, expect, beforeAll, afterAll } from 'vitest';
29
+ const fs = require('node:fs');
30
+ const os = require('node:os');
31
+ const path = require('node:path');
32
+
33
+ let tmpHome;
34
+ let originalHome;
35
+ let scheduler;
36
+
37
+ beforeAll(() => {
38
+ originalHome = process.env.HOME;
39
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-reconcile-flatsweep-home-'));
40
+ process.env.HOME = tmpHome;
41
+
42
+ scheduler = require('../scheduler.cjs');
43
+
44
+ if (!scheduler.PRDS_DIR.startsWith(tmpHome)) {
45
+ throw new Error(`refusing to run: PRDS_DIR (${scheduler.PRDS_DIR}) is not under the temp HOME (${tmpHome})`);
46
+ }
47
+ });
48
+
49
+ afterAll(() => {
50
+ process.env.HOME = originalHome;
51
+ fs.rmSync(tmpHome, { recursive: true, force: true });
52
+ });
53
+
54
+ function registerActiveProject(cwd) {
55
+ const projectsDir = path.join(tmpHome, '.claude', 'projects');
56
+ const slugDir = path.join(projectsDir, `fake-project-slug-${path.basename(cwd)}`);
57
+ fs.mkdirSync(slugDir, { recursive: true });
58
+ fs.writeFileSync(path.join(slugDir, 'transcript.jsonl'), JSON.stringify({ cwd }) + '\n');
59
+ }
60
+
61
+ function makeFixtureProject(prefix) {
62
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
63
+ registerActiveProject(cwd);
64
+ const opsRoot = path.join(cwd, 'session-manager-operations');
65
+ const flatPrdsDir = path.join(opsRoot, 'scheduler', 'prds');
66
+ const stateDir = path.join(opsRoot, 'scheduler', 'state');
67
+ fs.mkdirSync(flatPrdsDir, { recursive: true });
68
+ fs.mkdirSync(stateDir, { recursive: true });
69
+ return { cwd, flatPrdsDir, stateDir, archiveDir: path.join(opsRoot, 'scheduler', 'prds-archived') };
70
+ }
71
+
72
+ test('reconcile() never turns a hand-written flat-dir PRD into a job, no matter which caller triggers it', async () => {
73
+ const { cwd, flatPrdsDir, archiveDir } = makeFixtureProject('sm-reconcile-flatsweep-proj-');
74
+ const filename = '1500-hand-written-bypass.md';
75
+ fs.writeFileSync(
76
+ path.join(flatPrdsDir, filename),
77
+ `---\ntitle: Hand-written bypass\ncwd: ${cwd}\nestimateMinutes: 10\n---\n\n# Goal\n\nSomething.\n`,
78
+ 'utf8',
79
+ );
80
+ // No queue.json at all — the exact state of a PRD dropped on disk moments
81
+ // ago, before any prior reconcile() pass has scanned it into a job.
82
+
83
+ const state = { jobs: [], invalidJobs: [], paused: null };
84
+ await scheduler.reconcile(state);
85
+
86
+ const found = state.jobs.find((j) => j.slug === '1500-hand-written-bypass');
87
+ expect(found).toBeUndefined();
88
+ expect(fs.existsSync(path.join(flatPrdsDir, filename))).toBe(false);
89
+ expect(fs.existsSync(path.join(archiveDir, filename))).toBe(true);
90
+ });
91
+
92
+ test('reconcile() still onboards a PRD written to the canonical Epic-scoped dir (the sweep only touches the flat dir)', async () => {
93
+ const { cwd } = makeFixtureProject('sm-reconcile-flatsweep-epic-proj-');
94
+ const epicId = 'epic-abc';
95
+ const epicPrdsDir = path.join(cwd, 'session-manager-operations', 'scheduler', 'epics', epicId, 'prds');
96
+ fs.mkdirSync(epicPrdsDir, { recursive: true });
97
+ fs.writeFileSync(
98
+ path.join(epicPrdsDir, '1501-canonical.md'),
99
+ `---\ntitle: Canonical\ncwd: ${cwd}\nestimateMinutes: 10\nsourcePromptId: ${epicId}\ncreatedVia: scheduler-api\nissuedAt: 2026-08-07T00:00:00.000Z\n---\n\n# Goal\n\nSomething.\n`,
100
+ 'utf8',
101
+ );
102
+
103
+ const state = { jobs: [], invalidJobs: [], paused: null };
104
+ await scheduler.reconcile(state);
105
+
106
+ const found = state.jobs.find((j) => j.slug === '1501-canonical');
107
+ expect(found).toBeDefined();
108
+ expect(found.status).toBe('pending');
109
+ });
@@ -0,0 +1,127 @@
1
+ /**
2
+ * scheduleJobSchema.test.cjs — unit tests for the canonical ScheduleJob zod
3
+ * schema, its assertValidScheduleJob fail-closed helper, and queueStore.cjs's
4
+ * shapeJobs on-read quarantine gate.
5
+ *
6
+ * Reproduces the 2026-08-07 incident: PRDs 1021/1022 (social-signals-trader)
7
+ * sat unscheduled for 4+ hours because their queue.json rows carried
8
+ * `"status": "queued"` — a value absent from ScheduleJobStatus — which every
9
+ * picker silently skipped since none of them treat an unrecognized status as
10
+ * an error.
11
+ *
12
+ * Run: timeout 300 npx vitest run src/main/__tests__/scheduleJobSchema.test.cjs
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ import { test, expect, beforeEach, afterEach, vi } from 'vitest';
18
+ const fs = require('node:fs');
19
+ const os = require('node:os');
20
+ const path = require('node:path');
21
+ const {
22
+ ScheduleJobSchema,
23
+ JOB_STATUSES,
24
+ assertValidScheduleJob,
25
+ } = require('../lib/scheduleJobSchema.cjs');
26
+ const { shapeJobs } = require('../lib/queueStore.cjs');
27
+
28
+ function validJob(overrides = {}) {
29
+ return {
30
+ slug: '1021-social-signals',
31
+ title: 'Wire up social signals trader',
32
+ cwd: '/home/bilko/Projects/social-signals-trader',
33
+ parallelGroup: 1021,
34
+ estimateMinutes: 30,
35
+ bodyPreview: 'Do the thing.',
36
+ status: 'pending',
37
+ runId: null,
38
+ startedAt: null,
39
+ finishedAt: null,
40
+ exitCode: null,
41
+ error: null,
42
+ ...overrides,
43
+ };
44
+ }
45
+
46
+ test('JOB_STATUSES matches ScheduleJobStatus', () => {
47
+ expect(JOB_STATUSES).toEqual(['pending', 'running', 'investigating', 'completed', 'failed', 'needs_review', 'quarantined']);
48
+ });
49
+
50
+ test('a valid full job record parses', () => {
51
+ const full = validJob({
52
+ sessionId: 'c1b2a3d4-0000-0000-0000-000000000000',
53
+ runtime: { pid: 123, runId: 'run-1', startedAt: '2026-08-07T00:00:00.000Z' },
54
+ verifierVerdict: 'halt',
55
+ dependsOn: ['1020-prereq'],
56
+ originSessionId: 'orig-session',
57
+ sourceTabId: 'tab-1',
58
+ sourcePromptId: 'prompt-1',
59
+ epicId: 'epic-1',
60
+ });
61
+ expect(() => assertValidScheduleJob(full)).not.toThrow();
62
+ expect(ScheduleJobSchema.safeParse(full).success).toBe(true);
63
+ });
64
+
65
+ test('a job with an invalid status value fails', () => {
66
+ const badStatus = validJob({ status: 'queued' });
67
+ expect(() => assertValidScheduleJob(badStatus)).toThrow(/status/);
68
+ });
69
+
70
+ test('a job missing a required field fails', () => {
71
+ const { slug, ...missingSlug } = validJob();
72
+ expect(() => assertValidScheduleJob(missingSlug)).toThrow(/slug/);
73
+ });
74
+
75
+ // ---------- shapeJobs (the on-read quarantine gate) ----------
76
+
77
+ let tmpFile;
78
+ let errorSpy;
79
+
80
+ beforeEach(() => {
81
+ tmpFile = path.join(
82
+ os.tmpdir(),
83
+ `scheduleJobSchema-test-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`
84
+ );
85
+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
86
+ });
87
+
88
+ afterEach(() => {
89
+ try { fs.unlinkSync(tmpFile); } catch { /* ok if absent */ }
90
+ errorSpy.mockRestore();
91
+ });
92
+
93
+ test('a row with status "queued" (the 1021/1022 incident) is quarantined, logged, and absent from jobs', () => {
94
+ fs.writeFileSync(tmpFile, JSON.stringify({
95
+ jobs: [
96
+ validJob({ slug: '1021-social-signals', status: 'queued' }),
97
+ validJob({ slug: '1022-social-signals', status: 'queued' }),
98
+ validJob({ slug: '1023-healthy', status: 'pending' }),
99
+ ],
100
+ }));
101
+
102
+ const raw = fs.readFileSync(tmpFile, 'utf8');
103
+ const { jobs, invalid } = shapeJobs(raw, tmpFile);
104
+
105
+ expect(jobs.map((j) => j.slug)).toEqual(['1023-healthy']);
106
+ expect(invalid.map((i) => i.slug)).toEqual(['1021-social-signals', '1022-social-signals']);
107
+ expect(invalid[0].issues).toMatch(/status/);
108
+ expect(invalid[0].file).toBe(tmpFile);
109
+
110
+ expect(errorSpy).toHaveBeenCalledTimes(2);
111
+ const firstCallArgs = errorSpy.mock.calls[0][0];
112
+ expect(firstCallArgs).toContain(tmpFile);
113
+ expect(firstCallArgs).toContain('1021-social-signals');
114
+ expect(firstCallArgs).toMatch(/status/);
115
+ });
116
+
117
+ test('a fully valid row round-trips through shapeJobs unchanged', () => {
118
+ const job = validJob({ slug: '1023-healthy' });
119
+ fs.writeFileSync(tmpFile, JSON.stringify({ jobs: [job] }));
120
+
121
+ const raw = fs.readFileSync(tmpFile, 'utf8');
122
+ const { jobs, invalid } = shapeJobs(raw, tmpFile);
123
+
124
+ expect(invalid).toEqual([]);
125
+ expect(jobs).toEqual([job]);
126
+ expect(errorSpy).not.toHaveBeenCalled();
127
+ });
@@ -0,0 +1,65 @@
1
+ /**
2
+ * scheduleJobStatusDrift.test.cjs — guards the mirrored copies of
3
+ * JOB_STATUSES (src/main/lib/scheduleJobSchema.cjs) against silent drift.
4
+ *
5
+ * The renderer cannot require a .cjs module directly, and src/preload/api.d.ts
6
+ * is types-only (erased at build time, nothing to import at test runtime), so
7
+ * each consumer keeps its own hand-written mirror of the status enum:
8
+ * - src/preload/api.d.ts's `ScheduleJobStatus` union
9
+ * - src/renderer/components/ui/StatusBadge.tsx's `JobStatus` union
10
+ * - src/renderer/components/SchedulePanel.tsx's `FilterStatus` union
11
+ * (which also carries the UI-only 'all' meta-value)
12
+ *
13
+ * This test reads each file's source text and extracts its status list by
14
+ * regex, then diffs it against JOB_STATUSES — the single source of truth.
15
+ * A file whose union drifts (a status added/removed/renamed in one place but
16
+ * not the others) fails this test instead of silently mis-filtering jobs,
17
+ * which is exactly how the 2026-08-07 'queued' incident went undetected.
18
+ *
19
+ * Run: timeout 300 npx vitest run src/main/__tests__/scheduleJobStatusDrift.test.cjs
20
+ */
21
+
22
+ 'use strict';
23
+
24
+ import { test, expect } from 'vitest';
25
+ const fs = require('node:fs');
26
+ const path = require('node:path');
27
+ const { JOB_STATUSES } = require('../lib/scheduleJobSchema.cjs');
28
+
29
+ const ROOT = path.join(__dirname, '..', '..', '..');
30
+
31
+ function readSource(relPath) {
32
+ return fs.readFileSync(path.join(ROOT, relPath), 'utf8');
33
+ }
34
+
35
+ function extractQuotedList(source, anchorRegex) {
36
+ const match = source.match(anchorRegex);
37
+ if (!match) throw new Error(`extractQuotedList: anchor not found — ${anchorRegex}`);
38
+ return [...match[1].matchAll(/'([a-z_]+)'/g)].map((m) => m[1]);
39
+ }
40
+
41
+ test('JOB_STATUSES is the expected canonical list', () => {
42
+ expect(JOB_STATUSES).toEqual(['pending', 'running', 'investigating', 'completed', 'failed', 'needs_review', 'quarantined']);
43
+ });
44
+
45
+ function sorted(list) {
46
+ return [...list].sort();
47
+ }
48
+
49
+ test('src/preload/api.d.ts ScheduleJobStatus matches JOB_STATUSES', () => {
50
+ const source = readSource('src/preload/api.d.ts');
51
+ const values = extractQuotedList(source, /export type ScheduleJobStatus = ([^;]+);/);
52
+ expect(sorted(values)).toEqual(sorted(JOB_STATUSES));
53
+ });
54
+
55
+ test('src/renderer/components/ui/StatusBadge.tsx JobStatus matches JOB_STATUSES', () => {
56
+ const source = readSource('src/renderer/components/ui/StatusBadge.tsx');
57
+ const values = extractQuotedList(source, /export type JobStatus = ([^\n]+)/);
58
+ expect(sorted(values)).toEqual(sorted(JOB_STATUSES));
59
+ });
60
+
61
+ test('src/renderer/components/SchedulePanel.tsx FilterStatus matches JOB_STATUSES plus "all"', () => {
62
+ const source = readSource('src/renderer/components/SchedulePanel.tsx');
63
+ const values = extractQuotedList(source, /type FilterStatus = ([^\n]+)/);
64
+ expect(sorted(values)).toEqual(sorted(['all', ...JOB_STATUSES]));
65
+ });
@@ -0,0 +1,152 @@
1
+ /**
2
+ * scheduleJobTransitions.test.cjs — unit tests for transitionJob(), the sole
3
+ * chokepoint for a ScheduleJob's `status` field (scheduleJobTransitions.cjs).
4
+ *
5
+ * Run: timeout 120 npx vitest run src/main/__tests__/scheduleJobTransitions.test.cjs
6
+ */
7
+ 'use strict';
8
+
9
+ import { test, expect } from 'vitest';
10
+ const fs = require('node:fs');
11
+ const crypto = require('node:crypto');
12
+ const {
13
+ transitionJob,
14
+ LEGAL_TRANSITIONS,
15
+ STATUS_HISTORY_CAP,
16
+ getRefusedTransitionCount,
17
+ _resetRefusedTransitionCountForTests,
18
+ } = require('../lib/scheduleJobTransitions.cjs');
19
+ const auditLog = require('../lib/auditLog.cjs');
20
+
21
+ function uniqueSlug(label) {
22
+ return `test-${label}-${crypto.randomUUID().slice(0, 8)}`;
23
+ }
24
+
25
+ function readAuditRecordsForSlug(slug) {
26
+ if (!fs.existsSync(auditLog.AUDIT_LOG_PATH)) return [];
27
+ return fs.readFileSync(auditLog.AUDIT_LOG_PATH, 'utf8')
28
+ .split('\n')
29
+ .filter(Boolean)
30
+ .map((line) => {
31
+ try { return JSON.parse(line); } catch { return null; }
32
+ })
33
+ .filter((record) => record && record.slug === slug);
34
+ }
35
+
36
+ test('a legal transition mutates the job, records statusHistory, and audits', () => {
37
+ const slug = uniqueSlug('legal');
38
+ const job = { slug, cwd: '/tmp/proj', status: 'pending' };
39
+
40
+ const ok = transitionJob(job, 'running', { reason: 'dispatched', source: 'test' });
41
+
42
+ expect(ok).toBe(true);
43
+ expect(job.status).toBe('running');
44
+ expect(job.statusHistory).toHaveLength(1);
45
+ expect(job.statusHistory[0]).toMatchObject({ from: 'pending', to: 'running', reason: 'dispatched', source: 'test' });
46
+ expect(typeof job.statusHistory[0].at).toBe('string');
47
+
48
+ const records = readAuditRecordsForSlug(slug);
49
+ expect(records).toHaveLength(1);
50
+ expect(records[0]).toMatchObject({ kind: 'job_transition', slug, from: 'pending', to: 'running', reason: 'dispatched', source: 'test', cwd: '/tmp/proj' });
51
+ });
52
+
53
+ test('an illegal transition refuses: job untouched, error logged, counter incremented, audit written', () => {
54
+ const slug = uniqueSlug('illegal');
55
+ const job = { slug, cwd: '/tmp/proj', status: 'pending' };
56
+ const before = getRefusedTransitionCount();
57
+
58
+ const ok = transitionJob(job, 'needs_review', { reason: 'bogus', source: 'test' });
59
+
60
+ expect(ok).toBe(false);
61
+ expect(job.status).toBe('pending'); // untouched
62
+ expect(job.statusHistory).toBeUndefined(); // never mutated
63
+ expect(getRefusedTransitionCount()).toBe(before + 1);
64
+
65
+ const records = readAuditRecordsForSlug(slug);
66
+ expect(records).toHaveLength(1);
67
+ expect(records[0]).toMatchObject({ kind: 'job_transition_refused', slug, from: 'pending', to: 'needs_review' });
68
+ });
69
+
70
+ test('an identity transition (status unchanged) is accepted as a no-op with no history entry', () => {
71
+ const slug = uniqueSlug('identity');
72
+ const job = { slug, cwd: '/tmp/proj', status: 'running' };
73
+
74
+ const ok = transitionJob(job, 'running', { reason: 'no-op', source: 'test' });
75
+
76
+ expect(ok).toBe(true);
77
+ expect(job.status).toBe('running');
78
+ expect(job.statusHistory).toBeUndefined();
79
+ expect(readAuditRecordsForSlug(slug)).toHaveLength(0);
80
+ });
81
+
82
+ test('statusHistory caps at STATUS_HISTORY_CAP entries, dropping the oldest first', () => {
83
+ const slug = uniqueSlug('cap');
84
+ const job = { slug, cwd: '/tmp/proj', status: 'pending' };
85
+
86
+ // pending -> running -> pending -> running -> ... alternate legally more
87
+ // than the cap, to exercise eviction.
88
+ const cycles = STATUS_HISTORY_CAP + 5;
89
+ for (let i = 0; i < cycles; i++) {
90
+ const to = job.status === 'pending' ? 'running' : 'pending';
91
+ expect(transitionJob(job, to, { reason: `cycle ${i}`, source: 'test' })).toBe(true);
92
+ }
93
+
94
+ expect(job.statusHistory).toHaveLength(STATUS_HISTORY_CAP);
95
+ // Oldest entries (early cycles) were dropped — the earliest surviving
96
+ // entry's reason should be from a late cycle, not "cycle 0".
97
+ expect(job.statusHistory[0].reason).not.toBe('cycle 0');
98
+ expect(job.statusHistory[job.statusHistory.length - 1].reason).toBe(`cycle ${cycles - 1}`);
99
+ });
100
+
101
+ test('LEGAL_TRANSITIONS covers every real scheduler.cjs edge', () => {
102
+ // Spot-check the edges scheduler.cjs actually exercises, so a future prune
103
+ // of this table can't silently break a real call site without a test
104
+ // failure here pointing at it.
105
+ const mustBeLegal = [
106
+ ['pending', 'running'],
107
+ ['pending', 'completed'],
108
+ ['pending', 'failed'],
109
+ ['running', 'completed'],
110
+ ['running', 'failed'],
111
+ ['running', 'needs_review'],
112
+ ['running', 'pending'],
113
+ ['investigating', 'failed'],
114
+ ['investigating', 'needs_review'],
115
+ ['investigating', 'pending'],
116
+ ['failed', 'investigating'],
117
+ ['failed', 'pending'],
118
+ ['failed', 'completed'],
119
+ ['needs_review', 'investigating'],
120
+ ['needs_review', 'pending'],
121
+ ['needs_review', 'completed'],
122
+ ['completed', 'pending'],
123
+ ];
124
+ for (const [from, to] of mustBeLegal) {
125
+ expect(LEGAL_TRANSITIONS[from]).toContain(to);
126
+ }
127
+ });
128
+
129
+ test('a genuinely nonsensical edge (completed -> running) is illegal', () => {
130
+ expect(LEGAL_TRANSITIONS.completed).not.toContain('running');
131
+ const slug = uniqueSlug('nonsense');
132
+ const job = { slug, cwd: '/tmp/proj', status: 'completed' };
133
+ expect(transitionJob(job, 'running', { reason: 'nope', source: 'test' })).toBe(false);
134
+ expect(job.status).toBe('completed');
135
+ });
136
+
137
+ test('transitionJob never throws on a missing/malformed job', () => {
138
+ expect(transitionJob(null, 'running', {})).toBe(false);
139
+ expect(transitionJob(undefined, 'running', {})).toBe(false);
140
+ // status undefined -> 'running' is not a legal edge from any known state —
141
+ // refused, not a crash.
142
+ expect(transitionJob({}, 'running', {})).toBe(false);
143
+ });
144
+
145
+ test('_resetRefusedTransitionCountForTests resets the counter', () => {
146
+ const slug = uniqueSlug('reset-counter');
147
+ const job = { slug, status: 'completed' };
148
+ transitionJob(job, 'running', {});
149
+ expect(getRefusedTransitionCount()).toBeGreaterThan(0);
150
+ _resetRefusedTransitionCountForTests();
151
+ expect(getRefusedTransitionCount()).toBe(0);
152
+ });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * scheduleJobTransitionsGrep.test.cjs — asserts scheduleJobTransitions.cjs's
3
+ * transitionJob() is the ONLY place a ScheduleJob's `status` field is
4
+ * assigned, per the PRD that introduced it (job-lifecycle chokepoint,
5
+ * mirroring epicMint.cjs's ownership of the Epic's status transition).
6
+ *
7
+ * A bare `job.status = '...'` reintroduces the exact failure class this
8
+ * module exists to close: no legality check, no statusHistory trail, no
9
+ * audit record — the 1021/1022 stall (2026-08-07) was undiagnosable from
10
+ * the app because status changes left no trace beyond a heartbeat count.
11
+ *
12
+ * Deliberately a plain grep, not an AST walk — this repo's other structural
13
+ * guards (check-unstable-selectors.cjs, check-conditional-hooks.cjs) use the
14
+ * same grep-based approach for the same reason: fast, dependency-free, and
15
+ * precise enough for a single well-known pattern.
16
+ *
17
+ * Run: timeout 120 npx vitest run src/main/__tests__/scheduleJobTransitionsGrep.test.cjs
18
+ */
19
+ 'use strict';
20
+
21
+ import { test, expect } from 'vitest';
22
+ const fs = require('node:fs');
23
+ const path = require('node:path');
24
+
25
+ const SCHEDULER_PATH = path.join(__dirname, '..', 'scheduler.cjs');
26
+
27
+ // Lines explicitly exempt: `entry.status = ...` inside listPrdsInternal
28
+ // assigns a freshly-synthesized PRD-listing row's display field, never a
29
+ // persisted ScheduleJob's status (no queue.json mutation, no
30
+ // statusHistory/audit trail applies). Each must carry the justifying
31
+ // comment referencing this test, so the exemption can't silently drift.
32
+ const ALLOWLISTED_PATTERN = /^\s*entry\.status = /;
33
+
34
+ test('no bare `.status = ` assignment on a job object outside scheduleJobTransitions.cjs', () => {
35
+ const lines = fs.readFileSync(SCHEDULER_PATH, 'utf8').split('\n');
36
+ const offenders = [];
37
+ lines.forEach((line, i) => {
38
+ if (!/\.status = /.test(line)) return;
39
+ if (ALLOWLISTED_PATTERN.test(line)) return;
40
+ offenders.push(`scheduler.cjs:${i + 1}: ${line.trim()}`);
41
+ });
42
+ expect(offenders).toEqual([]);
43
+ });
44
+
45
+ test('scheduler.cjs references transitionJob (the chokepoint is actually wired up)', () => {
46
+ const content = fs.readFileSync(SCHEDULER_PATH, 'utf8');
47
+ expect(content).toMatch(/require\(['"]\.\/lib\/scheduleJobTransitions\.cjs['"]\)/);
48
+ // At least as many call sites as the PRD's own enumerated list — guards
49
+ // against someone reverting individual sites back to bare assignment
50
+ // without reintroducing the literal `.status = ` grep hit (e.g. swapping
51
+ // in a different mutation helper that itself bypasses transitionJob).
52
+ const callSites = content.match(/transitionJob\(/g) || [];
53
+ expect(callSites.length).toBeGreaterThanOrEqual(17);
54
+ });
55
+
56
+ test('the allowlisted entry.status lines carry their justifying comment', () => {
57
+ const content = fs.readFileSync(SCHEDULER_PATH, 'utf8');
58
+ expect(content).toMatch(/exempt from the\s*\n\s*\/\/ transitionJob-only rule enforced by scheduleJobTransitionsGrep\.test\.cjs/);
59
+ });