claude-code-session-manager 0.125.1 → 0.127.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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +71 -9
  3. package/bin/supervise.cjs +84 -0
  4. package/dist/assets/{AgentLibrary-DjEH5SoY.js → AgentLibrary-DKQznr7o.js} +1 -1
  5. package/dist/assets/{Button-B8NLivk-.js → Button-CZXqmIiM.js} +1 -1
  6. package/dist/assets/{DataModel-CHiBk8m_.js → DataModel-piyV33To.js} +1 -1
  7. package/dist/assets/{History-DttgrJO0.js → History-BxwtrKF2.js} +1 -1
  8. package/dist/assets/{Hooks-Bvy0BH1u.js → Hooks-DogeSPII.js} +1 -1
  9. package/dist/assets/{Library-UbBOgkkP.js → Library-BDt6EeQQ.js} +1 -1
  10. package/dist/assets/{ListDetail-xOyOpVZX.js → ListDetail-CwS-LKar.js} +1 -1
  11. package/dist/assets/{McpServers-CoGL0ddv.js → McpServers-D2HVljgS.js} +1 -1
  12. package/dist/assets/{Memory-Cise856d.js → Memory-hNzuOGn8.js} +1 -1
  13. package/dist/assets/{Panel-Cj72VO5s.js → Panel-BLDrsUeq.js} +1 -1
  14. package/dist/assets/{Permissions-BoJ9AB-G.js → Permissions-DzZ5vaJW.js} +1 -1
  15. package/dist/assets/{Plugins-DfT24sAZ.js → Plugins-Cz9yaxzG.js} +2 -2
  16. package/dist/assets/{ProvenanceBadge-ChkIslT4.js → ProvenanceBadge-CCgLO4m9.js} +1 -1
  17. package/dist/assets/{SaveBar-RCXr0jey.js → SaveBar-Shmn699J.js} +1 -1
  18. package/dist/assets/{Scheduler-B70tknnx.js → Scheduler-Bqr0WHNd.js} +1 -1
  19. package/dist/assets/{ScopeSwitcher-p_tgO5Sa.js → ScopeSwitcher-CBx1fB5g.js} +1 -1
  20. package/dist/assets/{Settings-wHiAxTfI.js → Settings-Ci8in-yF.js} +1 -1
  21. package/dist/assets/{SkillReferenceGraph-D_Pt35vb.js → SkillReferenceGraph-BWwljba8.js} +1 -1
  22. package/dist/assets/{Skills-DUvOrgw9.js → Skills-BON6o-c4.js} +1 -1
  23. package/dist/assets/{SystemPrompt-BrNIdy68.js → SystemPrompt-D5epIYYs.js} +1 -1
  24. package/dist/assets/{TagLibrary-CDRatxXG.js → TagLibrary-C2qDZROJ.js} +1 -1
  25. package/dist/assets/{TiptapBody-BF8PxUDj.js → TiptapBody-SZhI3-bW.js} +1 -1
  26. package/dist/assets/{Toggle-CQH8NGXW.js → Toggle-C_qFDG0g.js} +1 -1
  27. package/dist/assets/{ViewTabs-DwnxqCVs.js → ViewTabs-C9q5WCEd.js} +1 -1
  28. package/dist/assets/{historyTotals-KINLTHQ4.js → historyTotals-BCl7IOhY.js} +1 -1
  29. package/dist/assets/{index-CfR3NU2t.js → index-CMIYLbPb.js} +581 -581
  30. package/dist/assets/{settingsSchema-BUcHqLnt.js → settingsSchema-BBrRBrBr.js} +1 -1
  31. package/dist/assets/{skillFrontmatter-BwwkyuMD.js → skillFrontmatter-B01qJk6N.js} +1 -1
  32. package/dist/assets/{useAgentsDirWatch-Coem9Wg-.js → useAgentsDirWatch-CuR3GSjS.js} +1 -1
  33. package/dist/index.html +1 -1
  34. package/dist-web/{assets/app.js → app.js} +351 -351
  35. package/dist-web/index.html +2 -2
  36. package/package.json +2 -2
  37. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  38. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  39. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +10 -2
  40. package/scripts/scheduler-mcp-server.cjs +56 -5
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +73 -6
  43. package/src/main/crashDiagnostics.cjs +83 -8
  44. package/src/main/health.cjs +16 -5
  45. package/src/main/index.cjs +32 -0
  46. package/src/main/lib/chatBootRecovery.cjs +136 -0
  47. package/src/main/lib/chatInflight.cjs +88 -0
  48. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  49. package/src/main/lib/epic/epicMint.cjs +6 -0
  50. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  51. package/src/main/lib/epic/epicValidationHook.cjs +14 -2
  52. package/src/main/lib/epic/epicWorktreeMerge.cjs +9 -1
  53. package/src/main/lib/feedback-remote/autoStartedSession.cjs +102 -0
  54. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +130 -15
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  56. package/src/main/lib/feedback-remote/remoteAssets.cjs +25 -1
  57. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +13 -2
  58. package/src/main/lib/git/gitExec.cjs +11 -1
  59. package/src/main/lib/git/gitWorktree.cjs +255 -9
  60. package/src/main/lib/git/jobWorktree.cjs +5 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +27 -5
  62. package/src/main/lib/persona-macro/builtinMacros.cjs +12 -1
  63. package/src/main/lib/persona-macro/macroLibrary.cjs +78 -3
  64. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  65. package/src/main/lib/prd/prdCreate.cjs +5 -1
  66. package/src/main/lib/prd/prdDeclaredPaths.cjs +29 -2
  67. package/src/main/lib/process/childWithLog.cjs +38 -95
  68. package/src/main/lib/process/memoryScope.cjs +140 -0
  69. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  70. package/src/main/lib/process/procIdentity.cjs +10 -3
  71. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  72. package/src/main/lib/promptSessionSchema.cjs +6 -1
  73. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  74. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  75. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  76. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  77. package/src/main/lib/scheduler/landedSinceRun.cjs +13 -5
  78. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  79. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  80. package/src/main/lib/scheduler/rcaReport.cjs +1 -0
  81. package/src/main/lib/scheduler/reviewNotice.cjs +1 -0
  82. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  83. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  84. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  85. package/src/main/runVerify.cjs +59 -110
  86. package/src/main/scheduler/budget.cjs +31 -0
  87. package/src/main/scheduler/gitTreeGuard.cjs +51 -1
  88. package/src/main/scheduler/prdPaths.cjs +54 -0
  89. package/src/main/scheduler/reviewLadder.cjs +28 -5
  90. package/src/main/scheduler/starvation.cjs +22 -0
  91. package/src/main/scheduler.cjs +662 -90
  92. package/src/main/templates/PRD_AUTHORING.md +10 -3
  93. package/src/main/usage.cjs +4 -2
  94. package/src/main/webRemote.cjs +3 -0
  95. package/src/preload/api.d.ts +19 -3
  96. package/src/seed/agents/demo-video-builder.md +62 -14
  97. /package/dist-web/{assets/app.css → app.css} +0 -0
