claude-code-session-manager 0.139.0 → 0.140.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 (150) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  3. package/dist/assets/History--JwsFnbn.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-ijEXs--3.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-CALyU0pe.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-sdlA-fUb.js} +1 -1
  7. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-DtRzghn5.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-DApeu7x8.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-B7qLXRAH.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-DtStfv1H.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-ydfnwepc.js} +1 -1
  14. package/dist/assets/index-CtxruO1L.js +3121 -0
  15. package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +423 -426
  19. package/package.json +5 -2
  20. package/plugins/AGENTS.md +60 -0
  21. package/plugins/CLAUDE.md +1 -60
  22. package/plugins/session-manager-dev/skills/develop/SKILL.md +26 -19
  23. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  32. package/scripts/README.md +1 -0
  33. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  34. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  35. package/scripts/ops-sweep.cjs +53 -23
  36. package/scripts/scheduler-mcp-server.cjs +200 -18
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/config.cjs +112 -8
  39. package/src/main/docEdit.cjs +6 -1
  40. package/src/main/files.cjs +7 -27
  41. package/src/main/health.cjs +48 -15
  42. package/src/main/historyAggregator.cjs +88 -5
  43. package/src/main/historyDashboard.cjs +69 -4
  44. package/src/main/index.cjs +56 -2
  45. package/src/main/ipcSchemas.cjs +112 -16
  46. package/src/main/lib/AGENTS.md +54 -0
  47. package/src/main/lib/CLAUDE.md +1 -54
  48. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  49. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  50. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  51. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  52. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  53. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  54. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  55. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  56. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  57. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  58. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  59. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  60. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  61. package/src/main/lib/ephemeralCwd.cjs +37 -2
  62. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  63. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  64. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  65. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  66. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  67. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  68. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  69. package/src/main/lib/externalContract.cjs +31 -5
  70. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  71. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  72. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  73. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  75. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  76. package/src/main/lib/git/branchSweep.cjs +209 -4
  77. package/src/main/lib/git/gitWorktree.cjs +41 -5
  78. package/src/main/lib/guardShims.cjs +1 -1
  79. package/src/main/lib/historyRollup.cjs +26 -0
  80. package/src/main/lib/insideHome.cjs +27 -1
  81. package/src/main/lib/mcpToolCatalog.cjs +122 -12
  82. package/src/main/lib/mdDocCensus.cjs +59 -78
  83. package/src/main/lib/mdDocRefs.cjs +71 -93
  84. package/src/main/lib/mdNetworkScan.cjs +245 -250
  85. package/src/main/lib/mdReviewRecord.cjs +22 -9
  86. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  87. package/src/main/lib/opsOwnership.cjs +18 -2
  88. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  89. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  90. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  91. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  92. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  93. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  96. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  97. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  98. package/src/main/lib/prd/prdCreate.cjs +351 -23
  99. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  100. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  101. package/src/main/lib/process/loginItem.cjs +171 -0
  102. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  103. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  104. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  105. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  106. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  107. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  108. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  109. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  110. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  111. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  112. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  113. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  114. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  115. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  116. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  117. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  118. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  119. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  120. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  121. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  122. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  123. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  124. package/src/main/lib/tasks/taskRun.cjs +313 -0
  125. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  126. package/src/main/loginItemIpc.cjs +35 -0
  127. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  128. package/src/main/projectPages.cjs +6 -15
  129. package/src/main/promptSessionEvents.cjs +9 -1
  130. package/src/main/queueOps.cjs +260 -3
  131. package/src/main/runVerify.cjs +53 -25
  132. package/src/main/scheduler/AGENTS.md +26 -0
  133. package/src/main/scheduler/CLAUDE.md +1 -26
  134. package/src/main/scheduler/budget.cjs +239 -9
  135. package/src/main/scheduler/cancelDependents.cjs +154 -0
  136. package/src/main/scheduler/prdParser.cjs +4 -1
  137. package/src/main/scheduler/starvation.cjs +20 -18
  138. package/src/main/scheduler.cjs +745 -64
  139. package/src/main/supervisor.cjs +5 -1
  140. package/src/main/templates/PRD_AUTHORING.md +6 -1
  141. package/src/main/validationQualityHandlers.cjs +199 -0
  142. package/src/main/webRemote.cjs +10 -2
  143. package/src/preload/api.d.ts +364 -21
  144. package/src/preload/apiSurface.json +89 -10
  145. package/src/preload/index.cjs +23 -2
  146. package/src/seed/agents/validator.md +19 -8
  147. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  148. package/dist/assets/History-DDnqaLyw.js +0 -2
  149. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  150. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -15,7 +15,7 @@
