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
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * loginItemIpc.cjs — registers the `loginItem:*` IPC handlers over a login-item module built by
5
+ * lib/process/loginItem.cjs (createLoginItem). Local renderer only; no remote/relay command reaches it.
6
+ * loginItem:status → the module's status()
7
+ * loginItem:set-enabled { enabled: boolean } → { ok: true, status } | { ok: false, error }
8
+ */
9
+
10
+ const { z } = require('zod');
11
+
12
+ const schemas = {
13
+ setEnabled: z.object({ enabled: z.boolean() }).strict(),
14
+ };
15
+
16
+ /**
17
+ * @param {{ ipcMain: any, loginItem: { status: () => any, setEnabled: (on: boolean) => Promise<any> } }} opts
18
+ */
19
+ function registerLoginItemIpc({ ipcMain, loginItem }) {
20
+ ipcMain.handle('loginItem:status', () => loginItem.status());
21
+ ipcMain.handle('loginItem:set-enabled', async (_event, payload) => {
22
+ const parsed = schemas.setEnabled.safeParse(payload);
23
+ if (!parsed.success) {
24
+ return { ok: false, error: `Invalid payload: ${parsed.error.issues.map((i) => i.message).join('; ') || 'expected { enabled: boolean }'}` };
25
+ }
26
+ try {
27
+ const status = await loginItem.setEnabled(parsed.data.enabled);
28
+ return { ok: true, status };
29
+ } catch (e) {
30
+ return { ok: false, error: (e && e.message) || String(e) };
31
+ }
32
+ });
33
+ }
34
+
35
+ module.exports = { registerLoginItemIpc };
@@ -14,6 +14,7 @@ const path = require('path');
14
14
  const { ipcMain } = require('electron');
15
15
  const { computeLoopEfficiency } = require('./lib/scheduler/loopEfficiency.cjs');
16
16
  const { parseValidationSentinels } = require('./lib/scheduler/validationSentinels.cjs');
17
+ const { parseValidatorVerdict, verdictRowsFromStructured } = require('./lib/scheduler/validatorVerdictSchema.cjs');
17
18
 
18
19
  const WEEK_MS = 7 * 24 * 3600 * 1000;
19
20
  const LOG_TAIL_BYTES = 1024 * 1024;
@@ -60,7 +61,15 @@ async function validationsForLog(logPath) {
60
61
  if (!lines[i].includes('"type":"result"')) continue;
61
62
  try {
62
63
  const obj = JSON.parse(lines[i]);
63
- if (typeof obj.result === 'string') out = parseValidationSentinels(obj.result);
64
+ // `--json-schema` validator runs: the checked JSON is structured_output
65
+ // and `result` is its string form, so read it first. Older logs and
66
+ // non-validator runs fall back to the text sentinels.
67
+ if (obj.structured_output && parseValidatorVerdict(obj.structured_output).ok) {
68
+ out = verdictRowsFromStructured(obj.structured_output)
69
+ .map((r) => ({ slug: r.slug, verdict: r.verdict, reason: r.reason }));
70
+ } else if (typeof obj.result === 'string') {
71
+ out = parseValidationSentinels(obj.result);
72
+ }
64
73
  } catch { /* torn line — treat as no verdicts */ }
65
74
  break;
66
75
  }
@@ -157,4 +166,4 @@ function registerLoopEfficiencyHandlers() {
157
166
  });
158
167
  }
159
168
 
