claude-code-session-manager 0.130.2 → 0.131.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 (88) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +19 -2
  3. package/dist/assets/AgentLibrary-CYXre0J-.js +2 -0
  4. package/dist/assets/{AppSettings-Bpwynea4.js → AppSettings-xNSfCj8e.js} +2 -2
  5. package/dist/assets/{Button-DSoqrxCB.js → Button-BWljh5IK.js} +1 -1
  6. package/dist/assets/DocumentEditorPane-FUC2hZlp.js +1 -0
  7. package/dist/assets/Extensions-CsyUoklz.js +2 -0
  8. package/dist/assets/{History-DzMo9Otn.js → History-BvNmY9OQ.js} +2 -2
  9. package/dist/assets/{Library-C5wKMTSn.js → Library-DVXk77zA.js} +12 -12
  10. package/dist/assets/{ListDetail-DDQ1S0yu.js → ListDetail-DAAx__24.js} +1 -1
  11. package/dist/assets/{Panel-B-3NWUlv.js → Panel-g2D-e-RM.js} +1 -1
  12. package/dist/assets/ProjectClaudeConfig-BDuHJwaO.js +25 -0
  13. package/dist/assets/{ProvenanceBadge-CUChwz4Z.js → ProvenanceBadge-wew4_nf3.js} +1 -1
  14. package/dist/assets/Scheduler-CbeUIqD-.js +16 -0
  15. package/dist/assets/Settings-B23RsRfm.js +2 -0
  16. package/dist/assets/{SkillReferenceGraph-C6JEdypC.js → SkillReferenceGraph-BxQPCfsg.js} +1 -1
  17. package/dist/assets/Skills-4AR2FQrI.js +29 -0
  18. package/dist/assets/{SourceChip-DcBNYYhe.js → SourceChip-jrC0vjfw.js} +1 -1
  19. package/dist/assets/SystemPrompt-hHoBEnYb.js +1 -0
  20. package/dist/assets/{TiptapBody-DiVYC-_O.js → TiptapBody-FkUqxO9u.js} +1 -1
  21. package/dist/assets/{Toggle-Cs3k6I96.js → Toggle-DQMNWZKT.js} +1 -1
  22. package/dist/assets/ViewTabs-DGU0ZuxB.js +1 -0
  23. package/dist/assets/{VoiceButton-C3NLotUZ.js → VoiceButton-BPPvDllh.js} +1 -1
  24. package/dist/assets/{historyTotals-f-E0L9Xw.js → historyTotals-D8Oc3wUK.js} +1 -1
  25. package/dist/assets/index-9ajPMXBg.js +3097 -0
  26. package/dist/assets/{index-Bp8XE9A6.css → index-oXqzajWV.css} +1 -1
  27. package/dist/index.html +2 -2
  28. package/dist-web/app.css +1 -1
  29. package/dist-web/app.js +455 -427
  30. package/package.json +1 -1
  31. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +15 -5
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +8 -4
  34. package/scripts/scheduler-mcp-server.cjs +71 -0
  35. package/src/main/agentLibrary.cjs +81 -29
  36. package/src/main/agentsIpc.cjs +21 -16
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/index.cjs +9 -0
  39. package/src/main/ipcSchemas.cjs +35 -2
  40. package/src/main/lib/epic/epicMint.cjs +61 -6
  41. package/src/main/lib/epic/epicWorktreeMerge.cjs +11 -9
  42. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  43. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  44. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  45. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  46. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +4 -0
  47. package/src/main/lib/git/branchSweep.cjs +9 -3
  48. package/src/main/lib/git/gitExec.cjs +8 -1
  49. package/src/main/lib/git/gitWorktree.cjs +771 -96
  50. package/src/main/lib/git/jobWorktree.cjs +3 -0
  51. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  52. package/src/main/lib/mcpToolCatalog.cjs +28 -0
  53. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  54. package/src/main/lib/mdNetworkScan.cjs +555 -0
  55. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +18 -5
  56. package/src/main/lib/persona-macro/builtinMacros.cjs +22 -4
  57. package/src/main/lib/persona-macro/macroJobDispatch.cjs +17 -2
  58. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  59. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  60. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  61. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  62. package/src/main/lib/promptSessionSchema.cjs +5 -0
  63. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  64. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  65. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  66. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  67. package/src/main/lib/scheduler/terminalRunOutcome.cjs +61 -15
  68. package/src/main/projectPages.cjs +51 -7
  69. package/src/main/runVerify.cjs +8 -3
  70. package/src/main/scheduler/budget.cjs +146 -7
  71. package/src/main/scheduler/gitTreeGuard.cjs +92 -20
  72. package/src/main/scheduler/reviewLadder.cjs +60 -0
  73. package/src/main/scheduler.cjs +477 -53
  74. package/src/main/seedAgentPersonas.cjs +1 -1
  75. package/src/preload/api.d.ts +250 -7
  76. package/src/preload/apiSurface.json +28 -0
  77. package/src/preload/index.cjs +6 -0
  78. package/src/seed/agents/competitive-analyst.md +69 -0
  79. package/src/seed/agents/competitive-researcher.md +75 -0
  80. package/src/seed/agents/validator.md +2 -2
  81. package/dist/assets/AgentLibrary-Bfj862qf.js +0 -2
  82. package/dist/assets/Extensions-BziIutWV.js +0 -13
  83. package/dist/assets/Memory-Bq5T33d2.js +0 -25
  84. package/dist/assets/Scheduler-CkGHMXvo.js +0 -16
  85. package/dist/assets/Settings-DGxvyajs.js +0 -2
  86. package/dist/assets/SystemPrompt-CfozyVQx.js +0 -1
  87. package/dist/assets/ViewTabs-DFXH03tb.js +0 -1
  88. package/dist/assets/index-CuAfFXNd.js +0 -3086