15
15
  const path = require('node:path');
16
16
  const os = require('node:os');
17
17
  const { projectJobCap, quietMachineWaitMs } = require('./schedulerConfig.cjs');
18
- const { bareSlug, isSatisfiedDepRow } = require('../prd/depSlugResolve.cjs');
18
+ const { isSatisfiedDepRow, makeDepResolver } = require('../prd/depSlugResolve.cjs');
19
19
 
20
20
  const DEFAULT_PROJECT_CWD = path.join(os.homedir(), 'Projects', 'session-manager');
21
21
 
@@ -75,34 +75,14 @@ function dedupeCycles(cycles) {
75
75
  return out;
76
76
  }
77
77
 
78
- function makeDepResolver(projectJobs, satisfiedSlugs = new Set()) {
79
- const rowBySlug = new Map(projectJobs.map((j) => [j.slug, j]));
80
- const rowsByBareSlug = new Map();
81
- for (const j of projectJobs) {
82
- const bare = bareSlug(j.slug);
83
- if (!rowsByBareSlug.has(bare)) rowsByBareSlug.set(bare, []);
84
- rowsByBareSlug.get(bare).push(j);
85
- }
86
- const rowsForDep = (slug) => {
87
- const exact = rowBySlug.get(slug);
88
- if (exact) return [exact];
89
- return rowsByBareSlug.get(bareSlug(slug)) ?? [];
90
- };
91
- // Bare-name fallback applies here too: a satisfiedSlugs entry is almost
92
- // always the FULL NN-prefixed slug (a history.jsonl row or an archived
93
- // `<slug>.md` filename), but a human-authored dependsOn: writes the bare
94
- // name — same asymmetry findBlockingDep already resolves for live rows.
95
- let satisfiedBareSlugs = null;
96
- const isKnownSatisfied = (slug) => {
97
- if (satisfiedSlugs === DEP_HISTORY_FAIL_OPEN) return true;
98
- if (satisfiedSlugs.has(slug)) return true;
99
- if (satisfiedBareSlugs === null) {
100
- satisfiedBareSlugs = new Set();
101
- for (const s of satisfiedSlugs) satisfiedBareSlugs.add(bareSlug(s));
102
- }
103
- return satisfiedBareSlugs.has(bareSlug(slug));
104
- };
105
- return { rowsForDep, isKnownSatisfied };
78
+ /**
79
+ * The shared run-time dep resolver (depSlugResolve.cjs makeDepResolver),
80
+ * translating this module's DEP_HISTORY_FAIL_OPEN sentinel into its
81
+ * `failOpen` flag. Every gate below goes through this — no local slug rule.
82
+ */
83
+ function depResolver(projectJobs, satisfiedSlugs = new Set()) {
84
+ if (satisfiedSlugs === DEP_HISTORY_FAIL_OPEN) return makeDepResolver(projectJobs, new Set(), { failOpen: true });
85
+ return makeDepResolver(projectJobs, satisfiedSlugs);
106
86
  }
107
87
 
108
88
  /**
@@ -114,19 +94,19 @@ function makeDepResolver(projectJobs, satisfiedSlugs = new Set()) {
114
94
  * (or a restored record) can. Sorted, de-duplicated. O(jobs + deps).
115
95
  */
116
96
  function findUnresolvableDepRoots(projectJobs, satisfiedSlugs = new Set()) {
117
- const { rowsForDep, isKnownSatisfied } = makeDepResolver(projectJobs, satisfiedSlugs);
97
+ const { resolve } = depResolver(projectJobs, satisfiedSlugs);
118
98
  const roots = new Set();
119
99
  for (const j of projectJobs) {
120
100
  if (j.status !== 'pending') continue;
121
101
  for (const dep of j.dependsOn ?? []) {
122
- if (rowsForDep(dep).length === 0 && !isKnownSatisfied(dep)) roots.add(dep);
102
+ if (resolve(dep, j).kind === 'unresolved') roots.add(dep);
123
103
  }
124
104
  }
125
105
  return [...roots].sort();
126
106
  }
127
107
 
128
- function findBlockingDep(job, projectJobs, satisfiedSlugs = new Set()) {
129
- const { rowsForDep, isKnownSatisfied } = makeDepResolver(projectJobs, satisfiedSlugs);
108
+ function findBlockingDep(job, projectJobs, satisfiedSlugs = new Set(), resolver = null) {
109
+ const { resolve } = resolver ?? depResolver(projectJobs, satisfiedSlugs);
130
110
  // A dep row is blocking unless isSatisfiedDepRow — 'completed', or a
131
111
  // `needsReviewAutoResolvedSkip` skip. That skip is deliberately NOT the
132
112
  // "PRD source vanished, a human must author a fresh PRD" skip the
@@ -135,9 +115,9 @@ function findBlockingDep(job, projectJobs, satisfiedSlugs = new Set()) {
135
115
  // would defeat the auto-resolve pass. runVerify.checkDeps MUST use the same
136
116
  // predicate, or every run of the dependent is downgraded and re-dispatched.
137
117
  return (job.dependsOn ?? []).find((slug) => {
138
- const rows = rowsForDep(slug);
139
- if (rows.length > 0) return rows.some((dep) => !isSatisfiedDepRow(dep));
140
- return !isKnownSatisfied(slug);
118
+ const { kind, rows } = resolve(slug, job);
119
+ if (kind === 'row') return rows.some((dep) => !isSatisfiedDepRow(dep));
120
+ return kind === 'unresolved';
141
121
  });
142
122
  }
143
123
 
@@ -230,15 +210,12 @@ function pickForProject(projectJobs, runningSlugsInProject, slots, heldSlugs = n
230
210
  // `873-leftnav-two-face-framework`, all of them eligible immediately even
231
211
  // though the framework PRD they build on had not landed). findBlockingDep
232
212
  // resolves a dep by exact slug first, then falls back to matching rows
233
- // whose slug is that dep with a leading `NN-` stripped.
234
- const rowBySlug = new Map(projectJobs.map((j) => [j.slug, j]));
235
- const rowsForDep = (slug) => {
236
- const exact = rowBySlug.get(slug);
237
- if (exact) return [exact];
238
- const bare = String(slug ?? '').replace(/^\d+-/, '');
239
- return projectJobs.filter((j) => String(j.slug ?? '').replace(/^\d+-/, '') === bare);
240
- };
241
- const blockingDep = (j) => findBlockingDep(j, projectJobs, satisfiedSlugs);
213
+ // whose slug is that dep with a leading `NN-` stripped. One resolver
214
+ // (depSlugResolve.cjs makeDepResolver) serves gating, hold records and the
215
+ // root walk, so they can never name different rows for the same dep.
216
+ const resolver = depResolver(projectJobs, satisfiedSlugs);
217
+ const rowsForDep = (slug, dependent) => resolver.rowsForDep(slug, dependent);
218
+ const blockingDep = (j) => findBlockingDep(j, projectJobs, satisfiedSlugs, resolver);
242
219
  const depStatusOf = (rows) => (rows.length === 0 ? 'unresolved' : (rows.find((d) => d.status !== 'completed')?.status ?? 'unknown'));
243
220
 
244
221
  // Root-blocker walk (PRD 1123): follows dependsOn upward from a held job
@@ -255,7 +232,7 @@ function pickForProject(projectJobs, runningSlugsInProject, slots, heldSlugs = n
255
232
  for (let hops = 0; hops <= projectJobs.length; hops += 1) {
256
233
  const dep = blockingDep(current);
257
234
  if (!dep) return { rootSlug: current.slug, rootStatus: current.status, cycle: false };
258
- const rows = rowsForDep(dep);
235
+ const rows = rowsForDep(dep, current);
259
236
  if (rows.length === 0) return { rootSlug: dep, rootStatus: 'unresolved', cycle: false };
260
237
  const nextRow = rows.find((r) => r.status !== 'completed') ?? rows[0];
261
238
  if (visited.has(nextRow.slug)) return { cycle: true, members: [...visited, nextRow.slug] };
@@ -313,7 +290,7 @@ function pickForProject(projectJobs, runningSlugsInProject, slots, heldSlugs = n
313
290
  for (const j of allPending) {
314
291
  const dep = blockingDep(j);
315
292
  if (!dep) { pending.push(j); continue; }
316
- const depRows = rowsForDep(dep);
293
+ const depRows = rowsForDep(dep, j);
317
294
  const root = findRootBlocker(j);
318
295
  if (root.cycle) {
319
296
  cycles.push(root.members);
@@ -728,6 +705,6 @@ function findStarvedProjects(jobs, now, thresholdMs, lastDispatchAtByCwd = {}) {
728
705
  }
729
706
 
730
707
  module.exports = {
731
- pickForProject, pickNextBatch, enqueueTimestamp, findStarvedProjects, findBlockingDep, findUnresolvableDepRoots, DEFAULT_PROJECT_CWD,
708
+ pickForProject, pickNextBatch, enqueueTimestamp, findStarvedProjects, findBlockingDep, findUnresolvableDepRoots, DEFAULT_PROJECT_CWD, filesOverlap, pathsOverlap,
732
709
  DEP_HISTORY_FAIL_OPEN,
733
710
  };
@@ -107,6 +107,8 @@ function machineStatePath() { return assertNotLiveRoot(path.join(schedulerHome()
107
107
  function schedulerStatePath() { return assertNotLiveRoot(path.join(schedulerHome(), 'scheduler-state.json'), 'schedulerStatePath'); }
108
108
  function heartbeatPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'scheduler-heartbeat.log'), 'heartbeatPath'); }
109
109
  function sessionSlotsConfigPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'session-slots-config.json'), 'sessionSlotsConfigPath'); }
110
+ /** Machine-level per-project 'Scripts may run Tasks' switches, keyed by abs cwd (tasks/taskSwitch.cjs). */
111
+ function taskSwitchesPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'task-switches.json'), 'taskSwitchesPath'); }
110
112
  /** Machine-level (project cwd, externalRef) -> Epic id index (epic/externalRefIndex.cjs). */
111
113
  function externalRefIndexPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'external-refs.json'), 'externalRefIndexPath'); }