@@ -0,0 +1,147 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * cpuSample.cjs — measured machine-wide CPU use over a real window.
5
+ *
6
+ * The 1-minute load average counts parked D-state tasks and short bursts, so
7
+ * it can read high on a mostly idle machine (2026-11-01, 14 CPUs: 25 D-state
8
+ * tasks gave loadavg1 22.39 while the CPU was only 24% busy over 75 s). This
9
+ * helper derives busy/total from cumulative counters over a window of about a
10
+ * minute instead. Pure and injectable (`read`, `now`).
11
+ */
12
+
13
+ const fs = require('node:fs');
14
+ const os = require('node:os');
15
+
16
+ // Matches the 1-minute load average's horizon.
17
+ const DEFAULT_WINDOW_MS = 60_000;
18
+ // Anything shorter is a snapshot, not a sample: the two readings that started
19
+ // this work were 8 s long and fell in quiet gaps.
20
+ const MIN_WINDOW_MS = 20_000;
21
+ const MAX_WINDOW_MS = 180_000;
22
+ const MIN_SPACING_MS = 5_000;
23
+
24
+ /**
25
+ * Parse the aggregate `cpu ` line of /proc/stat into { busy, iowait, total }.
26
+ * Columns: user nice system idle iowait irq softirq steal guest guest_nice.
27
+ * Only the first 8 count (guest time is already inside user).
28
+ * - iowait is not busy: the CPU is idle during it and the load gate judges CPU
29
+ * only. Swap-in waits land there on this host, and the memory gate and swap
30
+ * clamp run before the load gate. It is carried as its own figure. os.cpus()
31
+ * has no such column, so macOS matches.
32
+ * - nice counts as busy: every Session Manager process here runs at nice 12,
33
+ * so nice is the largest column on this box.
34
+ * @param {string} text
35
+ * @returns {{ busy: number, iowait: number, total: number } | null}
36
+ */
37
+ function parseProcStat(text) {
38
+ if (typeof text !== 'string' || !text) return null;
39
+ const line = text.split('\n').find((l) => l.startsWith('cpu '));
40
+ if (!line) return null;
41
+ const parts = line.trim().split(/\s+/).slice(1, 9);
42
+ if (parts.length < 4) return null;
43
+ const nums = [];
44
+ for (const p of parts) {
45
+ const n = Number(p);
46
+ if (!Number.isFinite(n)) return null;
47
+ nums.push(n);
48
+ }
49
+ while (nums.length < 8) nums.push(0);
50
+ const total = nums.reduce((a, b) => a + b, 0);
51
+ const idle = nums[3];
52
+ const iowait = nums[4];
53
+ return { busy: total - idle - iowait, iowait, total };
54
+ }
55
+
56
+ /**
57
+ * @param {{ platform?: string, readFile?: (p: string) => string, cpus?: () => import('node:os').CpuInfo[] }} [deps]
58
+ * @returns {{ busy: number, iowait: number, total: number } | null}
59
+ */
60
+ function readCpuTimes({
61
+ platform = process.platform,
62
+ readFile = (p) => fs.readFileSync(p, 'utf8'),
63
+ cpus = () => os.cpus(),
64
+ } = {}) {
65
+ try {
66
+ if (platform === 'linux') return parseProcStat(readFile('/proc/stat'));
67
+ const list = cpus();
68
+ if (!Array.isArray(list) || list.length === 0) return null;
69
+ let busy = 0;
70
+ let idle = 0;
71
+ for (const c of list) {
72
+ const t = c.times;
73
+ busy += t.user + t.nice + t.sys + t.irq;
74
+ idle += t.idle;
75
+ }
76
+ if (![busy, idle].every(Number.isFinite)) return null;
77
+ return { busy, iowait: 0, total: busy + idle };
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * @param {{ read?: () => ({busy:number,iowait?:number,total:number}|null), now?: () => number,
85
+ * windowMs?: number, minWindowMs?: number, maxWindowMs?: number, minSpacingMs?: number }} [opts]
86
+ */
87
+ function createCpuSampler({
88
+ read = readCpuTimes,
89
+ now = () => Date.now(),
90
+ windowMs = DEFAULT_WINDOW_MS,
91
+ minWindowMs = MIN_WINDOW_MS,
92
+ maxWindowMs = MAX_WINDOW_MS,
93
+ minSpacingMs = MIN_SPACING_MS,
94
+ } = {}) {
95
+ /** @type {{ at: number, busy: number, iowait: number, total: number }[]} */
96
+ let entries = [];
97
+
98
+ function observe() {
99
+ const t = now();
100
+ const r = read();
101
+ if (!r) return;
102
+ const newest = entries[entries.length - 1];
103
+ if (newest && t - newest.at < minSpacingMs) return;
104
+ entries.push({ at: t, busy: r.busy, iowait: r.iowait ?? 0, total: r.total });
105
+ entries = entries.filter((e) => t - e.at <= maxWindowMs);
106
+ }
107
+
108
+ function sample() {
109
+ const t = now();
110
+ const r = read();
111
+ if (!r) return null;
112
+ let best = null;
113
+ let bestDiff = Infinity;
114
+ for (const e of entries) {
115
+ const age = t - e.at;
116
+ if (age < minWindowMs || age > maxWindowMs) continue;
117
+ const diff = Math.abs(age - windowMs);
118
+ if (diff < bestDiff) {
119
+ best = e;
120
+ bestDiff = diff;
121
+ }
122
+ }
123
+ if (!best) return null;
124
+ const dBusy = r.busy - best.busy;
125
+ const dTotal = r.total - best.total;
126
+ const dIowait = (r.iowait ?? 0) - best.iowait;
127
+ // Per-CPU idle and iowait counters can step backwards.
128
+ if (dTotal <= 0 || dBusy < 0) return null;
129
+ return {
130
+ busyFraction: Math.min(1, dBusy / dTotal),
131
+ iowaitFraction: Math.min(1, Math.max(0, dIowait / dTotal)),
132
+ windowMs: t - best.at,
133
+ };
134
+ }
135
+
136
+ return { observe, sample };
137
+ }
138
+
139
+ module.exports = {
140
+ parseProcStat,
141
+ readCpuTimes,
142
+ createCpuSampler,
143
+ DEFAULT_WINDOW_MS,
144
+ MIN_WINDOW_MS,
145
+ MAX_WINDOW_MS,
146
+ MIN_SPACING_MS,
147
+ };
@@ -389,6 +389,45 @@ function resolveGate(prdText) {
389
389
  return { source: 'absent', sequence: [] };
390
390
  }
391
391
 
392
+ const TIMEOUT_UNIT_MS = { '': 1000, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
393
+
394
+ /** Time one `&&` step may take: every `timeout N` outside quotes, else the default. */
395
+ function stepTimeoutMs(step) {
396
+ const bare = step.replace(/'[^']*'|"[^"]*"/g, ' ');
397
+ let sum = 0;
398
+ for (const m of bare.matchAll(/(?:^|\s)timeout\s+(\d+)([smhd]?)(?=\s|$)/g)) {
399
+ sum += parseInt(m[1], 10) * TIMEOUT_UNIT_MS[m[2]];
400
+ }
401
+ return sum || DEFAULT_GATE_TIMEOUT_MS;
402
+ }
403
+
404
+ /**
405
+ * The most one full pass over a PRD's gate can take: the sum of every step's
406
+ * `timeout`. Not built on resolveGate because that returns an empty sequence
407
+ * for a gate the no-shell parser refuses (Bilko-Game-Academy 872-fix-e2e-no-gpu-suite
408
+ * read as 0 minutes though it is 47.5), yet a validator runs gates through
409
+ * Bash, so that time is real. Returns 0 for a none gate, a PRD with no gate,
410
+ * or non-string/empty input.
411
+ *
412
+ * @param {unknown} prdText
413
+ * @returns {number} milliseconds
414
+ */
415
+ function gateTimeoutMs(prdText) {
416
+ if (!prdText || typeof prdText !== 'string') return 0;
417
+ const explicit = readExplicitGate(prdText);
418
+ if (explicit) {
419
+ if (explicit.kind === 'none') return 0;
420
+ let total = 0;
421
+ for (const chain of explicit.chains) {
422
+ for (const seg of splitOnAndAnd(chain)) {
423
+ if (seg.trim()) total += stepTimeoutMs(seg.trim());
424
+ }
425
+ }
426
+ return total;
427
+ }
428
+ return resolveGate(prdText).sequence.reduce((sum, step) => sum + step.timeoutMs, 0);
429
+ }
430
+
392
431
  /**
393
432
  * The gate as an ordered list of no-shell commands: [{argv, timeoutMs}, …].
394
433
  * Empty when there is no parseable gate or the PRD opted out with `gate: none`
@@ -918,6 +957,7 @@ module.exports = {
918
957
  explainChain,
919
958
  isNoneGate,
920
959
  resolveGate,
960
+ gateTimeoutMs,
921
961
  runGateSequence,
922
962
  runIsolatedSequence,
923
963
  extractSection,
@@ -0,0 +1,204 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * jobLeftovers.cjs — read-only detection of processes that outlived their
5
+ * scheduler job.
6
+ *
7
+ * Why it exists: the post-exit group sweep only reaches the job's own process
8
+ * group. A child that called setsid (pnpm dev trees: concurrently, tsx watch,
9
+ * vite; Playwright web servers) escapes that group, so run metas report
10
+ * leakedDescendants [] while the tree runs for days.
11
+ *
12
+ * Identity is the SM_SCHEDULER_JOB_SLUG environment marker every job process
13
+ * inherits — never cwd or command line (the scheduler's own git/gate commands
14
+ * run in retained worktrees without the marker). Linux /proc only; no signal
15
+ * is sent here.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+ const { isClaudeArgv } = require('./reaperHelpers.cjs');
21
+ const procIdentity = require('../process/procIdentity.cjs');
22
+
23
+ const LEFTOVER_GRACE_MS = 120000;
24
+ const MARKER = 'SM_SCHEDULER_JOB_SLUG=';
25
+ const LIVE_STATUSES = new Set(['running', 'investigating', 'pending']);
26
+
27
+ function parseStat(raw) {
28
+ const open = raw.indexOf('(');
29
+ const close = raw.lastIndexOf(')');
30
+ if (open === -1 || close === -1 || close < open) return null;
31
+ const f = raw.slice(close + 1).trim().split(/\s+/);
32
+ const ppid = Number(f[1]);
33
+ if (f.length < 20 || !Number.isFinite(ppid)) return null;
34
+ return {
35
+ comm: raw.slice(open + 1, close),
36
+ state: f[0],
37
+ ppid,
38
+ tty: Number(f[4]) || 0,
39
+ utime: Number(f[11]) || 0,
40
+ stime: Number(f[12]) || 0,
41
+ startTicks: Number(f[19]) || 0,
42
+ };
43
+ }
44
+
45
+ function scanJobProcesses({ fsImpl = fs, procRoot = process.env.SM_PROC_ROOT || '/proc', platform = process.platform } = {}) {
46
+ const empty = () => ({ procs: [], parentOf: new Map() });
47
+ if (platform !== 'linux') return empty();
48
+ let names;
49
+ try {
50
+ names = fsImpl.readdirSync(procRoot);
51
+ } catch {
52
+ return empty();
53
+ }
54
+ let uptime = 0;
55
+ try {
56
+ uptime = Number(String(fsImpl.readFileSync(path.join(procRoot, 'uptime'), 'utf8')).split(/\s+/)[0]) || 0;
57
+ } catch { /* leave 0 */ }
58
+
59
+ const procs = [];
60
+ const parentOf = new Map();
61
+ for (const name of names) {
62
+ if (!/^\d+$/.test(name)) continue;
63
+ const pid = Number(name);
64
+ const dir = path.join(procRoot, name);
65
+ try {
66
+ const st = parseStat(String(fsImpl.readFileSync(path.join(dir, 'stat'), 'utf8')));
67
+ if (!st) continue;
68
+ parentOf.set(pid, st.ppid);
69
+ let env;
70
+ try {
71
+ env = String(fsImpl.readFileSync(path.join(dir, 'environ'), 'utf8')).split('\0');
72
+ } catch { continue; }
73
+ const entry = env.find((e) => e.startsWith(MARKER));
74
+ if (!entry || st.state === 'Z') continue;
75
+ const slug = entry.slice(MARKER.length);
76
+ let argv = [];
77
+ try {
78
+ argv = String(fsImpl.readFileSync(path.join(dir, 'cmdline'), 'utf8')).split('\0');
79
+ if (argv.length && argv[argv.length - 1] === '') argv.pop();
80
+ } catch { /* empty argv */ }
81
+ let cwd = null;
82
+ try {
83
+ cwd = String(fsImpl.readlinkSync(path.join(dir, 'cwd'))).replace(/ \(deleted\)$/, '');
84
+ } catch { /* null */ }
85
+ const etimes = Math.max(0, uptime - st.startTicks / 100);
86
+ const pcpu = etimes > 0 ? (((st.utime + st.stime) / 100) / etimes) * 100 : 0;
87
+ procs.push({ pid, ppid: st.ppid, tty: st.tty, slug, argv, cwd, comm: st.comm, startTicks: st.startTicks, etimes, pcpu });
88
+ } catch { /* pid vanished or denied mid-scan */ }
89
+ }
90
+ return { procs, parentOf };
91
+ }
92
+
93
+ function rowEndedMs(row) {
94
+ if (row && row.finishedAt) {
95
+ const t = Date.parse(row.finishedAt);
96
+ if (Number.isFinite(t)) return t;
97
+ }
98
+ const h = row && Array.isArray(row.statusHistory) ? row.statusHistory : [];
99
+ if (h.length) {
100
+ const t = Date.parse(h[h.length - 1] && h[h.length - 1].at);
101
+ if (Number.isFinite(t)) return t;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ function selectLeftovers({ scan, rows, runningSlugs, now, selfPid } = {}) {
107
+ const procs = (scan && scan.procs) || [];
108
+ const parentOf = (scan && scan.parentOf) || new Map();
109
+ const allRows = Array.isArray(rows) ? rows : [];
110
+ const running = runningSlugs instanceof Set ? runningSlugs : new Set(runningSlugs || []);
111
+
112
+ const bySlug = new Map();
113
+ for (const p of procs) {
114
+ if (!bySlug.has(p.slug)) bySlug.set(p.slug, []);
115
+ bySlug.get(p.slug).push(p);
116
+ }
117
+
118
+ const ancestors = new Set();
119
+ let cur = selfPid;
120
+ for (let i = 0; i < 64 && cur != null && parentOf.has(cur); i++) {
121
+ cur = parentOf.get(cur);
122
+ if (!cur || ancestors.has(cur)) break;
123
+ ancestors.add(cur);
124
+ }
125
+ const isDescendant = (pid) => {
126
+ let c = pid;
127
+ for (let i = 0; i < 64 && parentOf.has(c); i++) {
128
+ c = parentOf.get(c);
129
+ if (c === selfPid) return true;
130
+ if (!c) return false;
131
+ }
132
+ return false;
133
+ };
134
+
135
+ const out = [];
136
+ for (const [slug, list] of bySlug) {
137
+ if (running.has(slug)) continue;
138
+ if (list.some((p) => isClaudeArgv(p.argv))) continue;
139
+ const slugRows = allRows.filter((r) => r && r.slug === slug);
140
+ if (slugRows.some((r) => LIVE_STATUSES.has(r.status))) continue;
141
+ let ended = true;
142
+ for (const r of slugRows) {
143
+ const t = rowEndedMs(r);
144
+ if (t == null || now - t < LEFTOVER_GRACE_MS) { ended = false; break; }
145
+ }
146
+ if (!ended) continue;
147
+ const keep = list.filter((p) => !(p.tty !== 0 || p.pid === selfPid || ancestors.has(p.pid) || isDescendant(p.pid)));
148
+ if (keep.length) out.push({ slug, procs: keep });
149
+ }
150
+ return out;
151
+ }
152
+
153
+ /**
154
+ * stopLeftovers(procs, deps) — SIGTERM each pid, then after graceMs SIGKILL only
155
+ * pids whose live identity is complete and not a different process from the one
156
+ * recorded before SIGTERM (a recycled pid is never killed). Never throws.
157
+ * Returns the pids that were signalled.
158
+ */
159
+ function stopLeftovers(procs, {
160
+ kill = process.kill.bind(process),
161
+ identityOf = procIdentity.identity,
162
+ isDifferentProcess = procIdentity.isDifferentProcess,
163
+ setTimer = setTimeout,
164
+ graceMs = 5000,
165
+ } = {}) {
166
+ const recorded = new Map();
167
+ const signalled = [];
168
+ for (const p of Array.isArray(procs) ? procs : []) {
169
+ const pid = p && p.pid;
170
+ if (!Number.isInteger(pid) || pid <= 1) continue;
171
+ try { recorded.set(pid, identityOf(pid)); } catch { recorded.set(pid, null); }
172
+ try {
173
+ kill(pid, 'SIGTERM');
174
+ signalled.push(pid);
175
+ } catch { /* already gone */ }
176
+ }
177
+ if (signalled.length === 0) return signalled;
178
+ const timer = setTimer(() => {
179
+ for (const pid of signalled) {
180
+ try {
181
+ const live = identityOf(pid);
182
+ if (!live || live.complete !== true) continue;
183
+ if (isDifferentProcess(recorded.get(pid), live)) continue;
184
+ kill(pid, 'SIGKILL');
185
+ } catch { /* gone */ }
186
+ }
187
+ }, graceMs);
188
+ if (timer && typeof timer.unref === 'function') timer.unref();
189
+ return signalled;
190
+ }
191
+
192
+ /**
193
+ * listJobSurvivors(slug, pid, opts) — every scanned process carrying the job's
194
+ * SM_SCHEDULER_JOB_SLUG marker except `pid` itself, whatever its process group or
195
+ * session. opts is passed to scanJobProcesses (injectable fs/procRoot/platform).
196
+ */
197
+ function listJobSurvivors(slug, pid, opts) {
198
+ const { procs } = scanJobProcesses(opts);
199
+ return procs
200
+ .filter((p) => p.slug === slug && p.pid !== pid)
201
+ .map((p) => ({ pid: p.pid, pcpu: Math.round(p.pcpu * 10) / 10, etimes: Math.round(p.etimes), comm: p.comm }));
202
+ }
203
+
204
+ module.exports = { scanJobProcesses, listJobSurvivors, selectLeftovers, stopLeftovers, LEFTOVER_GRACE_MS };
@@ -40,7 +40,7 @@ function recordPath(runDir, slug) {
40
40
  */
41
41
  function writeSupervisorRecord({
42
42
  runDir, slug, cwd, runId, pid, pgid, identity, execCwd, worktreeDir, worktreeBranch,
43
- sessionId, startedAt, budgetMs, maxDurationMs, idleKillMs, schedulerPid, codeSha, kind,
43
+ sessionId, startedAt, budgetMs, maxDurationMs, idleKillMs, schedulerPid, codeSha, kind, scopeUnit,
44
44
  }) {
45
45
  if (!runDir || !slug) throw new Error('writeSupervisorRecord: runDir and slug are required');
46
46
  const record = {
@@ -51,6 +51,7 @@ function writeSupervisorRecord({
51
51
  sessionId: sessionId ?? null, startedAt: startedAt ?? null,
52
52
  budgetMs: budgetMs ?? null, maxDurationMs: maxDurationMs ?? null, idleKillMs: idleKillMs ?? null,
53
53
  schedulerPid: schedulerPid ?? null, codeSha: codeSha ?? null,
54
+ scopeUnit: scopeUnit ?? null,
54
55
  };
55
56
  writeJsonAtomicSync(recordPath(runDir, slug), record);
56
57
  return record;
@@ -21,6 +21,8 @@
21
21
 
22
22
  const { execFile } = require('node:child_process');
23
23
 
24
+ const { STRANDED_REF_PREFIX } = require('../git/gitExec.cjs');
25
+
24
26
  const LANDED_SINCE_RUN_TIMEOUT_MS = 10_000;
25
27
 
26
28
  /**
@@ -42,7 +44,7 @@ function landedSinceRun(cwd, sinceIso, paths, { timeoutMs = LANDED_SINCE_RUN_TIM
42
44
  }
43
45
  execFile(
44
46
  'git',
45
- ['-C', cwd, 'log', '--all', `--since=${sinceIso}`, '--format=%H', '--', ...paths],
47
+ ['-C', cwd, 'log', `--exclude=${STRANDED_REF_PREFIX}*`, '--all', `--since=${sinceIso}`, '--format=%H', '--', ...paths],
46
48
  { timeout: timeoutMs, windowsHide: true },
47
49
  (err, stdout) => {
48
50
  if (err) { resolve([]); return; }
@@ -68,10 +70,16 @@ function landedSinceRun(cwd, sinceIso, paths, { timeoutMs = LANDED_SINCE_RUN_TIM
68
70
  * @param {string} cwd
69
71
  * @param {string} sinceIso
70
72
  * @param {string[]} paths
71
- * @param {{ timeoutMs?: number }} [opts]
73
+ * `baseBranch` defaults to `main` but can differ: burrow's default branch is
74
+ * `master`, so a hard-coded `main` silently returned [] there.
75
+ *
76
+ * @param {string} cwd
77
+ * @param {string} sinceIso
78
+ * @param {string[]} paths
79
+ * @param {{ baseBranch?: string, timeoutMs?: number }} [opts]
72
80
  * @returns {Promise<string[]>} full commit SHAs, newest first
73
81
  */
74
- function landedOnMainSince(cwd, sinceIso, paths, { timeoutMs = LANDED_SINCE_RUN_TIMEOUT_MS } = {}) {
82
+ function landedOnMainSince(cwd, sinceIso, paths, { baseBranch = 'main', timeoutMs = LANDED_SINCE_RUN_TIMEOUT_MS } = {}) {
75
83
  const runLog = (ref) => new Promise((resolve) => {
76
84
  execFile(
77
85
  'git',
@@ -85,9 +93,9 @@ function landedOnMainSince(cwd, sinceIso, paths, { timeoutMs = LANDED_SINCE_RUN_
85
93
  });
86
94
  return (async () => {
87
95
  if (!cwd || !sinceIso || !Array.isArray(paths) || paths.length === 0) return [];
88
- const viaLocal = await runLog('main');
96
+ const viaLocal = await runLog(baseBranch);
89
97
  if (viaLocal !== null) return viaLocal;
90
- const viaRemote = await runLog('origin/main');
98
+ const viaRemote = await runLog(`origin/${baseBranch}`);
91
99
  return viaRemote ?? [];
92
100
  })();
93
101
  }