@@ -0,0 +1,112 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * matrixStore.cjs — the one sanctioned writer of the Competitor matrix state
5
+ * (writer 'project-home', namespace project-pages). writeMatrix() validates,
6
+ * archives the previous valid matrix.json into history/ (newest HISTORY_KEEP
7
+ * kept), writes matrix.json + matrix.schema.json, and refreshes the HTML
8
+ * snapshot as the Pages library entry knowledge/competitive-matrix.
9
+ */
10
+
11
+ const fsp = require('node:fs/promises');
12
+ const path = require('node:path');
13
+ const config = require('../../config.cjs');
14
+ const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
15
+ const { validateMatrix, matrixJsonSchema, matrixPaths } = require('./competitiveMatrix.cjs');
16
+ const { renderMatrixHtml } = require('./matrixHtml.cjs');
17
+
18
+ const WRITER = 'project-home';
19
+ const HISTORY_KEEP = 50;
20
+ const PAGE_ID = 'competitive-matrix';
21
+ const HISTORY_NAME_RE = /^\d{8}T\d{6}Z\.json$/;
22
+
23
+ /** '2026-11-08T12:00:00.000Z' -> '20261108T120000Z'. */
24
+ function historyStamp(iso) {
25
+ const d = new Date(iso);
26
+ return d.toISOString().slice(0, 19).replace(/[-:]/g, '') + 'Z';
27
+ }
28
+
29
+ function write(abs, text) {
30
+ return config.writeTextAtomic(abs, text, { writer: WRITER });
31
+ }
32
+
33
+ /** Copy the current matrix.json into history/ if it is a valid matrix; -> path or null. */
34
+ async function archivePrevious(paths) {
35
+ let buf;
36
+ try {
37
+ buf = await fsp.readFile(paths.matrix);
38
+ } catch (e) {
39
+ if (e && e.code === 'ENOENT') return null;
40
+ throw e;
41
+ }
42
+ let value;
43
+ try {
44
+ value = JSON.parse(buf.toString('utf8'));
45
+ } catch {
46
+ return null;
47
+ }
48
+ const v = validateMatrix(value);
49
+ if (!v.ok) return null;
50
+ const dest = path.join(paths.history, `${historyStamp(v.matrix.updatedAt)}.json`);
51
+ await write(dest, buf.toString('utf8'));
52
+ return dest;
53
+ }
54
+
55
+ /** Remove all but the newest HISTORY_KEEP history files, through the same checks renameMigrated uses. */
56
+ async function pruneHistory(historyDir) {
57
+ let names;
58
+ try {
59
+ names = await fsp.readdir(historyDir);
60
+ } catch (e) {
61
+ if (e && e.code === 'ENOENT') return;
62
+ throw e;
63
+ }
64
+ const files = names.filter((n) => HISTORY_NAME_RE.test(n)).sort();
65
+ for (const name of files.slice(0, Math.max(0, files.length - HISTORY_KEEP))) {
66
+ const real = config.validatePath(path.join(historyDir, name));
67
+ config.validateWrite(real);
68
+ assertOpsWrite(real, WRITER);
69
+ await fsp.unlink(real);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * writeMatrix(realCwd, value, { model, renderHtml }) ->
75
+ * { ok: true, path, htmlPath, historyPath } | { ok: false, error }.
76
+ * Nothing is written when validation fails — of the matrix, or of the rendered
77
+ * HTML snapshot against validateHomeHtml (fail closed). renderHtml is a test seam.
78
+ */
79
+ async function writeMatrix(realCwd, value, { model = '', renderHtml = renderMatrixHtml } = {}) {
80
+ const v = validateMatrix(value);
81
+ if (!v.ok) return { ok: false, error: v.error };
82
+ const paths = matrixPaths(realCwd);
83
+ if (!paths) return { ok: false, error: 'not a project' };
84
+ const matrix = v.matrix;
85
+ const { schemas } = require('../../ipcSchemas.cjs');
86
+ const topic = `${matrix.product.name} vs ${matrix.competitors.map((c) => c.name).join(', ')}`.slice(0, 120);
87
+ const meta = schemas.projectPageMeta.parse({
88
+ id: PAGE_ID,
89
+ title: 'Competitor matrix',
90
+ topic,
91
+ createdAt: new Date().toISOString(),
92
+ model: String(model || '').slice(0, 60),
93
+ });
94
+ const html = renderHtml(matrix);
95
+ // Lazy: projectHomeAdminRoutes.cjs requires this module (circular at top level).
96
+ const { validateHomeHtml } = require('../feedback-remote/projectHomeAdminRoutes.cjs');
97
+ const rejection = validateHomeHtml(html);
98
+ if (rejection) return { ok: false, error: `matrix page rejected: ${rejection}` };
99
+
100
+ const historyPath = await archivePrevious(paths);
101
+ if (historyPath) await pruneHistory(paths.history);
102
+
103
+ await write(paths.matrix, JSON.stringify(value, null, 2) + '\n');
104
+ await write(paths.schema, JSON.stringify(matrixJsonSchema(), null, 2) + '\n');
105
+ const pageDir = opsPath(realCwd, 'project-pages', 'knowledge', PAGE_ID);
106
+ const htmlPath = path.join(pageDir, 'index.html');
107
+ await write(htmlPath, html);
108
+ await write(path.join(pageDir, 'meta.json'), JSON.stringify(meta, null, 2) + '\n');
109
+ return { ok: true, path: paths.matrix, htmlPath, historyPath };
110
+ }
111
+
112
+ module.exports = { writeMatrix, HISTORY_KEEP, PAGE_ID };
@@ -97,6 +97,11 @@ const PromptSessionSchema = z.object({
97
97
  // false = started with the develop loop (/develop skill, delegation guard, PRD queueing) switched off;
98
98
  // fixed for the life of its session; absent = on; only false is ever written.
99
99
  developLoop: z.boolean().optional(),
100
+ // true = this Epic adopted an existing CLI session as its claudeSessionId
101
+ // (ensureEpic's restoreSessionId) instead of a fresh one; absent otherwise.
102
+ // Only true is ever written: a false would fail here, and dropInvalidSessions
103
+ // (ipcSchemas.cjs) would then drop the whole stored row.
104
+ restoredSession: z.literal(true).optional(),
100
105
  // Absent on Epics minted before this field existed — those fall back to
101
106
  // rendering the flat `openingPrompt` as a single block (see
102
107
  // ChatTranscriptTurn.tsx's EpicIntakeCard).
@@ -32,6 +32,8 @@
32
32
  */
33
33
  'use strict';
34
34
 
35
+ const { isSafeEpicId } = require('../prd/prdLocations.cjs');
36
+
35
37
  function isFixPlanSlug(slug) {
36
38
  return /^\d+-fix-/.test(slug);
37
39
  }
@@ -59,4 +61,16 @@ function resolveIsFixPlan(slug, isFixPlan) {
59
61
  return isFixPlanSlug(slug);
60
62
  }
61
63
 
62
- module.exports = { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan };
64
+ /**
65
+ * The ONE repo-relative path a fix plan may name for a validation record
66
+ * (PRD 2883). Lives under the authored `reviews/` namespace — never under the
67
+ * gitignored `scheduler/` runtime folder, where the fix-plan PRD file itself
68
+ * sits. An unsafe/missing epicId drops the epic segment rather than
69
+ * concatenating it into a path.
70
+ */
71
+ function fixPlanRecordPath(epicId, fixSlug) {
72
+ const base = 'session-manager-operations/reviews/validation';
73
+ return isSafeEpicId(epicId) ? `${base}/${epicId}/${fixSlug}.md` : `${base}/${fixSlug}.md`;
74
+ }
75
+
76
+ module.exports = { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan, fixPlanRecordPath };
@@ -279,6 +279,40 @@ function mapOutcomeToGateOutcome(outcome) {
279
279
  }
280
280
  }
281
281
 
282
+ /**
283
+ * resolveReapGateOutcome(outcome, resultText) → 'passed'|'failed'|'never_ran'|'unknown'
284
+ *
285
+ * The reaper's gateOutcome for a non-pidless dead row. Unlike
286
+ * mapOutcomeToGateOutcome, 'passed' is NOT inferred from the CLI result
287
+ * event's subtype=success — that only says the session ended cleanly, not
288
+ * that a gate ran (Bilko job 1685 never ran its gate, printed no verdict, and
289
+ * was stamped 'passed'). 'passed' requires the run's own LAST
290
+ * `SCHEDULER_VERDICT:` line to say PASS. Each line is classified by
291
+ * runVerify.cjs's scanSentinel (the one SCHEDULER_VERDICT parser), scanned
292
+ * from the end so the final say wins.
293
+ */
294
+ function lastVerdictLine(resultText) {
295
+ if (typeof resultText !== 'string' || !resultText) return null;
296
+ // Lazy require: runVerify.cjs is a larger module; keep this lib cheap to load.
297
+ const { scanSentinel } = require('../../runVerify.cjs');
298
+ const lines = resultText.split('\n');
299
+ for (let i = lines.length - 1; i >= 0; i--) {
300
+ const v = scanSentinel({ resultText: lines[i].replace(/\r$/, '') }, []);
301
+ if (v) return v;
302
+ }
303
+ return null;
304
+ }
305
+
306
+ function resolveReapGateOutcome(outcome, resultText) {
307
+ if (outcome === 'failed') return 'failed';
308
+ if (outcome === 'no_result') return 'never_ran';
309
+ if (outcome !== 'success') return 'unknown';
310
+ const verdict = lastVerdictLine(resultText);
311
+ if (verdict === 'pass') return 'passed';
312
+ if (verdict === 'fail') return 'failed';
313
+ return 'unknown';
314
+ }
315
+
282
316
  // Max times an orphaned job may be re-queued before giving up (marking failed).
283
317
  // Single source of truth: both the in-app reaper (scheduler.cjs) and the external
284
318
  // offline watchdog (watchdogHelpers.cjs) import this so their give-up budgets can
@@ -527,6 +561,7 @@ module.exports = {
527
561
  isClaudeArgv,
528
562
  classifyRunOutcome,
529
563
  mapOutcomeToGateOutcome,
564
+ resolveReapGateOutcome,
530
565
  ORPHAN_REQUEUE_CAP,
531
566
  selectReapableJobs,
532
567
  findLiveProcessForJob,
@@ -107,6 +107,8 @@ const ScheduleJobSchema = z
107
107
  quietLeaseDegraded: z.boolean().optional(),
108
108
  // Salvaged uncommitted diff patch path (PRD 1098).
109
109
  salvagePatch: z.string().nullable().optional(),
110
+ // Pin of a dead run's uncommitted checkout work (refs/sm-uncommitted/...), PRD 2892.
111
+ uncommittedSnapshot: z.object({ sha: z.string(), ref: z.string() }).optional(),
110
112
  // Leftover-attribution fields: the newly-dirty paths a terminal run left
111
113
  // uncommitted, diffed against the persisted pre-run baseline
112
114
  // (guardBaseline/guardHeadBefore below). Set on EVERY terminal outcome
@@ -63,13 +63,14 @@ const STATUS_HISTORY_CAP = 20;
63
63
  * executor ever ran; kept distinct from 'completed' so unrun work can't
64
64
  * read as shipped), running->pending (halt/rate-limit reset,
65
65
  * transient-failure retry). Also reached with verdict
66
- * 'reaped_without_integration' (source 'reapDeadRunningJobs', PRD 1133): a
67
- * reaped job whose result event looked successful but whose work cannot
68
- * be shown to have landed — a worktree branch still holding unmerged
69
- * commits, or an in-place run whose HEAD never advanced during the run
70
- * window — is parked here instead of 'completed', naming the branch (or
71
- * the lack of any commit) so the stranded work is never silently treated
72
- * as shipped.
66
+ * 'reaped_without_integration' (source 'reapDeadRunningJobs', PRD 1133):
67
+ * the reaper lands a run that printed its own SCHEDULER_VERDICT: PASS
68
+ * line (integrating its worktree branch) and parks here only a run
69
+ * without one whose work cannot be shown to have landed — a worktree
70
+ * branch still holding unmerged commits, or an in-place run whose HEAD
71
+ * never advanced during the run window — naming the branch (or the lack
72
+ * of any commit) so the stranded work is never silently treated as
73
+ * shipped.
73
74
  * - investigating->failed|needs_review (restore prior status once the
74
75
  * investigation probe exits), investigating->completed (defensive: the
75
76
  * restored prior status could in principle be 'completed' if a caller
@@ -28,6 +28,64 @@ const COMPLETED_EQUIVALENT_VERDICTS = new Set([
28
28
  // the full runs/ directory (which can hold thousands of entries).
29
29
  const MAX_DIRS_SCANNED = 5;
30
30
 
31
+ // runsDir -> { dirFiles: Map<dirName, Set<slug>> } — slugs whose
32
+ // <slug>.meta.json exists in that run dir. Dirs older than IMMUTABLE_AFTER_MS
33
+ // are listed once and cached for good; younger ones are re-listed each call.
34
+ const indexes = new Map();
35
+ const IMMUTABLE_AFTER_MS = 24 * 60 * 60 * 1000;
36
+ const META_SUFFIX = '.meta.json';
37
+
38
+ /** Run-dir name (ISO with ':'/'.' -> '-') to epoch ms, or NaN. */
39
+ function runDirTime(name) {
40
+ const m = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/.exec(name);
41
+ if (!m) return NaN;
42
+ return Date.parse(`${m[1]}T${m[2]}:${m[3]}:${m[4]}.${m[5]}Z`);
43
+ }
44
+
45
+ function isYoung(name, now) {
46
+ const t = runDirTime(name);
47
+ return Number.isNaN(t) || now - t < IMMUTABLE_AFTER_MS;
48
+ }
49
+
50
+ function refreshIndex(runsDir, fsImpl) {
51
+ const names = fsImpl.readdirSync(runsDir); // throws -> caller returns null
52
+ if (!Array.isArray(names)) return new Map();
53
+ let idx = indexes.get(runsDir);
54
+ if (!idx) {
55
+ idx = { dirFiles: new Map() };
56
+ indexes.set(runsDir, idx);
57
+ }
58
+ const present = new Set(names);
59
+ for (const cached of idx.dirFiles.keys()) {
60
+ if (!present.has(cached)) idx.dirFiles.delete(cached);
61
+ }
62
+ const now = Date.now();
63
+ for (const name of names) {
64
+ if (idx.dirFiles.has(name) && !isYoung(name, now)) continue;
65
+ const slugs = new Set();
66
+ try {
67
+ for (const f of fsImpl.readdirSync(path.join(runsDir, name))) {
68
+ if (typeof f === 'string' && f.endsWith(META_SUFFIX)) slugs.add(f.slice(0, -META_SUFFIX.length));
69
+ }
70
+ } catch {
71
+ // unlistable dir (e.g. a stray file) — treat as having no runs
72
+ }
73
+ idx.dirFiles.set(name, slugs);
74
+ }
75
+ return idx.dirFiles;
76
+ }
77
+
78
+ function matchingDirs(slug, runsDir, fsImpl) {
79
+ const dirFiles = refreshIndex(runsDir, fsImpl);
80
+ const out = [];
81
+ for (const [name, slugs] of dirFiles) if (slugs.has(slug)) out.push(name);
82
+ return out;
83
+ }
84
+
85
+ function __resetRunIndexForTests() {
86
+ indexes.clear();
87
+ }
88
+
31
89
  /**
32
90
  * Returns { status: 'completed'|'failed', runId, finishedAt } for the newest
33
91
  * run directory containing a `<slug>.meta.json`, or null if none is found or
@@ -36,24 +94,12 @@ const MAX_DIRS_SCANNED = 5;
36
94
  */
37
95
  function latestTerminalOutcomeForSlug(slug, { runsDir, fsImpl = fs } = {}) {
38
96
  if (!slug || !runsDir) return null;
39
- let dirs;
97
+ let matches;
40
98
  try {
41
- dirs = fsImpl.readdirSync(runsDir);
99
+ matches = matchingDirs(slug, runsDir, fsImpl);
42
100
  } catch {
43
101
  return null;
44
102
  }
45
- if (!Array.isArray(dirs) || dirs.length === 0) return null;
46
-
47
- // Filter (cheap existence check) to dirs that actually have a run for this
48
- // slug, mirroring resolveRunId's existing pattern in scheduler.cjs — this
49
- // is a stat, not a read+parse.
50
- const matches = dirs.filter((d) => {
51
- try {
52
- return fsImpl.existsSync(path.join(runsDir, d, `${slug}.meta.json`));
53
- } catch {
54
- return false;
55
- }
56
- });
57
103
  if (!matches.length) return null;
58
104
 
59
105
  // Dir names are ISO timestamps with `:`/`.` replaced by `-` — lexical
@@ -110,4 +156,4 @@ function latestTerminalOutcomeForSlug(slug, { runsDir, fsImpl = fs } = {}) {
110
156
  return null;
111
157
  }
112
158
 
113
- module.exports = { latestTerminalOutcomeForSlug, COMPLETED_EQUIVALENT_VERDICTS, MAX_DIRS_SCANNED };
159
+ module.exports = { latestTerminalOutcomeForSlug, __resetRunIndexForTests, COMPLETED_EQUIVALENT_VERDICTS, MAX_DIRS_SCANNED };
@@ -10,6 +10,9 @@
10
10
  * home.html's content plus the demo video's { path, mtimeMs }, and a
11
11
  * refcounted per-cwd watcher pushes `project-pages:changed` for either. It
12
12
  * never writes content (watch()'s mkdir creates an empty directory only).
13
+ * mdNetwork() maps the project's markdown link network on demand
14
+ * (lib/mdNetworkScan.cjs) for the Tools pane. matrix() reads the saved
15
+ * Competitor matrix (lib/project-pages/competitiveMatrix.cjs readMatrix).
13
16
  */
14
17
 
15
18
  const { ipcMain } = require('electron');
@@ -17,9 +20,11 @@ const fs = require('node:fs');
17
20
  const path = require('node:path');
18
21
  const chokidar = require('chokidar');
19
22
  const config = require('./config.cjs');
20
- const { opsPath, assertOpsWrite } = require('./lib/opsOwnership.cjs');
23
+ const { opsPath, assertOpsWrite, resolveProjectRoot } = require('./lib/opsOwnership.cjs');
21
24
  const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
22
25
  const { listLibrary, migrateLegacy } = require('./lib/project-pages/pagesLibrary.cjs');
26
+ const { scanMdNetwork } = require('./lib/mdNetworkScan.cjs');
27
+ const { readMatrix } = require('./lib/project-pages/competitiveMatrix.cjs');
23
28
 
24
29
  let mainWindow = null;
25
30
  function attachWindow(window) {
@@ -35,19 +40,25 @@ function demoVideoPath(cwd) {
35
40
  }
36
41
 
37
42
  /**
38
- * Resolve `cwd`'s home.html path, treating the opsOwnership "ephemeral cwd"
39
- * throw (a tmpdir/linked-worktree project root) as "no path available"
43
+ * Resolve `realCwd`'s project root, treating the opsOwnership "ephemeral cwd"
44
+ * throw (a tmpdir/linked-worktree project root) as "no root available"
40
45
  * rather than letting it propagate.
41
46
  */
42
- function tryHomePath(realCwd) {
47
+ function tryProjectRoot(realCwd) {
43
48
  try {
44
- return { file: homePath(realCwd), ephemeral: false };
49
+ return { root: resolveProjectRoot(realCwd), ephemeral: false };
45
50
  } catch (e) {
46
- if (e.ephemeral) return { file: null, ephemeral: true };
51
+ if (e.ephemeral) return { root: null, ephemeral: true };
47
52
  throw e;
48
53
  }
49
54
  }
50
55
 
56
+ /** `realCwd`'s home.html path, or no path where tryProjectRoot finds no root. */
57
+ function tryHomePath(realCwd) {
58
+ const { root, ephemeral } = tryProjectRoot(realCwd);
59
+ return { file: ephemeral ? null : homePath(root), ephemeral };
60
+ }
61
+
51
62
  const EMPTY = () => ({ knowledge: [], videos: [], html: null, mtimeMs: null, demoVideo: null });
52
63
 
53
64
  /**
@@ -57,7 +68,7 @@ const EMPTY = () => ({ knowledge: [], videos: [], html: null, mtimeMs: null, dem
57
68
  */
58
69
  async function get({ cwd }) {
59
70
  const realCwd = config.validatePath(cwd);
60
- const { ephemeral } = tryHomePath(realCwd);
71
+ const { ephemeral } = tryProjectRoot(realCwd);
61
72
  if (ephemeral) return EMPTY();
62
73
  await migrateLegacy(realCwd);
63
74
  const { knowledge, videos } = await listLibrary(realCwd);
@@ -80,6 +91,35 @@ async function get({ cwd }) {
80
91
  };
81
92
  }
82
93
 
94
+ const MD_NETWORK_EPHEMERAL = 'refusing an ephemeral cwd (tmpdir or linked git worktree): no project to scan';
95
+
96
+ /**
97
+ * -> MdNetworkResult: the project's markdown link network from its root
98
+ * CLAUDE.md, scanned once per call (no watcher, no cache). `cwd` is validated
99
+ * like get() (an invalid path rejects); a cwd get() answers with EMPTY() gets
100
+ * `{ ok: false, error }`.
101
+ */
102
+ async function mdNetwork({ cwd }) {
103
+ const { root, ephemeral } = tryProjectRoot(config.validatePath(cwd));
104
+ if (ephemeral) return { ok: false, error: MD_NETWORK_EPHEMERAL };
105
+ return scanMdNetwork(root);
106
+ }
107
+
108
+ const MATRIX_EPHEMERAL = 'refusing an ephemeral cwd (tmpdir or linked git worktree): no project matrix';
109
+
110
+ /**
111
+ * -> CompetitorMatrixResult: the saved Competitor matrix, read once per call.
112
+ * Resolves the project root like mdNetwork(); `{ ok: true, matrix, error }`
113
+ * from readMatrix (matrix null when none / invalid, error set when invalid),
114
+ * or `{ ok: false, error }` when the cwd has no project root.
115
+ */
116
+ async function matrix({ cwd }) {
117
+ const { root, ephemeral } = tryProjectRoot(config.validatePath(cwd));
118
+ if (ephemeral) return { ok: false, error: MATRIX_EPHEMERAL };
119
+ const { matrix: m, error } = await readMatrix(root);
120
+ return { ok: true, matrix: m, error };
121
+ }
122
+
83
123
  /** True for paths whose change should refresh the library (relative to project-pages/). */
84
124
  function isLibraryPath(rel) {
85
125
  const parts = rel.split(path.sep);
@@ -251,6 +291,8 @@ async function deleteEntry(input) {
251
291
  function registerProjectPagesIpc() {
252
292
  const { schemas: s, validated: v } = require('./ipcSchemas.cjs');
253
293
  ipcMain.handle('project-pages:get', v(s.projectPagesCwd, get));
294
+ ipcMain.handle('project-pages:md-network', v(s.projectPagesCwd, mdNetwork));
295
+ ipcMain.handle('project-pages:matrix', v(s.projectPagesCwd, matrix));
254
296
  ipcMain.handle('project-pages:watch', v(s.projectPagesCwd, ({ cwd }) => watchOutput(cwd)));
255
297
  ipcMain.handle('project-pages:rename', v(s.projectPagesRename, renameEntry));
256
298
  ipcMain.handle('project-pages:delete', v(s.projectPagesDelete, deleteEntry));
@@ -264,6 +306,8 @@ module.exports = {
264
306
  attachWindow,
265
307
  registerProjectPagesIpc,
266
308
  get,
309
+ mdNetwork,
310
+ matrix,
267
311
  renameEntry,
268
312
  deleteEntry,
269
313
  watchOutput,
@@ -809,8 +809,10 @@ async function verifyRun({
809
809
  // bare PASS with no commit from one is still a strong silent-failure
810
810
  // signal and stays covered by this check.
811
811
  const isFixPlanJob = /^\d+-fix-/.test(queueEntry?.slug || '');
812
- // A transcript-reported commit that is not reachable from the repo was
813
- // dropped (detached HEAD, off-branch); no no-commit exemption may excuse it.
812
+ // A transcript-reported commit that exists in the repo but never landed
813
+ // on the checkout's HEAD (on no ref, for -merge-main slugs) was dropped
814
+ // (detached HEAD, off-branch, rewritten base); no no-commit exemption may
815
+ // excuse it.
814
816
  let unlandedTranscriptShas = [];
815
817
  if (sentinel === 'pass' && !commitEvidence && cwdIsGitRepo) {
816
818
  unlandedTranscriptShas = (transcriptCommitShas || [])
@@ -822,7 +824,10 @@ async function verifyRun({
822
824
  if (unlandedTranscriptShas.length > 0) {
823
825
  issues.push({
824
826
  verdict: 'run_commit_not_landed',
825
- reason: 'SCHEDULER_VERDICT: PASS but the transcript reports a commit that is not reachable from the repo: '
827
+ reason: 'SCHEDULER_VERDICT: PASS but the transcript reports a commit that '
828
+ + (isMergeMainSlug(queueEntry?.slug)
829
+ ? 'is on no ref: '
830
+ : "exists in the repo but never landed on the checkout's HEAD: ")
826
831
  + unlandedTranscriptShas.join(', '),
827
832
  priority: 1,
828
833
  downgradeTo: 'needs_review',
@@ -195,7 +195,7 @@ function computeJobBudgetMs(estimateMinutes, { factor, floorMs, ceilingMs } = {}
195
195
  }
196
196
 
197
197
  /**
198
- * classifyBudgetKill(res, landedCommitEvidence) → { status, reason, landedCommit } | null
198
+ * classifyBudgetKill(res, landedCommitEvidence, context?) → { status, reason, landedCommit } | null
199
199
  *
200
200
  * Pure. `res` is executeJob's resolved outcome — only fires when
201
201
  * `res.killedByWatchdog === 'budget'` (stamped by the budget watchdog inside
@@ -212,14 +212,151 @@ function computeJobBudgetMs(estimateMinutes, { factor, floorMs, ceilingMs } = {}
212
212
  * commit-guard evidence check the plain sigterm/exit paths already use, is
213
213
  * threaded onto the row as `landedCommit` so a job that HAD already
214
214
  * committed before overrunning is still adjudicated on its git evidence.
215
+ *
216
+ * `context` (optional) is describeBudgetKillContext's output plus an optional
217
+ * `commits` list ({ sha, subject }[], the run's own commits, read by the
218
+ * caller). Only when `context.inFinishReview` is true does the reason change:
219
+ * it names the review call the kill landed in, what had already landed, and
220
+ * which push/publish side effects had already run. Otherwise the reason is
221
+ * byte-identical to the context-less one.
222
+ *
223
+ * @param {any} res
224
+ * @param {string|null|undefined} landedCommitEvidence
225
+ * @param {{ inFinishReview?: boolean, reviewSkill?: string|null, sideEffects?: string[], commits?: Array<{ sha: string, subject: string }>|null }|null} [context]
215
226
  */
216
- function classifyBudgetKill(res, landedCommitEvidence) {
227
+ function classifyBudgetKill(res, landedCommitEvidence, context) {
217
228
  if (!res || res.killedByWatchdog !== 'budget') return null;
218
- return {
219
- status: 'needs_review',
220
- reason: res.budgetKillReason || `wall-clock budget exceeded (exit ${res.exitCode})`,
221
- landedCommit: landedCommitEvidence || null,
222
- };
229
+ const baseReason = res.budgetKillReason || `wall-clock budget exceeded (exit ${res.exitCode})`;
230
+ const landedCommit = landedCommitEvidence || null;
231
+ if (!context || context.inFinishReview !== true) {
232
+ return { status: 'needs_review', reason: baseReason, landedCommit };
233
+ }
234
+ // Keep the ran/budget/estimate figures: everything after the generic prefix.
235
+ const figures = baseReason.replace(/^wall-clock budget exceeded:?\s*/, '');
236
+ const skillLabel = String(context.reviewSkill || 'code-review');
237
+ const skillShown = skillLabel.length > REVIEW_SKILL_MAX_CHARS ? `${skillLabel.slice(0, REVIEW_SKILL_MAX_CHARS)}…` : skillLabel;
238
+ let reason = `wall-clock budget exceeded inside the finish-protocol review (/${skillShown} never returned)`;
239
+ if (figures) reason += `: ${figures}`;
240
+ const commits = Array.isArray(context.commits) ? context.commits.slice(0, 5) : [];
241
+ if (commits.length > 0) {
242
+ reason += `; work already landed: ${commits.map((c) => `${String(c.sha).slice(0, 7)} ${c.subject}`.trim()).join(', ')}`;
243
+ } else if (landedCommit) {
244
+ reason += `; work already landed: ${String(landedCommit).slice(0, 7)}`;
245
+ } else {
246
+ reason += '; no commit landed on the job branch';
247
+ }
248
+ const sideEffects = Array.isArray(context.sideEffects) ? context.sideEffects : [];
249
+ if (sideEffects.length > 0) reason += `; side effects already run: ${sideEffects.join(' | ')}`;
250
+ return { status: 'needs_review', reason, landedCommit };
251
+ }
252
+
253
+ const REVIEW_SKILL_PREFIXES = ['code-review', 'security-review'];
254
+ const SIDE_EFFECT_MAX = 5;
255
+ const SIDE_EFFECT_MAX_CHARS = 120;
256
+ const REVIEW_SKILL_MAX_CHARS = 80;
257
+ const SIDE_EFFECT_PATTERNS = ['git push', 'npm publish'];
258
+
259
+ /**
260
+ * sideEffectSegments(command) → string[]
261
+ *
262
+ * Pure. Splits a Bash command on &&, ||, ;, | and newlines (no shell parser —
263
+ * a split inside a quoted string is acceptable), trims each segment and keeps
264
+ * the ones naming `git push` / `npm publish`, each cut to 120 chars. So a real
265
+ * executor's `cd /tmp/x && git add a && git commit -m y && git push origin
266
+ * HEAD:main` is labelled by its push, not by its leading `cd`.
267
+ *
268
+ * @param {string} command
269
+ * @returns {string[]}
270
+ */
271
+ function sideEffectSegments(command) {
272
+ return String(command)
273
+ .split(/&&|\|\||;|\||\n/)
274
+ .map((seg) => seg.trim())
275
+ .filter((seg) => SIDE_EFFECT_PATTERNS.some((p) => seg.includes(p)))
276
+ .map((seg) => seg.slice(0, SIDE_EFFECT_MAX_CHARS));
277
+ }
278
+
279
+ /**
280
+ * describeBudgetKillContext(logText) → { inFinishReview, reviewSkill, sideEffects }
281
+ *
282
+ * Pure, never throws. Parses a `claude -p --output-format stream-json` run log
283
+ * (or its tail — a torn first line is just skipped) and answers: was the
284
+ * executor's LAST top-level tool call a review Skill (/code-review,
285
+ * /security-review) that never got its tool_result — i.e. did the budget kill
286
+ * land inside the finish-protocol review? `sideEffects` lists the `git push` /
287
+ * `npm publish` command segments (see sideEffectSegments) of Bash calls that had already succeeded (a matching
288
+ * tool_result with is_error !== true), deduped, at most 5, each ≤ 120 chars.
289
+ * Subagent events (non-null parent_tool_use_id) never count as the last
290
+ * top-level tool_use.
291
+ *
292
+ * @param {string} logText
293
+ * @returns {{ inFinishReview: boolean, reviewSkill: string|null, sideEffects: string[] }}
294
+ */
295
+ function describeBudgetKillContext(logText) {
296
+ const empty = { inFinishReview: false, reviewSkill: null, sideEffects: [] };
297
+ try {
298
+ if (typeof logText !== 'string' || !logText) return empty;
299
+ /** @type {any} */
300
+ let lastTopToolUse = null;
301
+ /** @type {Map<string, boolean>} tool_use_id → is_error */
302
+ const results = new Map();
303
+ // true once a tool_result answers the current lastTopToolUse
304
+ let answeredAfterLast = false;
305
+ /** @type {Array<{ id: string, command: string }>} */
306
+ const bashCalls = [];
307
+ for (const raw of logText.split('\n')) {
308
+ const line = raw.trim();
309
+ if (!line || line[0] !== '{') continue;
310
+ let ev;
311
+ try { ev = JSON.parse(line); } catch { continue; }
312
+ if (!ev || typeof ev !== 'object') continue;
313
+ const content = ev.message && Array.isArray(ev.message.content) ? ev.message.content : null;
314
+ if (!content) continue;
315
+ const topLevel = ev.parent_tool_use_id == null;
316
+ if (ev.type === 'assistant') {
317
+ for (const block of content) {
318
+ if (!block || block.type !== 'tool_use') continue;
319
+ if (block.name === 'Bash' && block.input && typeof block.input.command === 'string' && typeof block.id === 'string') {
320
+ bashCalls.push({ id: block.id, command: block.input.command });
321
+ }
322
+ if (topLevel) {
323
+ lastTopToolUse = block;
324
+ answeredAfterLast = false;
325
+ }
326
+ }
327
+ } else if (ev.type === 'user') {
328
+ for (const block of content) {
329
+ if (!block || block.type !== 'tool_result' || typeof block.tool_use_id !== 'string') continue;
330
+ results.set(block.tool_use_id, block.is_error === true);
331
+ if (lastTopToolUse && block.tool_use_id === lastTopToolUse.id) answeredAfterLast = true;
332
+ }
333
+ }
334
+ }
335
+ let inFinishReview = false;
336
+ let reviewSkill = null;
337
+ if (lastTopToolUse && lastTopToolUse.name === 'Skill' && !answeredAfterLast) {
338
+ const input = lastTopToolUse.input || {};
339
+ const skill = typeof input.skill === 'string' ? input.skill.trim() : '';
340
+ if (REVIEW_SKILL_PREFIXES.some((p) => skill.startsWith(p))) {
341
+ inFinishReview = true;
342
+ const args = typeof input.args === 'string' ? input.args.trim() : '';
343
+ reviewSkill = args ? `${skill} ${args}` : skill;
344
+ }
345
+ }
346
+ /** @type {string[]} */
347
+ const sideEffects = [];
348
+ for (const call of bashCalls) {
349
+ if (sideEffects.length >= SIDE_EFFECT_MAX) break;
350
+ if (!results.has(call.id) || results.get(call.id) === true) continue;
351
+ for (const seg of module.exports.sideEffectSegments(call.command)) {
352
+ if (sideEffects.length >= SIDE_EFFECT_MAX) break;
353
+ if (!sideEffects.includes(seg)) sideEffects.push(seg);
354
+ }
355
+ }
356
+ return { inFinishReview, reviewSkill, sideEffects };
357
+ } catch {
358
+ return empty;
359
+ }
223
360
  }
224
361
 
225
362
  /**
@@ -598,6 +735,8 @@ module.exports = {
598
735
  findOverrunningJobs,
599
736
  computeJobBudgetMs,
600
737
  classifyBudgetKill,
738
+ describeBudgetKillContext,
739
+ sideEffectSegments,
601
740
  isJobBudgetExempt,
602
741
  shouldKillForBudget,
603
742
  resolveBudgetKillOutcome,