112
114
  /** Machine-level "Needs you" items posted by outside apps (feedback-remote/needsYouStore.cjs). */
@@ -204,6 +206,7 @@ module.exports = {
204
206
  schedulerStatePath,
205
207
  heartbeatPath,
206
208
  sessionSlotsConfigPath,
209
+ taskSwitchesPath,
207
210
  externalRefIndexPath,
208
211
  needsYouPath,
209
212
  epicStateSnapshotPath,
@@ -20,6 +20,19 @@
20
20
  * is the one exception — a tiny standalone JSON file, not routed through any
21
21
  * other module's config store) — all consumers live in the one Electron main
22
22
  * process, which is exactly why it can be the arbiter.
23
+ *
24
+ * Lanes (Task primitive): every holder carries a lane — 'general' (default:
25
+ * chat, project brief, memory assist), 'job' (scheduler PRD jobs),
26
+ * 'task-batch' and 'task-interactive' (headless Task runs). When the
27
+ * interactive reserve is on (setInteractiveReserve) and the cap is >= 2, one
28
+ * slot is HELD for 'task-interactive': non-interactive acquires succeed only
29
+ * while non-interactive holders < cap - 1. The held slot is arithmetic only —
30
+ * never a placeholder holder. Tasks may queue with waitForSlot(); a queued
31
+ * waiter takes precedence over 'job' acquires (they return null while any
32
+ * waiter queues), and waiters are granted interactive-first then FIFO,
33
+ * synchronously inside release / setCap / expireDead / setInteractiveReserve
34
+ * before any listener fires. Precedence only ever affects NEW grants: no
35
+ * running holder is ever revoked or signalled.
23
36
  */
24
37
  'use strict';
25
38
 
@@ -59,9 +72,7 @@ function setCap(cap) {
59
72
  }
60
73
  const configPath = sessionSlotsConfigPath();
61
74
  atomicFs.writeJsonAtomicSync(configPath, { cap: n });
62
- for (const fn of listeners) {
63
- try { fn(); } catch { /* a consumer's pump error is its own problem */ }
64
- }
75
+ notify();
65
76
  return n;
66
77
  }