160
- module.exports = { gatherLoopEfficiency, registerLoopEfficiencyHandlers, defaultUsage };
169
+ module.exports = { gatherLoopEfficiency, registerLoopEfficiencyHandlers, defaultUsage, runIdToMs };
@@ -96,34 +96,25 @@ async function get({ cwd }) {
96
96
 
97
97
  const MD_NETWORK_EPHEMERAL = 'refusing an ephemeral cwd (tmpdir or linked git worktree): no project to scan';
98
98
 
99
- /** Strip trailing slashes ('docs/' -> 'docs'); undefined stays undefined. */
100
- const stripTrailingSlashes = (folders) => folders && folders.map((f) => f.replace(/\/+$/, ''));
101
-
102
99
  /**
103
100
  * -> MdNetworkResult: the project's markdown link network from its root
104
101
  * CLAUDE.md, scanned once per call (no watcher, no cache). `cwd` is validated
105
102
  * like get() (an invalid path rejects); a cwd get() answers with EMPTY() gets
106
- * `{ ok: false, error }`.
107
- *
108
- * `recordFolders` / `docFolders` are a human's census overrides (mark a folder
109
- * as machine-written records, or as real docs). They are only repo-relative
110
- * path prefixes for classification and never reach the file system — only
111
- * `cwd` is a path that is resolved or read.
103
+ * `{ ok: false, error }`. History folders come only from the tracked
104
+ * .session-manager.json mdNetwork.history and the census heuristic.
112
105
  */
113
- async function mdNetwork({ cwd, recordFolders, docFolders }) {
106
+ async function mdNetwork({ cwd }) {
114
107
  const { root, ephemeral } = tryProjectRoot(config.validatePath(cwd));
115
108
  if (ephemeral) return { ok: false, error: MD_NETWORK_EPHEMERAL };
116
- return scanMdNetwork(root, {}, {
117
- recordFolders: stripTrailingSlashes(recordFolders),
118
- docFolders: stripTrailingSlashes(docFolders),
119
- });
109
+ return scanMdNetwork(root);
120
110
  }
121
111
 
122
112
  const MD_REVIEW_EPHEMERAL = 'refusing an ephemeral cwd (tmpdir or linked git worktree): no project review record';
123
113
 
124
114
  /**
125
115
  * -> MdReviewResult: the newest review record under reviews/docs/ and, per
126
- * given Epic id, its reviews/validation/<id>/*.md paths — read once per call
116
+ * given Epic id, its plan-records/<id>/*.md + legacy reviews/validation/<id>/
117
+ * *.md paths — read once per call
127
118
  * (no watcher, no cache). Resolves the project root like mdNetwork(); an
128
119
  * ephemeral cwd gets `{ ok: false, error }`.
129
120
  */
@@ -74,7 +74,9 @@ function mintEventId() {
74
74
  * marker like 'job-not-queued', or PRD 3116's 'build-done'/'build-failed', the
75
75
  * renderer turns into a distinct notice) and `buildOutput` (PRD 3116 — `{ kind,
76
76
  * id, title }` of a macro build's saved entry), and `reply` (`{ fromCwd,
77
- * fromEpicId, outcome, referencePaths }` — a cross-project reply's origin). All
77
+ * fromEpicId, outcome, referencePaths }` — a cross-project reply's origin, plus
78
+ * a receipt's optional `hash`/`delivery`/`toEpicId`/`fallbackEpicId`/`reason`/
79
+ * `reused`). All
78
80
  * keys are added to the event object only when present in `meta`, never as
79
81
  * `undefined`-valued keys, so events appended without them serialize
80
82
  * identically to before.
@@ -116,6 +118,12 @@ async function appendResponseEventWithReason(cwd, sourcePromptId, text, meta = {
116
118
  if (meta && meta.reply && typeof meta.reply === 'object') {
117
119
  const { fromCwd, fromEpicId, outcome, referencePaths } = meta.reply;
118
120
  event.reply = { fromCwd, fromEpicId, outcome, referencePaths };
121
+ // Receipt-only keys (the replier's dedupe hash + the delivery it
122
+ // recorded) — copied only when present, as strings / a boolean.
123
+ for (const k of ['hash', 'delivery', 'toEpicId', 'fallbackEpicId', 'reason']) {
124
+ if (typeof meta.reply[k] === 'string' && meta.reply[k]) event.reply[k] = meta.reply[k];
125
+ }
126
+ if (meta.reply.reused === true) event.reply.reused = true;
119
127
  }
120
128
  data.events[sourcePromptId] = [...events, event];
121
129
  await config.writeJson(path, data, { writer: 'scheduler' });
@@ -127,7 +127,13 @@ const INTERACTIVE_AC_PATTERNS = [
127
127
  ];
128
128
 
129
129
  const { splitFrontmatter } = require('./lib/prd/prdFrontmatter.cjs');
130
- const { resolvePrdsDirs, resolvePrdWriteDir, listEpicPrdDirs } = require('./lib/prd/prdLocations.cjs');
130
+ const {
131
+ resolvePrdsDirs, resolvePrdWriteDir, listEpicPrdDirs, deriveEpicIdFromPrdPath, deriveProjectCwdFromPrdPath,
132
+ } = require('./lib/prd/prdLocations.cjs');
133
+ const { opsPath, assertOpsWrite } = require('./lib/opsOwnership.cjs');
134
+ const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
135
+ const { readActiveIndex } = require('./lib/epic/epicMint.cjs');
136
+ const cancelDependents = require('./scheduler/cancelDependents.cjs');
131
137
 
132
138
  // PRD 808: PRDS_DIR is now the LEGACY global dir — kept as a migration
133
139
  // source and search fallback for not-yet-migrated files. Live PRDs resolve
@@ -346,10 +352,61 @@ async function archiveOne(slug, ts, cwd) {
346
352
  */
347
353
  let retireCompletedSlugsFn = async () => {};
348
354
 
349
- async function archiveMany(slugs, cwd, { retire = true } = {}) {
355
+ const DISMISS_ROUTE = 'POST /admin/scheduler/dismiss-cancelled';
356
+
357
+ /**
358
+ * A cancelled row is a 'failed' row carrying the cancel marker remote.cancelJob
359
+ * stamps (`cancelledAt`). JOB_STATUSES is closed, so the marker — not a status —
360
+ * is what tells a cancel apart from a real failure.
361
+ */
362
+ function isCancelledRow(j) {
363
+ return !!j && j.status === 'failed' && typeof j.cancelledAt === 'string' && j.cancelledAt.length > 0;
364
+ }
365
+
366
+ function cancelledSlugsIn(jobs, cwd) {
367
+ const out = new Set();
368
+ for (const j of Array.isArray(jobs) ? jobs : []) {
369
+ if (!isCancelledRow(j)) continue;
370
+ if (cwd && j.cwd !== cwd) continue;
371
+ out.add(j.slug);
372
+ }
373
+ return out;
374
+ }
375
+
376
+ async function archiveMany(slugs, cwd, { retire = true, jobs } = {}) {
350
377
  if (!Array.isArray(slugs) || slugs.length === 0) {
351
378
  return { ok: true, archived: 0, archivedTo: null, results: [] };
352
379
  }
380
+ // A cancelled row must never be archived: prds-archived/ is read by
381
+ // budget.computeDepHistorySatisfaction as "satisfied", so archiving a
382
+ // cancelled PRD would silently release its dependents. Refuse with a
383
+ // warning pointing at dismiss (prds-cancelled/, never a satisfier).
384
+ let cancelled = new Set();
385
+ if (Array.isArray(jobs)) {
386
+ cancelled = cancelledSlugsIn(jobs, cwd);
387
+ } else if (queueAccess) {
388
+ try { cancelled = cancelledSlugsIn((await queueAccess.readQueue()).jobs, cwd); } catch { /* unreadable queue: no cancel info */ }
389
+ }
390
+ const warnings = [];
391
+ const toArchive = [];
392
+ const refused = [];
393
+ for (const slug of slugs) {
394
+ if (!cancelled.has(slug)) { toArchive.push(slug); continue; }
395
+ const warning = `"${slug}" is a cancelled job — archiving it would make it satisfy dependsOn. `
396
+ + `Dismiss it instead (${DISMISS_ROUTE}); not archived.`;
397
+ warnings.push(warning);
398
+ refused.push({ ok: false, slug, cancelled: true, warning, error: warning });
399
+ }
400
+ if (toArchive.length === 0) {
401
+ return { ok: true, archived: 0, archivedTo: null, results: refused, warnings };
402
+ }
403
+ const inner = await archiveAll(toArchive, cwd, { retire });
404
+ inner.results = [...refused, ...inner.results];
405
+ if (warnings.length > 0) inner.warnings = warnings;
406
+ return inner;
407
+ }
408
+
409
+ async function archiveAll(slugs, cwd, { retire }) {
353
410
  // One timestamp for the whole batch (so a multi-slug archive reads as one
354
411
  // event), but each slug's destination DIRECTORY is resolved from its own
355
412
  // source inside archiveOne — see archiveDirForSource. mkdir moved in there
@@ -456,7 +513,7 @@ async function autoArchiveCompleted(state, { nowMs } = {}) {
456
513
  if (slugs.length === 0) {
457
514
  return { ok: true, archived: 0, archivedTo: null, results: [] };
458
515
  }
459
- const result = await archiveMany(slugs, undefined, { retire: false });
516
+ const result = await archiveMany(slugs, undefined, { retire: false, jobs });
460
517
  for (const r of result.results) {
461
518
  if (r.ok) {
462
519
  logs.writeLine({
@@ -470,6 +527,202 @@ async function autoArchiveCompleted(state, { nowMs } = {}) {
470
527
  return result;
471
528
  }
472
529
 
530
+ // ────────────────────────────────────────────── dismiss cancelled rows
531
+ //
532
+ // A cancelled job lands as 'failed' + cancelledAt. Archiving it would file the
533
+ // PRD under prds-archived/, which dependency satisfaction counts as "shipped".
534
+ // Dismiss is the honest exit: the row leaves the live queue and the PRD moves
535
+ // to a prds-cancelled/<ts>/ sibling dir that nothing ever reads as satisfied.
536
+
537
+ /**
538
+ * Queue access injected by scheduler.cjs at load (queueOps cannot require
539
+ * scheduler.cjs — circular). `mutate` is scheduler's serialized mutate();
540
+ * dismissCancelled calls it from OUTSIDE any mutate body only (2026-09-25
541
+ * deadlock), and autoDismissCancelled never calls it at all.
542
+ */
543
+ let queueAccess = null;
544
+ function bindQueueAccess(access) {
545
+ queueAccess = access && typeof access.mutate === 'function' && typeof access.readQueue === 'function' ? access : null;
546
+ }
547
+
548
+ const CLOSED_EPIC_STATUSES = new Set(['completed', 'archived']);
549
+
550
+ function cancelledDirForSource(srcDir, ts) {
551
+ const parent = path.dirname(srcDir);
552
+ const epicId = deriveEpicIdFromPrdPath(path.join(srcDir, 'x.md'));
553
+ const projectCwd = deriveProjectCwdFromPrdPath(path.join(srcDir, 'x.md'));
554
+ if (projectCwd) {
555
+ try {
556
+ const segs = epicId ? ['scheduler', 'epics', epicId, 'prds-cancelled', ts] : ['scheduler', 'prds-cancelled', ts];
557
+ const dir = opsPath(projectCwd, ...segs);
558
+ if (path.dirname(path.dirname(dir)) === parent) return { dir, owned: true };
559
+ } catch { /* fall through to the plain sibling */ }
560
+ }
561
+ return { dir: path.join(parent, 'prds-cancelled', ts), owned: false };
562
+ }
563
+
564
+ /** Move `<prds>/<slug>.md` → `<prds>/../prds-cancelled/<ts>/<slug>.md`. */
565
+ async function moveToCancelled(slug, cwd, ts) {
566
+ const srcDir = await findPrdDir(slug, cwd);
567
+ if (!srcDir) return { ok: true, movedTo: null };
568
+ const src = path.resolve(path.join(srcDir, `${slug}.md`));
569
+ if (!src.startsWith(srcDir + path.sep)) return { ok: false, error: 'path escape (src)' };
570
+ const { dir, owned } = cancelledDirForSource(srcDir, ts);
571
+ const dst = path.resolve(path.join(dir, `${slug}.md`));
572
+ if (!dst.startsWith(path.resolve(dir) + path.sep)) return { ok: false, error: 'path escape (dst)' };
573
+ try {
574
+ if (owned) assertOpsWrite(dst, 'scheduler');
575
+ await fsp.mkdir(dir, { recursive: true });
576
+ await fsp.rename(src, dst);
577
+ return { ok: true, movedTo: dst };
578
+ } catch (e) {
579
+ return { ok: false, error: e?.message ?? 'rename failed' };
580
+ }
581
+ }
582
+
583
+ function newTs() {
584
+ return new Date().toISOString().replace(/[:.]/g, '-');
585
+ }
586
+
587
+ /**
588
+ * dismissCancelled(slug, cwd, { dependents? }) — remove a cancelled row from
589
+ * the live queue and file its PRD under prds-cancelled/. Refuses rows without
590
+ * a cancel marker, and refuses while pending dependents exist unless the same
591
+ * dependents choice cancelJob takes is passed (cancelDependents.cjs).
592
+ */
593
+ async function dismissCancelled(slug, cwd, opts = {}) {
594
+ if (!SLUG_RE.test(String(slug ?? ''))) return { ok: false, error: 'invalid slug' };
595
+ if (!queueAccess) return { ok: false, error: 'queue access not bound (scheduler not loaded)' };
596
+ const state = await queueAccess.readQueue();
597
+ if (state?.unreadable) return { ok: false, error: `queue unreadable (${state.unreadable})` };
598
+ const jobs = Array.isArray(state?.jobs) ? state.jobs : [];
599
+ const job = jobs.find((j) => j && j.slug === slug && (!cwd || j.cwd === cwd));
600
+ if (!job) {
601
+ return { ok: false, error: `unknown slug "${slug}": no queued job with that name${cwd ? ` in cwd ${cwd}` : ''}` };
602
+ }
603
+ if (!isCancelledRow(job)) {
604
+ return {
605
+ ok: false,
606
+ error: `job "${slug}" is not a cancelled row (status "${job.status}", no cancel marker) — dismiss only applies to cancelled jobs`,
607
+ notCancelled: true,
608
+ };
609
+ }
610
+ const depCwd = job.cwd ?? null;
611
+ const pending = cancelDependents.findPendingDependents(jobs, slug, depCwd);
612
+ let depPlan = null;
613
+ if (pending.length > 0) {
614
+ const names = pending.map((d) => d.slug);
615
+ if (!opts.dependents) {
616
+ return {
617
+ ok: false,
618
+ error: `cancelled job "${slug}" has ${names.length} pending dependent(s): ${names.join(', ')}. `
619
+ + 'Pass dependents: { action: "cascade" } to cancel them too, '
620
+ + '{ action: "repoint", to: "<slug>" } to make them depend on another PRD instead, '
621
+ + 'or { action: "clear" } to drop the dependency.',
622
+ dependents: names,
623
+ choices: [...cancelDependents.DEPENDENTS_ACTIONS],
624
+ };
625
+ }
626
+ depPlan = cancelDependents.planDependentsUpdate(jobs, slug, opts.dependents, depCwd);
627
+ if (!depPlan.ok) return { ok: false, error: depPlan.error, dependents: names };
628
+ if (depPlan.action !== 'cascade' && typeof queueAccess.updatePrd !== 'function') {
629
+ return { ok: false, error: 'updatePrd not bound — cannot rewrite dependents', dependents: names };
630
+ }
631
+ const applied = [];
632
+ for (const edit of depPlan.edits) {
633
+ if (edit.action !== 'setDependsOn') continue;
634
+ const res = await queueAccess.updatePrd({ slug: edit.slug, cwd: depCwd ?? undefined, frontmatter: { dependsOn: edit.dependsOn } });
635
+ if (!res?.ok) {
636
+ for (const done of applied.reverse()) {
637
+ await queueAccess.updatePrd({ slug: done.slug, cwd: depCwd ?? undefined, frontmatter: { dependsOn: done.previous } }).catch(() => null);
638
+ }
639
+ return {
640
+ ok: false,
641
+ error: `could not update dependent ${edit.slug}: ${res?.error ?? 'unknown error'} — "${slug}" was not dismissed`,
642
+ dependents: names,
643
+ };
644
+ }
645
+ applied.push(edit);
646
+ }
647
+ }
648
+ // File first, row second: a row with no file is harmless, but a live PRD
649
+ // file with no row would be re-minted as pending by the next reconcile.
650
+ const move = await moveToCancelled(slug, depCwd ?? undefined, newTs());
651
+ if (!move.ok) return { ok: false, error: `could not move PRD to prds-cancelled/: ${move.error}` };
652
+ const cascadeEdits = depPlan?.action === 'cascade' ? depPlan.edits : [];
653
+ const dependsOnEdits = depPlan && depPlan.action !== 'cascade' ? depPlan.edits : [];
654
+ const cancelledAt = new Date().toISOString();
655
+ let removed = false;
656
+ await queueAccess.mutate((s) => {
657
+ for (const edit of cascadeEdits) {
658
+ const d = s.jobs.find((x) => x.slug === edit.slug && x.cwd === job.cwd);
659
+ if (!d || d.status !== 'pending') continue;
660
+ if (queueAccess.transitionJob && !queueAccess.transitionJob(d, 'failed', { reason: edit.reason, source: 'queueOps:dismissCancelled' })) continue;
661
+ if (!queueAccess.transitionJob) d.status = 'failed';
662
+ d.error = edit.reason;
663
+ d.cancelledAt = cancelledAt;
664
+ d.finishedAt = cancelledAt;
665
+ d.exitCode = d.exitCode ?? null;
666
+ delete d.runtime;
667
+ }
668
+ for (const edit of dependsOnEdits) {
669
+ const d = s.jobs.find((x) => x.slug === edit.slug && x.cwd === job.cwd);
670
+ if (d) d.dependsOn = edit.dependsOn;
671
+ }
672
+ const idx = s.jobs.findIndex((x) => x.slug === slug && x.cwd === job.cwd && isCancelledRow(x));
673
+ if (idx >= 0) { s.jobs.splice(idx, 1); removed = true; }
674
+ });
675
+ if (typeof queueAccess.broadcast === 'function') {
676
+ await Promise.resolve(queueAccess.broadcast({ flush: true })).catch(() => {});
677
+ }
678
+ const audit = { slug, cwd: depCwd, source: 'manual', movedTo: move.movedTo, removed };
679
+ if (depPlan) Object.assign(audit, { action: depPlan.action, to: depPlan.to ?? null, dependents: depPlan.dependents });
680
+ appendAuditEvent('job_dismiss_cancelled', audit);
681
+ const result = { ok: true, slug, cwd: depCwd, movedTo: move.movedTo, removed };
682
+ if (depPlan) result.dependents = { action: depPlan.action, to: depPlan.to ?? null, slugs: depPlan.dependents };
683
+ return result;
684
+ }
685
+
686
+ /**
687
+ * autoDismissCancelled(state) — reconcile-time pass. Runs INSIDE a mutate
688
+ * body, so it edits `state.jobs` in place and never calls mutate(). Dismisses
689
+ * a cancelled row when its Epic is completed/archived and no pending row in
690
+ * its project (any Epic) still depends on it. Kill switch:
691
+ * SM_CANCELLED_AUTODISMISS_DISABLE=1.
692
+ */
693
+ async function autoDismissCancelled(state) {
694
+ if (process.env.SM_CANCELLED_AUTODISMISS_DISABLE === '1') return { dismissed: [], skipped: 'disabled' };
695
+ const jobs = Array.isArray(state?.jobs) ? state.jobs : [];
696
+ const candidates = jobs.filter((j) => isCancelledRow(j) && j.epicId && j.cwd);
697
+ if (candidates.length === 0) return { dismissed: [] };
698
+ const indexByCwd = new Map();
699
+ const epicStatus = (cwd, epicId) => {
700
+ if (!indexByCwd.has(cwd)) indexByCwd.set(cwd, readActiveIndex(cwd).sessions);
701
+ const sessions = indexByCwd.get(cwd);
702
+ return Object.prototype.hasOwnProperty.call(sessions, epicId) ? sessions[epicId]?.status ?? null : null;
703
+ };
704
+ const ts = newTs();
705
+ const dismissed = [];
706
+ const drop = new Set();
707
+ for (const j of candidates) {
708
+ const status = epicStatus(j.cwd, j.epicId);
709
+ if (!CLOSED_EPIC_STATUSES.has(status)) continue;
710
+ if (cancelDependents.findPendingDependents(jobs, j.slug, j.cwd).length > 0) continue;
711
+ const move = await moveToCancelled(j.slug, j.cwd, ts);
712
+ if (!move.ok) {
713
+ logs.writeLine({ level: 'warn', scope: 'queueOps', message: `auto-dismiss: move failed for ${j.slug}`, meta: { error: move.error } });
714
+ continue;
715
+ }
716
+ drop.add(j);
717
+ dismissed.push(j.slug);
718
+ appendAuditEvent('job_dismiss_cancelled', {
719
+ slug: j.slug, cwd: j.cwd, source: 'auto', epicId: j.epicId, epicStatus: status, movedTo: move.movedTo, removed: true,
720
+ });
721
+ }
722
+ if (drop.size > 0) state.jobs = jobs.filter((j) => !drop.has(j));
723
+ return { dismissed };
724
+ }
725
+
473
726
  // ────────────────────────────────────────────── retag
474
727
 
475
728
  /**
@@ -630,6 +883,10 @@ module.exports = {
630
883
  lintAll,
631
884
  lintOneAsync,
632
885
  archiveMany,
886
+ bindQueueAccess,
887
+ isCancelledRow,
888
+ dismissCancelled,
889
+ autoDismissCancelled,
633
890
  selectAutoArchivable,
634
891
  autoArchiveCompleted,
635
892
  retagMany,
@@ -45,7 +45,7 @@ const fs = require('node:fs');
45
45
  const path = require('node:path');
46
46
  const { execFileSync } = require('node:child_process');
47
47
  const { parsePrdFile, isArtifactOnlyDeclaration } = require('./lib/prd/prdFrontmatter.cjs');
48
- const { isSatisfiedDepRow } = require('./lib/prd/depSlugResolve.cjs');
48
+ const { isSatisfiedDepRow, makeDepResolver } = require('./lib/prd/depSlugResolve.cjs');
49
49
 
50
50
  const VERDICTS_SCHEMA_VERSION = 1;
51
51
 
@@ -145,6 +145,11 @@ function parseLog(logPath) {
145
145
  seq: seq++,
146
146
  subtype: obj.subtype ?? '',
147
147
  resultText: typeof obj.result === 'string' ? obj.result : '',
148
+ // `claude -p --json-schema` (validator jobs) puts the checked JSON
149
+ // here and replaces `result` with its string form.
150
+ ...(obj.structured_output && typeof obj.structured_output === 'object' && !Array.isArray(obj.structured_output)
151
+ ? { structuredOutput: obj.structured_output }
152
+ : {}),
148
153
  };
149
154
  resultEvent = ev;
150
155
  events.push(ev);
@@ -220,32 +225,26 @@ function hasAbandonedBackgroundTask(events) {
220
225
  * One layer: queue.json's `dependsOn` array — the same and only dependency
221
226
  * signal the dispatcher (findBlockingDep) uses. PRD body prose is NOT parsed.
222
227
  *
228
+ * Resolution is depSlugResolve.cjs makeDepResolver — the ONE run-time rule
229
+ * findBlockingDep dispatches with, so the verifier can never disagree with
230
+ * the picker. `satisfiedSlugs` (optional history/archive completion records,
231
+ * or DEP_HISTORY_FAIL_OPEN) lets an exact satisfied record win over a live
232
+ * same-bare failed/cancelled row, exactly as dispatch does.
233
+ *
223
234
  * @returns {{ ok: boolean, reason?: string }}
224
235
  */
225
- function checkDeps(queueEntry, allJobs) {
226
- const bySlug = new Map(allJobs.map((j) => [j.slug, j]));
227
- // A PRD's filename carries the allocator's `NN-` prefix, but `dependsOn:` is
228
- // authored with the bare name (the author cannot know the number that will
229
- // be issued). Resolve exact slug first, then bare-name — identical rule to
230
- // schedulerBatch.pickForProject's rowsForDep, which MUST agree with this
231
- // function (see the missing-row note below).
232
- const rowsByBareSlug = new Map();
233
- for (const j of allJobs) {
234
- const bare = String(j.slug ?? '').replace(/^\d+-/, '');
235
- if (!rowsByBareSlug.has(bare)) rowsByBareSlug.set(bare, []);
236
- rowsByBareSlug.get(bare).push(j);
237
- }
238
- const rowsForDep = (slug) => {
239
- const exact = bySlug.get(slug);
240
- if (exact) return [exact];
241
- return rowsByBareSlug.get(String(slug ?? '').replace(/^\d+-/, '')) ?? [];
242
- };
236
+ function checkDeps(queueEntry, allJobs, satisfiedSlugs = new Set()) {
237
+ const jobs = Array.isArray(allJobs) ? allJobs.filter(Boolean) : [];
238
+ const { resolve } = typeof satisfiedSlugs === 'symbol'
239
+ ? makeDepResolver(jobs, new Set(), { failOpen: true })
240
+ : makeDepResolver(jobs, satisfiedSlugs);
243
241
 
244
242
  // 1. Queue-level dependsOn (explicit).
245
243
  const queueDeps = Array.isArray(queueEntry.dependsOn) ? queueEntry.dependsOn : [];
246
244
  for (const depSlug of queueDeps) {
247
- const deps = rowsForDep(depSlug);
248
- // A dep with NO row is SATISFIED, not unmet. Completed rows are retired to
245
+ const { kind, rows: deps } = resolve(depSlug, queueEntry);
246
+ // A dep resolved 'satisfied' (completion record) is met. A dep with NO row
247
+ // ('unresolved' here) is ALSO treated as SATISFIED, not unmet. Completed rows are retired to
249
248
  // history shards and their PRD is archived, so absence is the normal
250
249
  // end-state of a finished dependency — exactly how pickForProject reads it.
251
250
  //
@@ -257,7 +256,7 @@ function checkDeps(queueEntry, allJobs) {
257
256
  // real work: PRDs 854 and 857 each ran to exit 0, were downgraded on a
258
257
  // bare dep name that never matched any row, and ended up on disk with no
259
258
  // queue row at all.
260
- if (deps.length === 0) continue;
259
+ if (kind !== 'row' || deps.length === 0) continue;
261
260
  // Same predicate as findBlockingDep — an auto-resolve skip the picker
262
261
  // dispatched past must not be re-judged unmet here (same infinite re-run).
263
262
  const unfinished = deps.find((d) => !isSatisfiedDepRow(d));
@@ -285,6 +284,9 @@ function scanSentinel(resultEvent, events) {
285
284
  const RE = /^SCHEDULER_VERDICT:\s*(PASS|FAIL|BLOCKED_BY_FOREIGN_WIP|NEEDS_HUMAN)\b/m;
286
285
  const norm = (v) => { const l = v.toLowerCase(); return l === 'needs_human' ? 'fail' : l; };
287
286
 
287
+ const structured = structuredSchedulerVerdict(resultEvent);
288
+ if (structured) return structured;
289
+
288
290
  if (resultEvent) {
289
291
  const m = resultEvent.resultText.match(RE);
290
292
  if (m) return norm(m[1]);
@@ -302,6 +304,18 @@ function scanSentinel(resultEvent, events) {
302
304
  return null;
303
305
  }
304
306
 
307
+ /**
308
+ * 'pass' | 'fail' from a result event's structured_output.schedulerVerdict
309
+ * (validator runs under `--json-schema`), else null.
310
+ */
311
+ function structuredSchedulerVerdict(resultEvent) {
312
+ const so = resultEvent && resultEvent.structuredOutput;
313
+ if (!so || typeof so !== 'object') return null;
314
+ if (so.schedulerVerdict === 'PASS') return 'pass';
315
+ if (so.schedulerVerdict === 'FAIL') return 'fail';
316
+ return null;
317
+ }
318
+
305
319
  /**
306
320
  * First line that starts at column 0 with the exact uppercase halt marker
307
321
  * (`HALT:`) outside a fenced block, else null. Line-anchored and fence-aware
@@ -333,6 +347,10 @@ function scanHaltLine(text) {
333
347
  function scanSentinelReason(resultEvent, events) {
334
348
  const RE = /^SCHEDULER_VERDICT:\s*(?:FAIL|NEEDS_HUMAN)\b[ \t]*([^\n]*)/m;
335
349
  const clip = (m) => m[1].trim().slice(0, 300);
350
+ if (structuredSchedulerVerdict(resultEvent) === 'fail') {
351
+ const fr = resultEvent.structuredOutput.failReason;
352
+ return typeof fr === 'string' ? fr.trim().slice(0, 300) : '';
353
+ }
336
354
  if (resultEvent && resultEvent.resultText) {
337
355
  const m = resultEvent.resultText.match(RE);
338
356
  if (m) return clip(m);
@@ -543,17 +561,26 @@ function isGitRepo(cwd) {
543
561
  * `cwd`, is a non-empty regular file, and has an mtime inside the run window
544
562
  * (startedAt - 60s .. (finishedAt ?? now) + 120s). Never throws: any doubt
545
563
  * (no paths, `..`, escape, missing, non-file, empty, stale, fs error) → false.
546
- * `cwd` may be a list of roots; a path is accepted if it verifies under any.
564
+ * `cwd` may be a list of roots; a path is accepted if it verifies under any —
565
+ * except a `session-manager-operations/plan-records/` path, which verifies only
566
+ * under the first root (the main checkout).
547
567
  * Complexity O(paths).
548
568
  */
549
569
  function artifactsVerifiedOnDisk({ cwd, paths, startedAt, finishedAt, fsImpl = fs } = {}) {
550
570
  return artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl }).ok;
551
571
  }
552
572
 
573
+ const PLAN_RECORDS_PREFIX = 'session-manager-operations/plan-records/';
574
+
553
575
  function artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl = fs }) {
554
576
  const fail = { ok: false, verified: [] };
555
577
  try {
556
- const roots = (Array.isArray(cwd) ? cwd : [cwd]).filter((r) => typeof r === 'string' && r);
578
+ const rawRoots = Array.isArray(cwd) ? cwd : [cwd];
579
+ const roots = rawRoots.filter((r) => typeof r === 'string' && r);
580
+ // A plan record lands in the main checkout only via the scheduler's
581
+ // harvest (planRecordHarvest.cjs), so it verifies against the FIRST root
582
+ // (queueEntry.cwd) alone — a copy left only in the worktree never counts.
583
+ const mainRoot = typeof rawRoots[0] === 'string' && rawRoots[0] ? [rawRoots[0]] : [];
557
584
  if (!roots.length || !Array.isArray(paths) || paths.length === 0) return fail;
558
585
  const start = Date.parse(startedAt ?? '');
559
586
  if (Number.isNaN(start)) return fail;
@@ -566,7 +593,8 @@ function artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl = fs }) {
566
593
  if (typeof p !== 'string' || !p || p.includes('\0')) return fail;
567
594
  if (p.split(/[\\/]/).includes('..')) return fail;
568
595
  let hit = null;
569
- for (const root of roots) {
596
+ const isPlanRecord = path.posix.normalize(p.replace(/\\/g, '/')).startsWith(PLAN_RECORDS_PREFIX);
597
+ for (const root of (isPlanRecord ? mainRoot : roots)) {
570
598
  const base = path.resolve(root);
571
599
  const abs = path.resolve(base, p);
572
600
  const rel = path.relative(base, abs);
@@ -0,0 +1,26 @@
1
+ # src/main/scheduler/ — scoped context
2
+
3
+ Pure, extracted pieces of `../scheduler.cjs` (the most-edited file). Scheduler-family helpers
4
+ (dispatch loop, slots, gates, supervisors, queue store) live in [`../lib/scheduler/`](../lib/AGENTS.md).
5
+ Runtime diagnosis (stuck queue, `needs_review`, reap gate) is NOT here — see
6
+ [`scheduler-operations.md`](../../../session-manager-operations/architecture/scheduler-operations.md).
7
+
8
+ ## Rules
9
+
10
+ - **Spy seam:** call module functions through the module object (`mod.fn()`), never destructure them, so `vi.spyOn` works.
11
+ - **New pure scheduler logic goes in a module here, not in `scheduler.cjs`** (which keeps state, IO and timers).
12
+
13
+ ## If you are changing X, edit Y
14
+
15
+ | Changing | Edit |
16
+ | --- | --- |
17
+ | PRD file parsing, frontmatter, dir/file mtime cache | `prdParser.cjs` |
18
+ | Per-project PRD dirs, slug containment, archive-on-complete, boot migration, queue-backup sweep | `prdPaths.cjs` |
19
+ | `needs_review` / auto-fix / auto-reset eligibility, verdict sets, thresholds | `reviewLadder.cjs` |
20
+ | Git status/stash/HEAD helpers, shared-tree guard, commit-guard, finalize-drop predicates | `gitTreeGuard.cjs` |
21
+ | Starvation / blocked-chain classifiers, dispatch-idle clock | `starvation.cjs` |
22
+ | Stall / stranded-row / overrun / wall-clock budget selectors, failure backoff, `dependsOn` history lookup | `budget.cjs` |
23
+ | `spawnJob` / execution, `tickQueue`, dead-process reaper, poll loop, IPC handlers, admin routes, queue-mutating ladder rungs and watchdogs | `../scheduler.cjs` (by section banner) |
24
+
25
+ Before adding to `scheduler.cjs`, check the table: a predicate or selector belongs above, the
26
+ mutation that acts on it stays in `scheduler.cjs`.
@@ -1,26 +1 @@
1
- # src/main/scheduler/ — scoped context
2
-
3
- Pure, extracted pieces of `../scheduler.cjs` (the most-edited file). Scheduler-family helpers
4
- (dispatch loop, slots, gates, supervisors, queue store) live in [`../lib/scheduler/`](../lib/CLAUDE.md).
5
- Runtime diagnosis (stuck queue, `needs_review`, reap gate) is NOT here — see
6
- [`scheduler-operations.md`](../../../session-manager-operations/architecture/scheduler-operations.md).
7
-
8
- ## Rules
9
-
10
- - **Spy seam:** call module functions through the module object (`mod.fn()`), never destructure them, so `vi.spyOn` works.
11
- - **New pure scheduler logic goes in a module here, not in `scheduler.cjs`** (which keeps state, IO and timers).
12
-
13
- ## If you are changing X, edit Y
14
-
15
- | Changing | Edit |
16
- | --- | --- |
17
- | PRD file parsing, frontmatter, dir/file mtime cache | `prdParser.cjs` |
18
- | Per-project PRD dirs, slug containment, archive-on-complete, boot migration, queue-backup sweep | `prdPaths.cjs` |
19
- | `needs_review` / auto-fix / auto-reset eligibility, verdict sets, thresholds | `reviewLadder.cjs` |
20
- | Git status/stash/HEAD helpers, shared-tree guard, commit-guard, finalize-drop predicates | `gitTreeGuard.cjs` |
21
- | Starvation / blocked-chain classifiers, dispatch-idle clock | `starvation.cjs` |
22
- | Stall / stranded-row / overrun / wall-clock budget selectors, failure backoff, `dependsOn` history lookup | `budget.cjs` |
23
- | `spawnJob` / execution, `tickQueue`, dead-process reaper, poll loop, IPC handlers, admin routes, queue-mutating ladder rungs and watchdogs | `../scheduler.cjs` (by section banner) |
24
-
25
- Before adding to `scheduler.cjs`, check the table: a predicate or selector belongs above, the
26
- mutation that acts on it stays in `scheduler.cjs`.
1
+ @AGENTS.md