claude-code-session-manager 0.141.0 → 0.142.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 (200) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,258 @@
1
+ /**
2
+ * toolClearance.cjs — single-use clearances for tool-risk 'confirm' calls.
3
+ *
4
+ * Flow (see session-manager-operations/architecture/tool-risk.md):
5
+ * 1. The guard (scripts/hooks/lib/guard-tool-risk-policy.cjs) denies a
6
+ * confirm-marked call in a job and records a PENDING confirmation here
7
+ * (one record per tool + args digest, listing every job that asked).
8
+ * 2. The owner answers the Needs-you item. The scheduler takes the pending
9
+ * record and calls answerConfirmation: it emits human.tool_confirmation,
10
+ * and on approve grants one clearance bound to (job, tool, args digest,
11
+ * project) and resumes the SAME Claude session; on deny it parks the job
12
+ * with reason confirmation_denied.
13
+ * 3. In the resumed run the guard calls consumeClearance for the exact call.
14
+ * A matching live clearance lets exactly ONE call through: consumption is
15
+ * an atomic rename, so a second use (or a racing hook) finds nothing. A
16
+ * call with different args has a different digest, so it never matches.
17
+ *
18
+ * State lives machine-level under schedulerHome() (not the operations root):
19
+ * tool-clearances/<key>.json live grants
20
+ * tool-confirmations-pending/<key>.json pending confirmation records
21
+ * Plain Node (no Electron) so the guard hook can require it.
22
+ */
23
+ 'use strict';
24
+
25
+ const crypto = require('node:crypto');
26
+ const fs = require('node:fs');
27
+ const path = require('node:path');
28
+ const { writeJsonAtomicSync } = require('../util/atomicFs.cjs');
29
+
30
+ const CLEARANCES_DIR = 'tool-clearances';
31
+ const PENDING_DIR = 'tool-confirmations-pending';
32
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
33
+ const MAX_TTL_MS = 7 * DEFAULT_TTL_MS;
34
+ const DIGEST_RE = /^[0-9a-f]{64}$/;
35
+ const MAX_REQUESTS_PER_RECORD = 50;
36
+ const DENIED_REASON = 'confirmation_denied';
37
+ const NO_SESSION_REASON = 'confirmation_no_session';
38
+ const EVENT_KIND = 'human.tool_confirmation';
39
+
40
+ function home() {
41
+ return require('./schedulerPaths.cjs').schedulerHome();
42
+ }
43
+
44
+ function clearancesDir(dir) { return dir || path.join(home(), CLEARANCES_DIR); }
45
+ function pendingDir(dir) { return dir || path.join(home(), PENDING_DIR); }
46
+
47
+ function sha(parts) {
48
+ return crypto.createHash('sha256').update(parts.join('\u0000')).digest('hex');
49
+ }
50
+
51
+ /** File key of a clearance: one per (job, tool, args digest). */
52
+ function clearanceKey(jobSlug, tool, argsDigest) {
53
+ return sha(['clearance', jobSlug, tool, argsDigest]).slice(0, 48);
54
+ }
55
+
56
+ /** File key of a pending confirmation: one per (tool, args digest), like its Needs-you item. */
57
+ function confirmationKey(tool, argsDigest) {
58
+ return sha(['confirm', tool, argsDigest]).slice(0, 48);
59
+ }
60
+
61
+ function requireString(name, v) {
62
+ if (typeof v !== 'string' || !v) throw new Error(`toolClearance: ${name} must be a non-empty string`);
63
+ }
64
+
65
+ function requireDigest(v) {
66
+ if (typeof v !== 'string' || !DIGEST_RE.test(v)) throw new Error('toolClearance: argsDigest must be a sha256 hex digest');
67
+ }
68
+
69
+ function readJson(file) {
70
+ try {
71
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Grant one single-use clearance. A new grant for the same key replaces the old one.
79
+ * @param {{ cwd?: string|null, jobSlug: string, tool: string, argsDigest: string, ttlMs?: number, now?: number, dir?: string }} args
80
+ * @returns {{ key: string, file: string, grantedAt: number, expiresAt: number }}
81
+ */
82
+ function grantClearance({ cwd = null, jobSlug, tool, argsDigest, ttlMs = DEFAULT_TTL_MS, now = Date.now(), dir } = /** @type {any} */ ({})) {
83
+ requireString('jobSlug', jobSlug);
84
+ requireString('tool', tool);
85
+ requireDigest(argsDigest);
86
+ const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? Math.min(ttlMs, MAX_TTL_MS) : DEFAULT_TTL_MS;
87
+ const key = clearanceKey(jobSlug, tool, argsDigest);
88
+ const file = path.join(clearancesDir(dir), `${key}.json`);
89
+ const record = { key, cwd: typeof cwd === 'string' && cwd ? cwd : null, jobSlug, tool, argsDigest, grantedAt: now, expiresAt: now + ttl };
90
+ fs.mkdirSync(path.dirname(file), { recursive: true });
91
+ writeJsonAtomicSync(file, record);
92
+ return { key, file, grantedAt: record.grantedAt, expiresAt: record.expiresAt };
93
+ }
94
+
95
+ /**
96
+ * Consume the clearance for this exact call, at most once. Atomic: the grant
97
+ * is renamed aside before it is read, so only one caller can ever win it.
98
+ * A claimed grant is always deleted — expired or mismatched ones included.
99
+ * @param {{ cwd?: string|null, jobSlug: string, tool: string, argsDigest: string, now?: number, dir?: string }} args
100
+ * @returns {{ ok: true, clearance: object } | { ok: false, reason: 'none'|'expired'|'mismatch' }}
101
+ */
102
+ function consumeClearance({ cwd = null, jobSlug, tool, argsDigest, now = Date.now(), dir } = /** @type {any} */ ({})) {
103
+ if (typeof jobSlug !== 'string' || !jobSlug || typeof tool !== 'string' || !tool
104
+ || typeof argsDigest !== 'string' || !DIGEST_RE.test(argsDigest)) {
105
+ return { ok: false, reason: 'none' };
106
+ }
107
+ const file = path.join(clearancesDir(dir), `${clearanceKey(jobSlug, tool, argsDigest)}.json`);
108
+ const claimed = `${file}.consumed-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
109
+ try {
110
+ fs.renameSync(file, claimed);
111
+ } catch {
112
+ return { ok: false, reason: 'none' };
113
+ }
114
+ const record = readJson(claimed);
115
+ try { fs.rmSync(claimed, { force: true }); } catch { /* best effort */ }
116
+ if (!record || record.jobSlug !== jobSlug || record.tool !== tool || record.argsDigest !== argsDigest) {
117
+ return { ok: false, reason: 'mismatch' };
118
+ }
119
+ if (!(typeof record.expiresAt === 'number' && record.expiresAt > now)) return { ok: false, reason: 'expired' };
120
+ if (record.cwd && cwd && path.resolve(record.cwd) !== path.resolve(cwd)) return { ok: false, reason: 'mismatch' };
121
+ return { ok: true, clearance: record };
122
+ }
123
+
124
+ /**
125
+ * Delete every expired (or unreadable) grant. Never throws.
126
+ * @param {{ now?: number, dir?: string }} [opts]
127
+ * @returns {number} grants removed
128
+ */
129
+ function pruneExpired({ now = Date.now(), dir } = {}) {
130
+ let removed = 0;
131
+ let names = [];
132
+ try { names = fs.readdirSync(clearancesDir(dir)); } catch { return 0; }
133
+ for (const name of names) {
134
+ if (!name.endsWith('.json')) continue;
135
+ const file = path.join(clearancesDir(dir), name);
136
+ const rec = readJson(file);
137
+ if (rec && typeof rec.expiresAt === 'number' && rec.expiresAt > now) continue;
138
+ try { fs.rmSync(file, { force: true }); removed++; } catch { /* next */ }
139
+ }
140
+ return removed;
141
+ }
142
+
143
+ // ── pending confirmations ───────────────────────────────────────────────────
144
+
145
+ /**
146
+ * Record (or extend) the pending confirmation for one guard refusal. One
147
+ * record per (tool, digest); each job asks at most once in it. Never throws.
148
+ * @param {{ tool: string, argsDigest: string, jobSlug: string, sessionId?: string|null, epicId?: string|null, cwd?: string|null, rule?: string, summary?: string }} req
149
+ * @param {{ dir?: string, now?: number }} [opts]
150
+ * @returns {boolean}
151
+ */
152
+ function recordPendingConfirmation(req, { dir, now = Date.now() } = {}) {
153
+ try {
154
+ requireString('tool', req.tool);
155
+ requireDigest(req.argsDigest);
156
+ requireString('jobSlug', req.jobSlug);
157
+ const key = confirmationKey(req.tool, req.argsDigest);
158
+ const file = path.join(pendingDir(dir), `${key}.json`);
159
+ const existing = readJson(file);
160
+ const requests = existing && Array.isArray(existing.requests) ? existing.requests : [];
161
+ if (requests.some((r) => r && r.jobSlug === req.jobSlug)) return true;
162
+ if (requests.length >= MAX_REQUESTS_PER_RECORD) return false;
163
+ requests.push({
164
+ tool: req.tool,
165
+ argsDigest: req.argsDigest,
166
+ jobSlug: req.jobSlug,
167
+ sessionId: typeof req.sessionId === 'string' && req.sessionId ? req.sessionId : null,
168
+ epicId: typeof req.epicId === 'string' && req.epicId ? req.epicId : null,
169
+ cwd: typeof req.cwd === 'string' && req.cwd ? req.cwd : null,
170
+ ...(typeof req.rule === 'string' ? { rule: req.rule } : {}),
171
+ ...(typeof req.summary === 'string' ? { summary: req.summary } : {}),
172
+ requestedAt: now,
173
+ });
174
+ fs.mkdirSync(path.dirname(file), { recursive: true });
175
+ writeJsonAtomicSync(file, { key, tool: req.tool, argsDigest: req.argsDigest, requests });
176
+ return true;
177
+ } catch (e) {
178
+ console.error(`[toolClearance] pending confirmation not recorded: ${e && e.message}`);
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /** @returns {{ key: string, tool: string, argsDigest: string, requests: object[] }[]} */
184
+ function listPendingConfirmations({ dir } = {}) {
185
+ let names = [];
186
+ try { names = fs.readdirSync(pendingDir(dir)); } catch { return []; }
187
+ const out = [];
188
+ for (const name of names.sort()) {
189
+ if (!name.endsWith('.json')) continue;
190
+ const rec = readJson(path.join(pendingDir(dir), name));
191
+ if (rec && typeof rec.key === 'string' && Array.isArray(rec.requests)) out.push(rec);
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /** Atomically take (remove and return) one pending record, or null when it is gone. */
197
+ function takePendingConfirmation(key, { dir } = {}) {
198
+ if (typeof key !== 'string' || !/^[0-9a-f]{1,64}$/.test(key)) return null;
199
+ const file = path.join(pendingDir(dir), `${key}.json`);
200
+ const claimed = `${file}.taken-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
201
+ try { fs.renameSync(file, claimed); } catch { return null; }
202
+ const rec = readJson(claimed);
203
+ try { fs.rmSync(claimed, { force: true }); } catch { /* best effort */ }
204
+ return rec && Array.isArray(rec.requests) ? rec : null;
205
+ }
206
+
207
+ // ── answering ───────────────────────────────────────────────────────────────
208
+
209
+ /**
210
+ * Apply the owner's answer to one job's confirmation request.
211
+ * approve → emit human.tool_confirmation { approved: true }, grant the
212
+ * clearance, resume({ jobSlug, sessionId, request }) — same session.
213
+ * deny → emit human.tool_confirmation { approved: false },
214
+ * park({ jobSlug, reason: 'confirmation_denied', request }).
215
+ * An approval with no session id to resume parks with 'confirmation_no_session'.
216
+ * @param {{ request: any, approved: boolean, ttlMs?: number, now?: number, dir?: string }} answer
217
+ * @param {{ emit: (e: object) => void, resume: (r: object) => void, park: (p: object) => void }} deps
218
+ * @returns {{ action: 'resume'|'park', clearance?: object }}
219
+ */
220
+ function answerConfirmation({ request, approved, ttlMs, now = Date.now(), dir }, deps) {
221
+ requireString('jobSlug', request && request.jobSlug);
222
+ const event = {
223
+ kind: EVENT_KIND,
224
+ approved: approved === true,
225
+ tool: request.tool,
226
+ argsDigest: request.argsDigest,
227
+ jobSlug: request.jobSlug,
228
+ ...(request.rule ? { rule: request.rule } : {}),
229
+ };
230
+ try { deps.emit(event); } catch (e) { console.error(`[toolClearance] event emit failed: ${e && e.message}`); }
231
+ if (approved === true && request.sessionId) {
232
+ const clearance = grantClearance({
233
+ cwd: request.cwd, jobSlug: request.jobSlug, tool: request.tool, argsDigest: request.argsDigest, ttlMs, now, dir,
234
+ });
235
+ deps.resume({ jobSlug: request.jobSlug, sessionId: request.sessionId, request });
236
+ return { action: 'resume', clearance };
237
+ }
238
+ deps.park({ jobSlug: request.jobSlug, reason: approved === true ? NO_SESSION_REASON : DENIED_REASON, request });
239
+ return { action: 'park' };
240
+ }
241
+
242
+ module.exports = {
243
+ CLEARANCES_DIR,
244
+ PENDING_DIR,
245
+ DEFAULT_TTL_MS,
246
+ DENIED_REASON,
247
+ NO_SESSION_REASON,
248
+ EVENT_KIND,
249
+ clearanceKey,
250
+ confirmationKey,
251
+ grantClearance,
252
+ consumeClearance,
253
+ pruneExpired,
254
+ recordPendingConfirmation,
255
+ listPendingConfirmations,
256
+ takePendingConfirmation,
257
+ answerConfirmation,
258
+ };
@@ -10,7 +10,10 @@
10
10
  * The CLI enforces the schema itself; parseValidatorVerdict is the defensive
11
11
  * second check plus the rules a schema cannot express: a non-empty REFUTED
12
12
  * reason, unique `prd` values, and at least one missKind on every REFUTED
13
- * entry.
13
+ * entry. With `{ expected }` (prd -> { ids, failedIds }, built by the
14
+ * scheduler from each judged PRD's frontmatter `criteria` and its stored
15
+ * mechanical check results) it also refuses an entry that omits a criterion
16
+ * id or marks met: true a criterion whose mechanical check failed.
14
17
  *
15
18
  * Pure: no I/O, no dependencies, never throws, never mutates its input.
16
19
  */
@@ -22,6 +25,10 @@
22
25
  /** @typedef {{ prd: string, verdict: 'VERIFIED'|'REFUTED', reason: string, criteria: Criterion[], findings: Finding[] }} VerdictEntry */
23
26
  /** @typedef {{ schedulerVerdict: 'PASS'|'FAIL', failReason?: string, verdicts: VerdictEntry[] }} ValidatorVerdict */
24
27
  /** @typedef {{ slug: string, verdict: 'verified'|'refuted', reason: string, missKinds: MissKind[] }} VerdictRow */
28
+ /** @typedef {{ ids: string[], failedIds?: string[] }} ExpectedCriteria */
29
+ /** @typedef {Record<string, ExpectedCriteria> | Map<string, ExpectedCriteria>} ExpectedMap */
30
+ /** @typedef {'criterion-missing'|'criterion-met-on-failed-check'} CriteriaErrorCode */
31
+ /** @typedef {{ ok: true, value: ValidatorVerdict } | { ok: false, error: string, code?: CriteriaErrorCode }} ParseResult */
25
32
 
26
33
  /** One-line meaning per miss kind, in MISS_KINDS order. */
27
34
  const MISS_KIND_MEANINGS = Object.freeze({
@@ -78,9 +85,9 @@ const VALIDATOR_VERDICT_SCHEMA = {
78
85
  properties: {
79
86
  id: {
80
87
  type: 'string',
81
- description: "The criterion's 1-based position in the judged PRD's # Acceptance criteria list, as a string ('1', '2', ...).",
88
+ description: "The criterion's id: when the judged PRD lists structured criteria with ids (e.g. 'ac-1'), that id exactly; otherwise its 1-based position in the PRD's # Acceptance criteria list, as a string ('1', '2', ...). Return one entry per criterion id.",
82
89
  },
83
- met: { type: 'boolean' },
90
+ met: { type: 'boolean', description: 'Never true when that criterion\'s mechanical check failed.' },
84
91
  evidence: { type: 'string', description: 'What was checked and what it showed.' },
85
92
  missKind: { type: 'string', enum: [...MISS_KINDS], description: MISS_KIND_DESCRIPTION + ' Set it on every unmet criterion.' },
86
93
  },
@@ -193,13 +200,62 @@ function checkEntry(e, where) {
193
200
  return null;
194
201
  }
195
202
 
203
+ /** Leading numeric prefix stripped (`3612-a` -> `a`). */
204
+ function bareOf(slug) {
205
+ return String(slug).replace(/^\d+-/, '');
206
+ }
207
+
208
+ /**
209
+ * The expected-criteria entry for one judged prd: exact key first, then a
210
+ * bare-slug match (a validator may report `x` for a PRD filed as `3612-x`).
211
+ * @param {ExpectedMap} expected
212
+ * @param {string} prd
213
+ * @returns {ExpectedCriteria|null}
214
+ */
215
+ function lookupExpected(expected, prd) {
216
+ const entries = expected instanceof Map ? [...expected.entries()] : Object.entries(expected);
217
+ for (const [k, v] of entries) if (k === prd) return v;
218
+ const bare = bareOf(prd);
219
+ for (const [k, v] of entries) if (bareOf(k) === bare) return v;
220
+ return null;
221
+ }
222
+
196
223
  /**
197
- * parseValidatorVerdict(value) → { ok: true, value } | { ok: false, error }.
198
- * Never throws.
224
+ * Cross-check one entry's criteria against what the scheduler expects.
225
+ * @param {VerdictEntry} entry
226
+ * @param {ExpectedCriteria} exp
227
+ * @param {string} where
228
+ * @returns {{ error: string, code: CriteriaErrorCode }|null}
229
+ */
230
+ function checkExpectedCriteria(entry, exp, where) {
231
+ const ids = Array.isArray(exp.ids) ? exp.ids.filter((x) => typeof x === 'string') : [];
232
+ const failed = new Set(Array.isArray(exp.failedIds) ? exp.failedIds.filter((x) => typeof x === 'string') : []);
233
+ const reported = new Set(entry.criteria.map((c) => c.id));
234
+ for (const id of ids) {
235
+ if (!reported.has(id)) {
236
+ return { error: `${where} (${entry.prd}): missing criterion id ${id}`, code: 'criterion-missing' };
237
+ }
238
+ }
239
+ for (const c of entry.criteria) {
240
+ if (c.met === true && failed.has(c.id)) {
241
+ return {
242
+ error: `${where} (${entry.prd}): criterion ${c.id} marked met but its mechanical check failed`,
243
+ code: 'criterion-met-on-failed-check',
244
+ };
245
+ }
246
+ }
247
+ return null;
248
+ }
249
+
250
+ /**
251
+ * parseValidatorVerdict(value, { expected }?) → { ok: true, value } | { ok: false, error, code? }.
252
+ * `expected` maps a judged prd slug to { ids, failedIds }; an entry whose prd
253
+ * has no expected record is checked as before. Never throws.
199
254
  * @param {unknown} value
200
- * @returns {{ ok: true, value: ValidatorVerdict } | { ok: false, error: string }}
255
+ * @param {{ expected?: ExpectedMap|null }} [opts]
256
+ * @returns {ParseResult}
201
257
  */
202
- function parseValidatorVerdict(value) {
258
+ function parseValidatorVerdict(value, opts = {}) {
203
259
  try {
204
260
  if (!isPlainObject(value)) return { ok: false, error: 'verdict: not an object' };
205
261
  const keyErr = checkKeys(value, ['schedulerVerdict', 'verdicts'], ['schedulerVerdict', 'failReason', 'verdicts'], 'verdict');
@@ -211,15 +267,23 @@ function parseValidatorVerdict(value) {
211
267
  return { ok: false, error: 'failReason: not a string' };
212
268
  }
213
269
  if (!Array.isArray(value.verdicts)) return { ok: false, error: 'verdicts: not an array' };
270
+ const expected = opts && (opts.expected instanceof Map || isPlainObject(opts.expected)) ? opts.expected : null;
214
271
  /** @type {Set<string>} */
215
272
  const seen = new Set();
216
273
  for (let i = 0; i < value.verdicts.length; i++) {
217
274
  const where = `verdicts[${i}]`;
218
275
  const err = checkEntry(value.verdicts[i], where);
219
276
  if (err) return { ok: false, error: err };
220
- const prd = /** @type {VerdictEntry} */ (value.verdicts[i]).prd;
221
- if (seen.has(prd)) return { ok: false, error: `${where}.prd: duplicate ${prd}` };
222
- seen.add(prd);
277
+ const entry = /** @type {VerdictEntry} */ (value.verdicts[i]);
278
+ if (seen.has(entry.prd)) return { ok: false, error: `${where}.prd: duplicate ${entry.prd}` };
279
+ seen.add(entry.prd);
280
+ if (expected) {
281
+ const exp = lookupExpected(/** @type {ExpectedMap} */ (expected), entry.prd);
282
+ if (exp && typeof exp === 'object') {
283
+ const critErr = checkExpectedCriteria(entry, exp, where);
284
+ if (critErr) return { ok: false, ...critErr };
285
+ }
286
+ }
223
287
  }
224
288
  return { ok: true, value: /** @type {ValidatorVerdict} */ (/** @type {unknown} */ (value)) };
225
289
  } catch (err) {
@@ -227,6 +291,70 @@ function parseValidatorVerdict(value) {
227
291
  }
228
292
  }
229
293
 
294
+ /**
295
+ * expectedFromCriteria(criteria, checks) → ExpectedCriteria | null.
296
+ * `criteria` is a PRD's frontmatter `criteria` list ({ id, ... }); `checks`
297
+ * its stored mechanical results ({ id, ok }). failedIds = ids whose check
298
+ * came back ok: false (a manual check, ok: null, never counts as failed).
299
+ * Null when the PRD has no structured criteria.
300
+ * @param {unknown} criteria
301
+ * @param {unknown} checks
302
+ * @returns {{ ids: string[], failedIds: string[] }|null}
303
+ */
304
+ function expectedFromCriteria(criteria, checks) {
305
+ if (!Array.isArray(criteria)) return null;
306
+ const ids = criteria
307
+ .map((c) => (isPlainObject(c) && typeof c.id === 'string' ? c.id : null))
308
+ .filter((x) => typeof x === 'string' && x !== '');
309
+ if (!ids.length) return null;
310
+ const idSet = new Set(ids);
311
+ const failedIds = (Array.isArray(checks) ? checks : [])
312
+ .filter((c) => isPlainObject(c) && c.ok === false && typeof c.id === 'string' && idSet.has(c.id))
313
+ .map((c) => /** @type {string} */ (/** @type {Record<string, unknown>} */ (c).id));
314
+ return { ids, failedIds: [...new Set(failedIds)] };
315
+ }
316
+
317
+ /**
318
+ * formatCriteriaChecksSection(prds) → Markdown for the validator prompt: per
319
+ * judged PRD, each criterion id, its statement, and its stored mechanical
320
+ * check result. '' when no PRD has structured criteria.
321
+ * @param {Array<{ slug: string, criteria: unknown, checks: unknown }>} prds
322
+ * @returns {string}
323
+ */
324
+ function formatCriteriaChecksSection(prds) {
325
+ const oneLine = (v, max = 300) => {
326
+ const t = String(v ?? '').replace(/[\r\n]+/g, ' ').trim();
327
+ return t.length > max ? `${t.slice(0, max)}…` : t;
328
+ };
329
+ const blocks = [];
330
+ for (const p of Array.isArray(prds) ? prds : []) {
331
+ if (!p || !Array.isArray(p.criteria) || !p.criteria.length) continue;
332
+ /** @type {Map<string, Record<string, unknown>>} */
333
+ const byId = new Map();
334
+ for (const c of Array.isArray(p.checks) ? p.checks : []) {
335
+ if (isPlainObject(c) && typeof c.id === 'string') byId.set(c.id, c);
336
+ }
337
+ const lines = [`### ${oneLine(p.slug, 200)}`];
338
+ for (const c of p.criteria) {
339
+ if (!isPlainObject(c) || typeof c.id !== 'string') continue;
340
+ const r = byId.get(c.id);
341
+ const kind = isPlainObject(c.check) && typeof c.check.kind === 'string' ? c.check.kind : 'manual';
342
+ const result = !r ? 'not run' : r.ok === true ? 'PASS' : r.ok === false ? 'FAIL' : 'manual';
343
+ const detail = r && r.detail ? ` — ${oneLine(r.detail)}` : '';
344
+ lines.push(`- \`${oneLine(c.id, 60)}\` (${kind}) ${result}${detail}: ${oneLine(c.statement)}`);
345
+ }
346
+ blocks.push(lines.join('\n'));
347
+ }
348
+ if (!blocks.length) return '';
349
+ return [
350
+ '## Stored mechanical check results',
351
+ '',
352
+ 'The scheduler ran each structured criterion\'s mechanical check when the PRD finished. In your verdict JSON, return one `criteria` entry per criterion id below, using that id exactly. A criterion whose check is FAIL must be `met: false` — a verdict marking it met is refused.',
353
+ '',
354
+ ...blocks,
355
+ ].join('\n');
356
+ }
357
+
230
358
  /**
231
359
  * verdictRowsFromStructured(value) → VerdictRow[] in input order; [] when the
232
360
  * value does not pass parseValidatorVerdict.
@@ -251,4 +379,6 @@ module.exports = {
251
379
  SEVERITIES,
252
380
  parseValidatorVerdict,
253
381
  verdictRowsFromStructured,
382
+ expectedFromCriteria,
383
+ formatCriteriaChecksSection,
254
384
  };