67
78
 
@@ -73,9 +84,109 @@ function totalSlots() {
73
84
  return readPersistedCap();
74
85
  }
75
86
 
76
- // token → { owner, at, claimedAt (ms), pid (null until stampPid) }
87
+ const LANES = ['general', 'job', 'task-batch', 'task-interactive'];
88
+ const WAIT_LANES = ['task-batch', 'task-interactive'];
89
+ const MAX_WAITERS = 50;
90
+
91
+ function normalizeLane(lane) {
92
+ return LANES.includes(lane) ? lane : 'general';
93
+ }
94
+
95
+ // token → { owner, at, claimedAt (ms), pid (null until stampPid), lane }
77
96
  const holders = new Map();
78
97
 
98
+ let reserveOn = false;
99
+ // Each: { owner, lane, since (ms), seq, resolve, timer, signal, onAbort }
100
+ const waiters = [];
101
+ let waiterSeq = 0;
102
+
103
+ function reserveCount(total = totalSlots()) {
104
+ return reserveOn && total >= 2 ? 1 : 0;
105
+ }
106
+
107
+ function nonInteractiveHolders() {
108
+ let n = 0;
109
+ for (const h of holders.values()) if (h.lane !== 'task-interactive') n += 1;
110
+ return n;
111
+ }
112
+
113
+ /** How many more acquires of `lane` the pool admits now (ignores waiter precedence). */
114
+ function capacityFor(lane) {
115
+ const total = totalSlots();
116
+ const free = Math.max(0, total - holders.size);
117
+ if (lane === 'task-interactive') return free;
118
+ const budget = Math.max(0, total - reserveCount(total) - nonInteractiveHolders());
119
+ return Math.min(free, budget);
120
+ }
121
+
122
+ function allowed(lane) {
123
+ return capacityFor(lane) > 0;
124
+ }
125
+
126
+ function createHolder(owner, claimedAt, lane) {
127
+ const token = crypto.randomUUID();
128
+ holders.set(token, {
129
+ owner: String(owner || 'unknown'),
130
+ at: new Date(claimedAt).toISOString(),
131
+ claimedAt,
132
+ pid: null,
133
+ lane,
134
+ });
135
+ return token;
136
+ }
137
+
138
+ function priority(lane) {
139
+ return lane === 'task-interactive' ? 0 : 1;
140
+ }
141
+
142
+ function sortWaiters() {
143
+ waiters.sort((a, b) => (priority(a.lane) - priority(b.lane)) || (a.since - b.since) || (a.seq - b.seq));
144
+ }
145
+
146
+ function detachWaiter(w) {
147
+ if (w.timer) clearTimeout(w.timer);
148
+ if (w.signal && w.onAbort) w.signal.removeEventListener('abort', w.onAbort);
149
+ w.timer = null;
150
+ w.onAbort = null;
151
+ }
152
+
153
+ /** Grant queued waiters (interactive first, then FIFO) while the head is admitted. */
154
+ function grantWaiters() {
155
+ sortWaiters();
156
+ while (waiters.length && allowed(waiters[0].lane)) {
157
+ const w = waiters.shift();
158
+ detachWaiter(w);
159
+ w.resolve(createHolder(w.owner, Date.now(), w.lane));
160
+ }
161
+ }
162
+
163
+ function notify() {
164
+ grantWaiters();
165
+ for (const fn of listeners) {
166
+ try { fn(); } catch { /* a consumer's pump error is its own problem */ }
167
+ }
168
+ }
169
+
170
+ /** Turn the held interactive slot on/off (default off). Grants any waiter it unblocks. */
171
+ function setInteractiveReserve(on) {
172
+ reserveOn = !!on;
173
+ notify();
174
+ return reserveOn;
175
+ }
176
+
177
+ /** totalSlots() minus the held interactive slot — the most the scheduler may ever run. */
178
+ function jobCapacity() {
179
+ const total = totalSlots();
180
+ return Math.max(0, total - reserveCount(total));
181
+ }
182
+
183
+ /** How many acquires of `lane` would succeed right now (0 for 'job' while waiters queue). */
184
+ function availableFor(lane) {
185
+ const l = normalizeLane(lane);
186
+ if (l === 'job' && waiters.length > 0) return 0;
187
+ return capacityFor(l);
188
+ }
189
+
79
190
  function inUse() {
80
191
  return holders.size;
81
192
  }
