claude-code-session-manager 0.138.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +352 -79
  3. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  4. package/dist/assets/History--JwsFnbn.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
  6. package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
  8. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  10. package/dist/assets/Skills-DtRzghn5.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
  12. package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
  15. package/dist/assets/index-CtxruO1L.js +3121 -0
  16. package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +467 -451
  20. package/package.json +17 -6
  21. package/plugins/AGENTS.md +60 -0
  22. package/plugins/CLAUDE.md +1 -60
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  25. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  26. package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  36. package/scripts/README.md +2 -0
  37. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  38. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  39. package/scripts/ops-sweep.cjs +53 -23
  40. package/scripts/scheduler-mcp-server.cjs +360 -35
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +2 -2
  43. package/src/main/config.cjs +112 -8
  44. package/src/main/docEdit.cjs +6 -1
  45. package/src/main/exchanges.cjs +70 -5
  46. package/src/main/files.cjs +7 -27
  47. package/src/main/health.cjs +48 -15
  48. package/src/main/historyAggregator.cjs +172 -63
  49. package/src/main/historyDashboard.cjs +87 -17
  50. package/src/main/index.cjs +78 -4
  51. package/src/main/ipcSchemas.cjs +233 -20
  52. package/src/main/lib/AGENTS.md +54 -0
  53. package/src/main/lib/CLAUDE.md +1 -54
  54. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  55. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  56. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  57. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  58. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  59. package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
  60. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  61. package/src/main/lib/claude/modelPricing.cjs +148 -0
  62. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  63. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  64. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  65. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  66. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  67. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  68. package/src/main/lib/ephemeralCwd.cjs +37 -2
  69. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  70. package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
  71. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  72. package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
  73. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  74. package/src/main/lib/epic/epicSettle.cjs +1 -1
  75. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  76. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  77. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  78. package/src/main/lib/epic/externalRef.cjs +37 -0
  79. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  80. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  81. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  82. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  83. package/src/main/lib/externalContract.cjs +137 -0
  84. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  90. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  91. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  92. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
  93. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  94. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  95. package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
  96. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  97. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  98. package/src/main/lib/git/branchSweep.cjs +209 -4
  99. package/src/main/lib/git/gitWorktree.cjs +41 -5
  100. package/src/main/lib/guardShims.cjs +1 -1
  101. package/src/main/lib/historyRollup.cjs +58 -5
  102. package/src/main/lib/insideHome.cjs +27 -1
  103. package/src/main/lib/mcpToolCatalog.cjs +232 -25
  104. package/src/main/lib/mdDocCensus.cjs +59 -78
  105. package/src/main/lib/mdDocRefs.cjs +71 -93
  106. package/src/main/lib/mdNetworkScan.cjs +245 -250
  107. package/src/main/lib/mdReviewRecord.cjs +22 -9
  108. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  109. package/src/main/lib/opsOwnership.cjs +18 -2
  110. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  111. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  112. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  113. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  114. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  115. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  116. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  117. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  118. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  119. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  120. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  121. package/src/main/lib/prd/prdCreate.cjs +351 -23
  122. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  123. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  124. package/src/main/lib/process/loginItem.cjs +171 -0
  125. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  126. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  127. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  128. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  129. package/src/main/lib/promptSessionSchema.cjs +4 -0
  130. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  131. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  132. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  133. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  134. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  135. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  136. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  137. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  138. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  139. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  140. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  141. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  142. package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
  143. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  144. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  145. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  146. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  147. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  148. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  149. package/src/main/lib/tasks/taskRun.cjs +313 -0
  150. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  151. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  152. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  153. package/src/main/loginItemIpc.cjs +35 -0
  154. package/src/main/loopEfficiencyHandlers.cjs +11 -2
  155. package/src/main/projectPages.cjs +6 -15
  156. package/src/main/promptSessionEvents.cjs +9 -1
  157. package/src/main/queueOps.cjs +260 -3
  158. package/src/main/runVerify.cjs +53 -25
  159. package/src/main/scheduler/AGENTS.md +26 -0
  160. package/src/main/scheduler/CLAUDE.md +1 -26
  161. package/src/main/scheduler/budget.cjs +239 -9
  162. package/src/main/scheduler/cancelDependents.cjs +154 -0
  163. package/src/main/scheduler/prdParser.cjs +4 -1
  164. package/src/main/scheduler/starvation.cjs +20 -18
  165. package/src/main/scheduler.cjs +774 -64
  166. package/src/main/supervisor.cjs +5 -1
  167. package/src/main/templates/PRD_AUTHORING.md +7 -1
  168. package/src/main/transcripts.cjs +62 -7
  169. package/src/main/validationQualityHandlers.cjs +199 -0
  170. package/src/main/webRemote.cjs +132 -20
  171. package/src/preload/api.d.ts +434 -28
  172. package/src/preload/apiSurface.cjs +7 -0
  173. package/src/preload/apiSurface.json +485 -81
  174. package/src/preload/index.cjs +38 -5
  175. package/src/seed/agents/validator.md +19 -8
  176. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  177. package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
  178. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  179. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  180. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  181. package/dist/assets/History-BwO3coo4.js +0 -2
  182. package/dist/assets/Library-BDV69fSe.js +0 -32
  183. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  184. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  185. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  186. package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
  187. package/dist/assets/Settings-COT34hBF.js +0 -2
  188. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  189. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  190. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  191. package/dist/assets/Toggle-CENi19iK.js +0 -1
  192. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  193. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  194. package/dist/assets/index-CgCxpunJ.js +0 -3116