@@ -89,11 +200,53 @@ function available() {
89
200
  * `owner` is a diagnostic label ("scheduler:<slug>", "chat:<tabId>") shown in
90
201
  * snapshot() so a stuck holder is attributable.
91
202
  */
92
- function acquire(owner, { claimedAt = Date.now() } = {}) {
93
- if (holders.size >= totalSlots()) return null;
94
- const token = crypto.randomUUID();
95
- holders.set(token, { owner: String(owner || 'unknown'), at: new Date(claimedAt).toISOString(), claimedAt, pid: null });
96
- return token;
203
+ function acquire(owner, { claimedAt = Date.now(), lane = 'general' } = {}) {
204
+ const l = normalizeLane(lane);
205
+ if (l === 'job' && waiters.length > 0) return null;
206
+ if (!allowed(l)) return null;
207
+ return createHolder(owner, claimedAt, l);
208
+ }
209
+
210
+ /**
211
+ * waitForSlot(owner, { lane, timeoutMs, signal }) → Promise<token|null>.
212
+ * Only for lanes 'task-batch' / 'task-interactive'. Resolves with a token as
213
+ * soon as a slot is granted (immediately when one is free and no waiter of the
214
+ * same-or-higher priority queues), or null on timeout / abort. Rejects with
215
+ * err.code 'too_many_waiting' past MAX_WAITERS, 'bad_lane' for other lanes.
216
+ */
217
+ function waitForSlot(owner, { lane = 'task-batch', timeoutMs = 0, signal } = {}) {
218
+ if (!WAIT_LANES.includes(lane)) {
219
+ const err = new Error(`sessionSlots.waitForSlot: lane must be one of ${WAIT_LANES.join(', ')}`);
220
+ /** @type {any} */ (err).code = 'bad_lane';
221
+ return Promise.reject(err);
222
+ }
223
+ if (signal && signal.aborted) return Promise.resolve(null);
224
+ const blockedByQueue = waiters.some((w) => priority(w.lane) <= priority(lane));
225
+ if (!blockedByQueue && allowed(lane)) {
226
+ return Promise.resolve(createHolder(owner, Date.now(), lane));
227
+ }
228
+ if (waiters.length >= MAX_WAITERS) {
229
+ const err = new Error(`sessionSlots.waitForSlot: ${MAX_WAITERS} waiters already queued`);
230
+ /** @type {any} */ (err).code = 'too_many_waiting';
231
+ return Promise.reject(err);
232
+ }
233
+ return new Promise((resolve) => {
234
+ const w = { owner: String(owner || 'unknown'), lane, since: Date.now(), seq: waiterSeq++, resolve, timer: null, signal: signal || null, onAbort: null };
235
+ const giveUp = () => {
236
+ const i = waiters.indexOf(w);
237
+ if (i === -1) return;
238
+ waiters.splice(i, 1);
239
+ detachWaiter(w);
240
+ resolve(null);
241
+ };
242
+ if (Number.isFinite(timeoutMs) && timeoutMs > 0) w.timer = setTimeout(giveUp, timeoutMs);
243
+ if (signal) {
244
+ w.onAbort = giveUp;
245
+ signal.addEventListener('abort', giveUp, { once: true });
246
+ }
247
+ waiters.push(w);
248
+ sortWaiters();
249
+ });
97
250
  }
98
251
 
99
252
  /** stampPid(token, pid) — record the child pid once known, so expireDead can prove death by pid. */
@@ -122,11 +275,7 @@ function expireDead({ liveSlugs, pidAlive, now = Date.now(), graceMs = DEFAULT_G
122
275
  expired.push(h.owner);
123
276
  appendAuditEvent('slot_reservation_expired', { owner: h.owner, pid: h.pid, claimedAt: h.at });
124
277
  }
125
- if (expired.length) {
126
- for (const fn of listeners) {
127
- try { fn(); } catch { /* a consumer's pump error is its own problem */ }
128
- }
129
- }
278
+ if (expired.length) notify();
130
279
  return expired;
131
280
  }
132
281
 
@@ -142,11 +291,7 @@ function subscribe(fn) {
142
291
  /** release(token) — idempotent; releasing an unknown/already-released token is a no-op. */
143
292
  function release(token) {
144
293
  const had = holders.delete(token);
145
- if (had) {
146
- for (const fn of listeners) {
147
- try { fn(); } catch { /* a consumer's pump error is its own problem */ }
148
- }
149
- }
294
+ if (had) notify();
150
295
  return had;
151
296
  }
152
297
 
@@ -155,7 +300,9 @@ function snapshot() {
155
300
  return {
156
301
  total: totalSlots(),
157
302
  inUse: holders.size,
158
- holders: [...holders.values()],
303
+ holders: [...holders.values()].map((h) => ({ ...h })),
304
+ waiters: waiters.map((w) => ({ owner: w.owner, lane: w.lane, since: w.since })),
305
+ reserve: reserveCount(),
159
306
  min: MIN_SLOTS,
160
307
  max: MAX_SLOTS,
161
308
  default: DEFAULT_SLOTS,
@@ -163,20 +310,28 @@ function snapshot() {
163
310
  };
164
311
  }
165
312
 
166
- /** Test hook: drop all held slots. */
313
+ /** Test hook: drop all held slots, queued waiters and the reserve. */
167
314
  function __resetForTests() {
168
315
  holders.clear();
316
+ for (const w of waiters.splice(0)) detachWaiter(w);
317
+ reserveOn = false;
169
318
  }
170
319
 
171
320
  module.exports = {
172
321
  MIN_SLOTS,
173
322
  MAX_SLOTS,
174
323
  DEFAULT_SLOTS,
324
+ LANES,
325
+ MAX_WAITERS,
175
326
  totalSlots,
176
327
  setCap,
177
328
  inUse,
178
329
  available,
179
330
  acquire,
331
+ waitForSlot,
332
+ availableFor,
333
+ jobCapacity,
334
+ setInteractiveReserve,
180
335
  stampPid,
181
336
  expireDead,
182
337
  release,