@@ -532,14 +532,113 @@ function applyRetention(runsDir, settings, opts) {
532
532
  * happens unless the read config opts out with
533
533
  * schedulerRunLogRetention.enabled === false (see isRetentionEnabled).
534
534
  *
535
- * Intended to be called once per app boot (see index.cjs's deferred 30s
536
- * startup timer, alongside finalizeClosedDays) — never on its own timer.
535
+ * Called by index.cjs's runRunLogRetentionPass: once on the deferred boot
536
+ * pass, then every 24h from that pass's setInterval timer.
537
537
  */
538
538
  function runBootSweep(opts) {
539
539
  const runsDir = (opts && opts.runsDir) || schedulerPaths.runsDir();
540
540
  const queueStore = require('./queueStore.cjs');
541
541
  const state = queueStore.readMergedSync();
542
- return applyRetention(runsDir, state.config || {}, { jobs: state.jobs || [] });
542
+ const result = applyRetention(runsDir, state.config || {}, { jobs: state.jobs || [] });
543
+ // Same pass, same project list: the cwds readMergedSync just swept (state.sourceCwds,
544
+ // from queueStore's cached stateCwds) — never a fresh allProjectCwds() scan.
545
+ result.planRecords = runPlanRecordSweep({ cwds: Array.isArray(state.sourceCwds) ? state.sourceCwds : [] });
546
+ return result;
547
+ }
548
+
549
+ const INDEX_UNREADABLE = Symbol('active-index-unreadable');
550
+
551
+ /**
552
+ * readIndexSessions(projectRoot) → the active-index.json `sessions` map, {} when the
553
+ * file is absent, or INDEX_UNREADABLE when it exists but cannot be read/parsed into an
554
+ * object carrying an object `sessions` field. Deliberately NOT epicMint.readActiveIndex:
555
+ * that reader folds every error into an empty index, which would make every live Epic
556
+ * look like an orphan to the plan-records sweep.
557
+ */
558
+ function readIndexSessions(projectRoot) {
559
+ const { opsPath } = require('../opsOwnership.cjs');
560
+ const { readJsonOrSync } = require('../util/atomicFs.cjs');
561
+ const file = opsPath(projectRoot, 'prompt-sessions', 'active-index.json');
562
+ if (!fs.existsSync(file)) return {};
563
+ const parsed = readJsonOrSync(file, INDEX_UNREADABLE);
564
+ if (parsed === INDEX_UNREADABLE || !parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
565
+ return INDEX_UNREADABLE;
566
+ }
567
+ const sessions = parsed.sessions;
568
+ if (!sessions || typeof sessions !== 'object' || Array.isArray(sessions)) return INDEX_UNREADABLE;
569
+ return sessions;
570
+ }
571
+
572
+ /**
573
+ * epicStatusFor(projectRoot, deps) → epicStatus(id) for prunePlanRecords. Reads the
574
+ * active-index.json row (read once per call) first, else the per-Epic
575
+ * prompt-sessions/<id>.json archive/mirror (planRecordRetention.defaultEpicStatus).
576
+ * Returns null for an unknown Epic (orphan).
577
+ *
578
+ * FAILS CLOSED: when active-index.json exists but is unreadable/corrupt, the returned
579
+ * function throws for every id, so prunePlanRecords keeps every folder in that project.
580
+ * A missing index means no rows: ids fall through to the archive, unknown ids are orphans.
581
+ * deps: { readActiveIndex, defaultEpicStatus } for tests (readActiveIndex replaces the
582
+ * canonical read; its result is trusted as-is).
583
+ */
584
+ function epicStatusFor(projectRoot, deps) {
585
+ const d = deps || {};
586
+ const archiveStatus = (d.defaultEpicStatus || require('./planRecordRetention.cjs').defaultEpicStatus)(projectRoot);
587
+ let sessions;
588
+ if (d.readActiveIndex) {
589
+ const idx = d.readActiveIndex(projectRoot);
590
+ sessions = idx && idx.sessions && typeof idx.sessions === 'object' ? idx.sessions : {};
591
+ } else {
592
+ let read;
593
+ try { read = readIndexSessions(projectRoot); } catch { read = INDEX_UNREADABLE; }
594
+ if (read === INDEX_UNREADABLE) {
595
+ return () => { throw new Error('active-index unreadable'); };
596
+ }
597
+ sessions = read;
598
+ }
599
+ return (id) => {
600
+ try {
601
+ const row = Object.prototype.hasOwnProperty.call(sessions, id) ? sessions[id] : null;
602
+ if (row && typeof row === 'object' && typeof row.status === 'string') {
603
+ return { status: row.status, completedAt: row.completedAt ?? null };
604
+ }
605
+ return archiveStatus(id);
606
+ } catch {
607
+ return null;
608
+ }
609
+ };
610
+ }
611
+
612
+ /**
613
+ * Prune plan-records/<epic-id>/ in every given project root with planRecordsDays from
614
+ * opsRetentionSettings. Per-project failures are logged and skipped — never throws.
615
+ * deps: { prune, readSettings, epicStatusFor, now } for tests.
616
+ */
617
+ function runPlanRecordSweep(opts) {
618
+ const o = opts || {};
619
+ const out = { projects: 0, removed: 0, errors: 0 };
620
+ let days;
621
+ try {
622
+ days = (o.readSettings || require('../opsRetentionSettings.cjs').read)().planRecordsDays;
623
+ } catch {
624
+ days = undefined; // prunePlanRecords falls back to its own default
625
+ }
626
+ const prune = o.prune || require('./planRecordRetention.cjs').prunePlanRecords;
627
+ const statusFor = o.epicStatusFor || epicStatusFor;
628
+ const seen = new Set();
629
+ for (const cwd of o.cwds || []) {
630
+ if (typeof cwd !== 'string' || !cwd || seen.has(cwd)) continue;
631
+ seen.add(cwd);
632
+ try {
633
+ const r = prune({ projectRoot: cwd, epicStatus: statusFor(cwd), days, now: o.now });
634
+ out.projects += 1;
635
+ out.removed += (r && Array.isArray(r.removed)) ? r.removed.length : 0;
636
+ } catch (e) {
637
+ out.errors += 1;
638
+ console.warn(`[runLogRetention] plan-records sweep skipped ${cwd}:`, e && e.message);
639
+ }
640
+ }
641
+ return out;
543
642
  }
544
643
 
545
644
  module.exports = {
@@ -556,4 +655,6 @@ module.exports = {
556
655
  isRetentionEnabled,
557
656
  applyRetention,
558
657
  runBootSweep,
658
+ runPlanRecordSweep,
659
+ epicStatusFor,
559
660
  };
@@ -101,6 +101,9 @@ const ScheduleJobSchema = z
101
101
  // PRD frontmatter `effort` — a per-run level from a macro press (outranks the persona's).
102
102
  effort: z.string().nullable().optional(),
103
103
  statusHistory: z.array(ScheduleJobStatusHistoryEntrySchema).optional(),
104
+ // PRD frontmatter `fixes` — the earlier PRDs this one repairs, copied onto
105
+ // the row at discovery by reconcile() (validationQuality.cjs reads it).
106
+ fixes: z.array(z.object({ prd: z.string(), missKind: z.string(), reason: z.string() }).passthrough()).optional(),
104
107
  // Opt-in exclusive-lease PRD flag (PRD 1107) — serializes this job against
105
108
  // every other job machine-wide for its run so a timing-sensitive gate
106
109
  // (frame time, performance fence) measures without CPU contention. See
@@ -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,14 @@ 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'); }
112
+ /** Machine-level (project cwd, externalRef) -> Epic id index (epic/externalRefIndex.cjs). */
113
+ function externalRefIndexPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'external-refs.json'), 'externalRefIndexPath'); }
114
+ /** Machine-level "Needs you" items posted by outside apps (feedback-remote/needsYouStore.cjs). */
115
+ function needsYouPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'needs-you.json'), 'needsYouPath'); }
116
+ /** Last-seen outside-facing state of every open Epic (epic/epicStateWatcher.cjs). */
117
+ function epicStateSnapshotPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'epic-state-snapshot.json'), 'epicStateSnapshotPath'); }
110
118
  function watchdogLogsDir() { return assertNotLiveRoot(path.join(schedulerHome(), 'logs'), 'watchdogLogsDir'); }
111
119
  function restartRequestPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'restart-request.json'), 'restartRequestPath'); }
112
120
  function restartingMarkerPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'restarting.json'), 'restartingMarkerPath'); }
@@ -198,6 +206,10 @@ module.exports = {
198
206
  schedulerStatePath,
199
207
  heartbeatPath,
200
208
  sessionSlotsConfigPath,
209
+ taskSwitchesPath,
210
+ externalRefIndexPath,
211
+ needsYouPath,
212
+ epicStateSnapshotPath,
201
213
  adminTokenPath,
202
214
  machineStateLogCwd,
203
215
  worktreeBase,
@@ -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,