claude-code-session-manager 0.142.0 → 0.144.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 (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * planReviewSchema.cjs — the JSON Schema the plan-reviewer returns through
5
+ * `claude -p --json-schema`, a strict parser, and an allOk predicate.
6
+ * Mirrors validatorVerdictSchema.cjs: the CLI enforces the simple schema
7
+ * (enums + required); parsePlanReview adds the cross-field rules (PRD slugs
8
+ * match `expected`, amend|block needs findings, no unknown keys).
9
+ *
10
+ * Pure: no I/O, never throws, never mutates its input.
11
+ */
12
+
13
+ /** @typedef {'Critical'|'Important'|'Minor'} Severity */
14
+ /** @typedef {'ok'|'amend'|'block'} Decision */
15
+ /** @typedef {{ severity: Severity, check: string, text: string, suggestedEdit?: string, field?: string }} PrdFinding */
16
+ /** @typedef {{ prd: string, decision: Decision, findings: PrdFinding[] }} PrdReview */
17
+ /** @typedef {{ severity: Severity, check: string, text: string }} PlanFinding */
18
+ /** @typedef {{ prds: PrdReview[], planFindings: PlanFinding[] }} PlanReview */
19
+ /** @typedef {{ ok: true, value: PlanReview } | { ok: false, error: string }} ParseResult */
20
+
21
+ const PLAN_REVIEW_CHECKS = [
22
+ 'provable-criterion',
23
+ 'failure-path',
24
+ 'edge-case',
25
+ 'vacuous-by-sibling',
26
+ 'depends-on',
27
+ 'gate-green-at-base',
28
+ 'http-criterion',
29
+ 'doc-after-code',
30
+ ];
31
+ const SEVERITIES = ['Critical', 'Important', 'Minor'];
32
+ const DECISIONS = ['ok', 'amend', 'block'];
33
+
34
+ const PLAN_REVIEW_SCHEMA = {
35
+ type: 'object',
36
+ required: ['prds', 'planFindings'],
37
+ properties: {
38
+ prds: {
39
+ type: 'array',
40
+ items: {
41
+ type: 'object',
42
+ required: ['prd', 'decision', 'findings'],
43
+ properties: {
44
+ prd: { type: 'string' },
45
+ decision: { type: 'string', enum: DECISIONS },
46
+ findings: {
47
+ type: 'array',
48
+ items: {
49
+ type: 'object',
50
+ required: ['severity', 'check', 'text'],
51
+ properties: {
52
+ severity: { type: 'string', enum: SEVERITIES },
53
+ check: { type: 'string', enum: PLAN_REVIEW_CHECKS },
54
+ text: { type: 'string' },
55
+ suggestedEdit: { type: 'string' },
56
+ field: { type: 'string' },
57
+ },
58
+ },
59
+ },
60
+ },
61
+ },
62
+ },
63
+ planFindings: {
64
+ type: 'array',
65
+ items: {
66
+ type: 'object',
67
+ required: ['severity', 'check', 'text'],
68
+ properties: {
69
+ severity: { type: 'string', enum: SEVERITIES },
70
+ check: { type: 'string', enum: PLAN_REVIEW_CHECKS },
71
+ text: { type: 'string' },
72
+ },
73
+ },
74
+ },
75
+ },
76
+ };
77
+
78
+ /** @param {unknown} v @returns {v is Record<string, unknown>} */
79
+ function isPlainObject(v) {
80
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
81
+ }
82
+
83
+ /**
84
+ * @param {Record<string, unknown>} obj
85
+ * @param {string[]} required
86
+ * @param {string[]} allowed
87
+ * @param {string} where
88
+ * @returns {string|null}
89
+ */
90
+ function checkKeys(obj, required, allowed, where) {
91
+ for (const k of required) if (!(k in obj)) return `${where}: missing ${k}`;
92
+ for (const k of Object.keys(obj)) if (!allowed.includes(k)) return `${where}: unexpected key ${k}`;
93
+ return null;
94
+ }
95
+
96
+ /**
97
+ * @param {unknown} f
98
+ * @param {string} where
99
+ * @param {boolean} prdLevel
100
+ * @returns {string|null}
101
+ */
102
+ function checkFinding(f, where, prdLevel) {
103
+ if (!isPlainObject(f)) return `${where}: not an object`;
104
+ const keyErr = checkKeys(
105
+ f,
106
+ ['severity', 'check', 'text'],
107
+ prdLevel ? ['severity', 'check', 'text', 'suggestedEdit', 'field'] : ['severity', 'check', 'text'],
108
+ where,
109
+ );
110
+ if (keyErr) return keyErr;
111
+ if (!SEVERITIES.includes(/** @type {string} */ (f.severity))) return `${where}.severity: not one of ${SEVERITIES.join(', ')}`;
112
+ if (!PLAN_REVIEW_CHECKS.includes(/** @type {string} */ (f.check))) return `${where}.check: unknown check ${String(f.check)}`;
113
+ if (typeof f.text !== 'string') return `${where}.text: not a string`;
114
+ if (f.suggestedEdit !== undefined && typeof f.suggestedEdit !== 'string') return `${where}.suggestedEdit: not a string`;
115
+ if (f.field !== undefined && typeof f.field !== 'string') return `${where}.field: not a string`;
116
+ return null;
117
+ }
118
+
119
+ /**
120
+ * parsePlanReview(value, { expected }) → { ok, value | error }.
121
+ * `expected` is the list (array or Set) of PRD slugs the review must cover
122
+ * exactly: none missing, none extra, none duplicated.
123
+ * @param {unknown} value
124
+ * @param {{ expected?: Iterable<string>|null }} [opts]
125
+ * @returns {ParseResult}
126
+ */
127
+ function parsePlanReview(value, opts = {}) {
128
+ try {
129
+ if (!isPlainObject(value)) return { ok: false, error: 'review: not an object' };
130
+ const keyErr = checkKeys(value, ['prds', 'planFindings'], ['prds', 'planFindings'], 'review');
131
+ if (keyErr) return { ok: false, error: keyErr };
132
+ if (!Array.isArray(value.prds)) return { ok: false, error: 'prds: not an array' };
133
+ if (!Array.isArray(value.planFindings)) return { ok: false, error: 'planFindings: not an array' };
134
+ /** @type {Set<string>} */
135
+ const seen = new Set();
136
+ for (let i = 0; i < value.prds.length; i++) {
137
+ const where = `prds[${i}]`;
138
+ const p = value.prds[i];
139
+ if (!isPlainObject(p)) return { ok: false, error: `${where}: not an object` };
140
+ const pe = checkKeys(p, ['prd', 'decision', 'findings'], ['prd', 'decision', 'findings'], where);
141
+ if (pe) return { ok: false, error: pe };
142
+ if (typeof p.prd !== 'string' || !p.prd) return { ok: false, error: `${where}.prd: not a non-empty string` };
143
+ if (seen.has(p.prd)) return { ok: false, error: `${where}.prd: duplicate ${p.prd}` };
144
+ seen.add(p.prd);
145
+ if (!DECISIONS.includes(/** @type {string} */ (p.decision))) {
146
+ return { ok: false, error: `${where}.decision: not one of ${DECISIONS.join(', ')}` };
147
+ }
148
+ if (!Array.isArray(p.findings)) return { ok: false, error: `${where}.findings: not an array` };
149
+ for (let j = 0; j < p.findings.length; j++) {
150
+ const err = checkFinding(p.findings[j], `${where}.findings[${j}]`, true);
151
+ if (err) return { ok: false, error: err };
152
+ }
153
+ if (p.decision !== 'ok' && p.findings.length === 0) {
154
+ return { ok: false, error: `${where}: decision ${p.decision} needs at least one finding` };
155
+ }
156
+ }
157
+ for (let i = 0; i < value.planFindings.length; i++) {
158
+ const err = checkFinding(value.planFindings[i], `planFindings[${i}]`, false);
159
+ if (err) return { ok: false, error: err };
160
+ }
161
+ if (opts && opts.expected) {
162
+ const exp = new Set(opts.expected);
163
+ for (const slug of exp) if (!seen.has(slug)) return { ok: false, error: `prds: missing ${slug}` };
164
+ for (const slug of seen) if (!exp.has(slug)) return { ok: false, error: `prds: unexpected ${slug}` };
165
+ }
166
+ return { ok: true, value: /** @type {PlanReview} */ (/** @type {unknown} */ (value)) };
167
+ } catch (err) {
168
+ return { ok: false, error: `review: ${err instanceof Error ? err.message : String(err)}` };
169
+ }
170
+ }
171
+
172
+ /**
173
+ * True only when every PRD decision is ok and planFindings is empty.
174
+ * @param {PlanReview} review
175
+ * @returns {boolean}
176
+ */
177
+ function isAllOk(review) {
178
+ if (!review || !Array.isArray(review.prds) || !Array.isArray(review.planFindings)) return false;
179
+ return review.planFindings.length === 0 && review.prds.every((p) => p && p.decision === 'ok');
180
+ }
181
+
182
+ module.exports = { PLAN_REVIEW_SCHEMA, PLAN_REVIEW_CHECKS, parsePlanReview, isAllOk };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * planReviewStats.cjs — pure aggregate comparing an Epic's reviewed plans (a
5
+ * stored plan-review record with a release) against its unreviewed ones, on
6
+ * review findings accepted/rejected, validator findings, REFUTED verdicts and
7
+ * fixes[] escapes (missKind spec-gap | missing-test).
8
+ *
9
+ * A plan is a validate slug. A PRD belongs to a reviewed plan when it appears
10
+ * in that record's reviews[].review.prds[].prd (bare slug). Every other verdict
11
+ * or fix is unreviewed; unreviewed `plans` counts the distinct `validator` slugs (else `plan`) a
12
+ * verdict entry carries; a record with no stored review or a timeout release is not reviewed (entries with none add to the totals only).
13
+ */
14
+
15
+ const ESCAPE_KINDS = new Set(['spec-gap', 'missing-test']);
16
+ const isObj = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
17
+ const bare = (s) => String(s).replace(/^\d+-/, '');
18
+
19
+ /**
20
+ * @param {{ planReviews?: any[], verdictFiles?: any[], fixes?: any[] }} [input]
21
+ */
22
+ function planReviewStats({ planReviews, verdictFiles, fixes } = {}) {
23
+ const reviewed = { plans: 0, acceptedFindings: 0, rejectedFindings: 0, validatorFindings: 0, refuted: 0, escapes: 0 };
24
+ const unreviewed = { plans: 0, validatorFindings: 0, refuted: 0, escapes: 0 };
25
+ const member = new Map(); // bare prd slug -> validateSlug of a reviewed plan
26
+
27
+ for (const rec of Array.isArray(planReviews) ? planReviews : []) {
28
+ if (!isObj(rec) || !isObj(rec.release)) continue;
29
+ if (!Array.isArray(rec.reviews) || rec.reviews.length === 0) continue;
30
+ if (rec.release.by === 'timeout') continue;
31
+ reviewed.plans += 1;
32
+ const acc = rec.release.accepted;
33
+ if (Number.isFinite(acc)) reviewed.acceptedFindings += acc;
34
+ if (Array.isArray(rec.release.rejected)) reviewed.rejectedFindings += rec.release.rejected.length;
35
+ for (const r of Array.isArray(rec.reviews) ? rec.reviews : []) {
36
+ const prds = isObj(r) && isObj(r.review) && Array.isArray(r.review.prds) ? r.review.prds : [];
37
+ for (const p of prds) if (isObj(p) && typeof p.prd === 'string') member.set(bare(p.prd), rec.validateSlug);
38
+ }
39
+ }
40
+
41
+ const unreviewedPlanKeys = new Set();
42
+ for (const v of Array.isArray(verdictFiles) ? verdictFiles : []) {
43
+ if (!isObj(v) || typeof v.prd !== 'string') continue;
44
+ const target = member.has(bare(v.prd)) ? reviewed : unreviewed;
45
+ if (target === unreviewed) {
46
+ const raw = typeof v.validator === 'string' && v.validator ? v.validator : v.plan;
47
+ const key = typeof raw === 'string' && raw ? bare(raw) : null;
48
+ if (key) unreviewedPlanKeys.add(key);
49
+ }
50
+ target.validatorFindings += Array.isArray(v.findings) ? v.findings.length : 0;
51
+ if (v.verdict === 'REFUTED') target.refuted += 1;
52
+ }
53
+ unreviewed.plans = unreviewedPlanKeys.size;
54
+
55
+ for (const f of Array.isArray(fixes) ? fixes : []) {
56
+ if (!isObj(f) || typeof f.prd !== 'string' || !ESCAPE_KINDS.has(f.missKind)) continue;
57
+ (member.has(bare(f.prd)) ? reviewed : unreviewed).escapes += 1;
58
+ }
59
+
60
+ return { reviewed, unreviewed };
61
+ }
62
+
63
+ module.exports = { planReviewStats };
@@ -0,0 +1,128 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * planReviewStore.cjs — read/write `plan-records/<epic>/<validate-slug>.plan-review.json`:
5
+ * the independent plan review(s), the round count, and the release record.
6
+ * Writes go through opsPath + writeJsonAtomic as the plan-records namespace's
7
+ * owner ('scheduler'). Unsafe ids/slugs are refused before any path is built.
8
+ */
9
+
10
+ const fs = require('node:fs');
11
+ const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
12
+ const { writeJsonAtomic } = require('../util/atomicFs.cjs');
13
+ const { EPIC_ID_RE } = require('./planRecordHarvest.cjs');
14
+
15
+ const NAMESPACE = 'plan-records';
16
+ const WRITER = 'scheduler';
17
+ const SUFFIX = '.plan-review.json';
18
+ const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
19
+ const RELEASE_BY = ['planner', 'auto', 'timeout'];
20
+
21
+ function safeIds(epicId, validateSlug) {
22
+ return typeof epicId === 'string' && EPIC_ID_RE.test(epicId)
23
+ && typeof validateSlug === 'string' && SLUG_RE.test(validateSlug)
24
+ && !validateSlug.includes('..');
25
+ }
26
+
27
+ function assertSafe(epicId, validateSlug) {
28
+ if (!safeIds(epicId, validateSlug)) {
29
+ throw new Error('planReviewStore: unsafe epicId or validateSlug');
30
+ }
31
+ }
32
+
33
+ /** Absolute record path; throws on an unsafe epicId/slug. */
34
+ function planReviewPath(cwd, epicId, validateSlug) {
35
+ assertSafe(epicId, validateSlug);
36
+ return opsPath(cwd, NAMESPACE, epicId, `${validateSlug}${SUFFIX}`);
37
+ }
38
+
39
+ function readFile(file) {
40
+ try {
41
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
42
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ /** The record, or null when missing, malformed, or the ids are unsafe. */
49
+ function readPlanReview(cwd, epicId, validateSlug) {
50
+ if (!safeIds(epicId, validateSlug)) return null;
51
+ return readFile(planReviewPath(cwd, epicId, validateSlug));
52
+ }
53
+
54
+ async function writeRecord(cwd, record) {
55
+ const file = planReviewPath(cwd, record.epicId, record.validateSlug);
56
+ assertOpsWrite(file, WRITER);
57
+ await writeJsonAtomic(file, record);
58
+ return file;
59
+ }
60
+
61
+ /** Append one review round; the record's `round` becomes the saved round. */
62
+ async function savePlanReviewResult({
63
+ cwd, epicId, validateSlug, round, reviewer, runId, model, review,
64
+ } = {}) {
65
+ assertSafe(epicId, validateSlug);
66
+ const prior = readPlanReview(cwd, epicId, validateSlug);
67
+ const reviews = prior && Array.isArray(prior.reviews) ? prior.reviews.slice() : [];
68
+ const n = Number.isFinite(round) ? round : reviews.length + 1;
69
+ reviews.push({ round: n, at: new Date().toISOString(), reviewer, runId, model, review });
70
+ const record = {
71
+ ...(prior || {}),
72
+ validateSlug,
73
+ epicId,
74
+ round: n,
75
+ reviews,
76
+ release: prior && prior.release ? prior.release : null,
77
+ };
78
+ if (n === 2) record.rereviewRequested = false;
79
+ await writeRecord(cwd, record);
80
+ return record;
81
+ }
82
+
83
+ /** Record the release once. An already-released record is left untouched. */
84
+ async function recordPlanRelease({
85
+ cwd, epicId, validateSlug, by, rejected = [], accepted = 0,
86
+ } = {}) {
87
+ assertSafe(epicId, validateSlug);
88
+ if (!RELEASE_BY.includes(by)) throw new Error(`planReviewStore: bad release actor '${by}'`);
89
+ const prior = readPlanReview(cwd, epicId, validateSlug);
90
+ if (prior && prior.release) return { alreadyReleased: true };
91
+ const record = {
92
+ ...(prior || {}),
93
+ validateSlug,
94
+ epicId,
95
+ round: prior && Number.isFinite(prior.round) ? prior.round : 0,
96
+ reviews: prior && Array.isArray(prior.reviews) ? prior.reviews : [],
97
+ release: {
98
+ at: new Date().toISOString(),
99
+ by,
100
+ rejected: (Array.isArray(rejected) ? rejected : []).map((r) => ({
101
+ finding: String(r && r.finding != null ? r.finding : ''),
102
+ reason: String(r && r.reason != null ? r.reason : ''),
103
+ })),
104
+ accepted: Number.isFinite(accepted) ? accepted : 0,
105
+ },
106
+ };
107
+ await writeRecord(cwd, record);
108
+ return record;
109
+ }
110
+
111
+ /** Every readable record in an Epic's folder; [] for unsafe id/missing folder. */
112
+ function readPlanReviewFiles(cwd, epicId) {
113
+ if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) return [];
114
+ const dir = opsPath(cwd, NAMESPACE, epicId);
115
+ let names;
116
+ try { names = fs.readdirSync(dir); } catch { return []; }
117
+ const out = [];
118
+ for (const name of names.sort()) {
119
+ if (!name.endsWith(SUFFIX)) continue;
120
+ const rec = readFile(`${dir}/${name}`);
121
+ if (rec) out.push(rec);
122
+ }
123
+ return out;
124
+ }
125
+
126
+ module.exports = {
127
+ planReviewPath, readPlanReview, savePlanReviewResult, recordPlanRelease, readPlanReviewFiles,
128
+ };
@@ -18,7 +18,7 @@
18
18
 
19
19
  const path = require('node:path');
20
20
  const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
21
- const { writeJsonAtomic } = require('../util/atomicFs.cjs');
21
+ const { writeJsonAtomic, writeTextAtomic, readJsonOr } = require('../util/atomicFs.cjs');
22
22
 
23
23
  const WRITER = 'scheduler';
24
24
  const SCHEMA_VERSION = 1;
@@ -77,6 +77,64 @@ async function writeOutcomeRecord({
77
77
  return file;
78
78
  }
79
79
 
80
+ /**
81
+ * mergeOutcomeChecks({ cwd, epicId, slug, checks, write? }) → Promise<boolean>
82
+ * (true when a record was rewritten). Replaces the existing record's `checks`
83
+ * entries by id with the fresh ones (each stamped ranAt + stage
84
+ * 'validator-dispatch' unless already stamped), keeps every other entry, and
85
+ * writes atomically as 'scheduler'. No record on disk → no write. Never throws.
86
+ */
87
+ async function mergeOutcomeChecks({ cwd, epicId, slug, checks, write = writeJsonAtomic } = {}) {
88
+ try {
89
+ const file = outcomeRecordPath(cwd, epicId, slug);
90
+ const record = await readJsonOr(file, null);
91
+ if (!record || typeof record !== 'object' || Array.isArray(record)) return false;
92
+ const ranAt = new Date().toISOString();
93
+ const fresh = objList(checks)
94
+ .filter((c) => typeof c.id === 'string' && c.id)
95
+ .map((c) => ({ ...c, ranAt: c.ranAt || ranAt, stage: c.stage || 'validator-dispatch' }));
96
+ const freshById = new Map(fresh.map((c) => [c.id, c]));
97
+ const merged = [];
98
+ const seen = new Set();
99
+ for (const c of objList(record.checks)) {
100
+ if (typeof c.id === 'string' && freshById.has(c.id)) {
101
+ if (!seen.has(c.id)) { merged.push(freshById.get(c.id)); seen.add(c.id); }
102
+ } else merged.push(c);
103
+ }
104
+ for (const c of fresh) if (!seen.has(c.id)) { merged.push(c); seen.add(c.id); }
105
+ assertOpsWrite(file, WRITER);
106
+ await write(file, { ...record, checks: merged });
107
+ return true;
108
+ } catch (e) {
109
+ console.error('[prdOutcomeRecord] mergeOutcomeChecks failed', epicId, slug, e && e.message ? e.message : e);
110
+ return false;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * writeCheckBody({ cwd, epicId, slug, id, body, write? }) → Promise<string|null>.
116
+ * Writes one http check's response body to
117
+ * scheduler/epics/<epicId>/outcomes/<slug>.bodies/<id>.txt (atomic, writer
118
+ * 'scheduler'; overwritten per id, so each check keeps one copy). Returns the
119
+ * absolute path, or null on a bad id / write failure. Never throws. The
120
+ * directory lives under the Epic's scheduler folder, so epicPurge removes it
121
+ * with the outcome records.
122
+ */
123
+ async function writeCheckBody({ cwd, epicId, slug, id, body, write = writeTextAtomic } = {}) {
124
+ try {
125
+ assertIds(epicId, slug);
126
+ if (typeof id !== 'string' || !SLUG_RE.test(id) || id.includes('..')) throw new Error(`invalid check id "${id}"`);
127
+ if (typeof body !== 'string') throw new Error('body must be a string');
128
+ const file = opsPath(cwd, 'scheduler', 'epics', epicId, 'outcomes', `${slug}.bodies`, `${id}.txt`);
129
+ assertOpsWrite(file, WRITER);
130
+ await write(file, body);
131
+ return file;
132
+ } catch (e) {
133
+ console.error('[prdOutcomeRecord] writeCheckBody failed', epicId, slug, id, e && e.message ? e.message : e);
134
+ return null;
135
+ }
136
+ }
137
+
80
138
  /**
81
139
  * Pure: derive { verdict, commits, files, gates, checks } from a finalized
82
140
  * job row plus the run's verifyResult. `gates` holds the verifier verdict
@@ -129,5 +187,5 @@ async function listCommitFiles(cwd, shas) {
129
187
  }
130
188
 
131
189
  module.exports = {
132
- writeOutcomeRecord, outcomeRecordPath, buildOutcomeFromJob, listCommitFiles, SCHEMA_VERSION,
190
+ writeOutcomeRecord, mergeOutcomeChecks, writeCheckBody, outcomeRecordPath, buildOutcomeFromJob, listCommitFiles, SCHEMA_VERSION,
133
191
  };
@@ -403,6 +403,21 @@ function loadMachineStateSync() {
403
403
  }
404
404
  }
405
405
 
406
+ /**
407
+ * The machine-runtime state file's `config` (firePolicy, utilizationThreshold,
408
+ * …) or {} when the file is missing, unreadable or carries none. Reads only the
409
+ * small machine file — never a project queue shard — and never throws.
410
+ */
411
+ function readMachineConfigSync() {
412
+ try {
413
+ const m = loadMachineStateSync();
414
+ const c = m && m.shaped && m.shaped.config;
415
+ return c && typeof c === 'object' ? c : {};
416
+ } catch {
417
+ return {};
418
+ }
419
+ }
420
+
406
421
  async function loadMachineState() {
407
422
  let raw;
408
423
  try {
@@ -604,6 +619,7 @@ module.exports = {
604
619
  writeJsonAtomic,
605
620
  writeJsonAtomicSync,
606
621
  findLongestValidJsonPrefix,
622
+ readMachineConfigSync,
607
623
  };
608
624
 
609
625
  // Lazy path getters (SM_SCHEDULER_HOME resolved at read, never at require).
@@ -34,7 +34,13 @@ const fs = require('node:fs');
34
34
  const path = require('node:path');
35
35
  const { splitFrontmatter } = require('../prd/prdFrontmatter.cjs');
36
36
  const { readTail } = require('../util/fileTail.cjs');
37
- const { resolvePrdWriteDir } = require('../prd/prdLocations.cjs');
37
+ const {
38
+ resolvePrdWriteDir,
39
+ resolveEpicPrdWriteDir,
40
+ listEpicPrdDirs,
41
+ listArchivedPrdDirs,
42
+ isSafeEpicId,
43
+ } = require('../prd/prdLocations.cjs');
38
44
  const atomicFs = require('../util/atomicFs.cjs');
39
45
 
40
46
  // ─── VERDICT_LABELS — deliberate duplicate ──────────────────────────────────
@@ -74,6 +80,7 @@ const FAILURE_CLASSES = {
74
80
  TRANSCRIPT_ERRORS: 'transcript-errors',
75
81
  ABANDONED_BACKGROUND_TASK: 'abandoned-background-task',
76
82
  BLOCKED_BY_FOREIGN_WIP: 'blocked-by-foreign-wip',
83
+ EXECUTOR_FAIL: 'executor-fail',
77
84
  UNKNOWN: 'unknown',
78
85
  };
79
86
 
@@ -105,6 +112,7 @@ const RECOVERY_ACTIONS = {
105
112
  // guidance into that cold-read investigation.
106
113
  [FAILURE_CLASSES.ABANDONED_BACKGROUND_TASK]: 'investigate',
107
114
  [FAILURE_CLASSES.BLOCKED_BY_FOREIGN_WIP]: 'archive',
115
+ [FAILURE_CLASSES.EXECUTOR_FAIL]: 'investigate',
108
116
  [FAILURE_CLASSES.UNKNOWN]: 'investigate',
109
117
  };
110
118
 
@@ -132,6 +140,8 @@ const PREVENTION_HINTS = {
132
140
  'A headless run cannot receive a background-task completion notification — never let a long Bash command auto-background past its foreground timeout and then wait for it. Run long commands with an explicit bound (`timeout <N> <cmd>`) so they finish in the foreground, or poll their output file directly instead of waiting on Monitor/notification.',
133
141
  [FAILURE_CLASSES.BLOCKED_BY_FOREIGN_WIP]:
134
142
  'This job correctly reported `SCHEDULER_VERDICT: BLOCKED_BY_FOREIGN_WIP` against a sibling job\'s in-flight, uncommitted files three times in a row — auto-requeue is exhausted (reconcile() only clears this once the blocked paths go clean). This is not a defect in this PRD\'s own work: check on the sibling job/human that owns the still-dirty path(s) named on the job row, and either wait for them to commit or manually reset this job to `pending` once the tree is clear. Do not author a fix-plan PRD against it.',
143
+ [FAILURE_CLASSES.EXECUTOR_FAIL]:
144
+ "The executor ended `SCHEDULER_VERDICT: FAIL` and stated why — read its reason under 'What happened'. That stated reason, not a log-tail pattern, is what to fix. If the blocker is a step only a person can do (an account, dashboard or signing action), it belongs behind a preflight hold, not in the job body (PRD_AUTHORING.md §6).",
135
145
  [FAILURE_CLASSES.UNKNOWN]:
136
146
  'Re-run the acceptance criteria gate locally against the failure log to pin down the specific break before re-queuing.',
137
147
  };
@@ -162,7 +172,13 @@ const SELF_QUEUE_SKILL_RE = /Launching skill: session-manager-dev:(develop|proce
162
172
  // rule now requires a stream-json tool_use `"name":"ScheduleWakeup"` field, and
163
173
  // classifyFailure strips init events before any rule runs.
164
174
  const SELF_QUEUE_WAKEUP_RE = /"name"\s*:\s*"ScheduleWakeup"/;
165
- const STUCK_LOOP_RE = /\b(until\s|while\s+true|sleep\s)/i;
175
+ // Stuck-loop rule: matched only against real Bash tool_use commands (see
176
+ // bashCommandsIn), never prose. Incident: starry-night-2
177
+ // 856-ios-testflight-public-link (run 2026-11-24T17-02-30-189Z) — the old
178
+ // word rule matched 'until ' in skill-catalog text in the log tail; 49 of 114
179
+ // reports since 2026-11-17 were prose false positives.
180
+ const UNBOUNDED_LOOP_RE = /\b(?:while\s+(?:true\b|:)|until\s)[\s\S]*?(?:;|\n)\s*do\b/;
181
+ const TIMEOUT_BOUND_RE = /\btimeout\s+(?:-\S+\s+)*\d/;
166
182
  const AC_CHECKBOX_RE = /^\s*[-*]\s*\[[xX]\]/;
167
183
  const SENTINEL_PASS_RE = /SCHEDULER_VERDICT:\s*PASS/;
168
184
  const STUCK_LOOP_WINDOW = 40; // "final lines" per AC
@@ -188,6 +204,31 @@ function structuredPassLine(line) {
188
204
  }
189
205
  }
190
206
 
207
+ /**
208
+ * Shell commands from stream-json Bash tool_use events in `lines`. Plain-text
209
+ * lines, assistant text blocks, tool_result content and system events yield
210
+ * nothing; malformed JSON lines are skipped. Pure; O(n) in characters.
211
+ */
212
+ function bashCommandsIn(lines) {
213
+ const out = [];
214
+ for (const line of lines || []) {
215
+ if (typeof line !== 'string' || !line.includes('"tool_use"') || !line.includes('"Bash"')) continue;
216
+ let obj;
217
+ try {
218
+ obj = JSON.parse(line.trim());
219
+ } catch {
220
+ continue;
221
+ }
222
+ if (!obj || obj.type !== 'assistant' || !Array.isArray(obj.message?.content)) continue;
223
+ for (const c of obj.message.content) {
224
+ if (c && c.type === 'tool_use' && c.name === 'Bash' && typeof c.input?.command === 'string') {
225
+ out.push(c.input.command);
226
+ }
227
+ }
228
+ }
229
+ return out;
230
+ }
231
+
191
232
  /**
192
233
  * Drop every stream-json harness init event (`"type":"system"` +
193
234
  * `"subtype":"init"`) from a log tail. That line names every available tool
@@ -239,22 +280,27 @@ function classifyFailure({ verdict, logTail: rawLogTail }) {
239
280
  // Checked before SELF_QUEUE/STUCK_LOOP: the verifier already did the real
240
281
  // detection work (scanning for the harness's own auto-background marker
241
282
  // text) to produce this verdict — trust it rather than re-deriving from the
242
- // log tail, which can otherwise false-match SELF_QUEUE_WAKEUP_RE/STUCK_LOOP_RE
243
- // on words like "sleep"/"background" that appear in the harness's own
244
- // auto-background tool_result.
283
+ // log tail, which can otherwise false-match SELF_QUEUE_WAKEUP_RE on words
284
+ // like "background" that appear in the harness's own auto-background
285
+ // tool_result.
245
286
  if (verdict === 'abandoned_background_task') {
246
287
  return FAILURE_CLASSES.ABANDONED_BACKGROUND_TASK;
247
288
  }
248
289
 
249
290
  // Checked before STUCK_LOOP: a backgrounded command + ScheduleWakeup
250
291
  // (variant b) can land words like "sleep"/"poll" in the tail via the PRD's
251
- // own AC text, which would otherwise false-match STUCK_LOOP_RE (see PRD 771).
292
+ // own AC text; self-queue is the truer class for that run (see PRD 771).
252
293
  if (SELF_QUEUE_SKILL_RE.test(logTail || '') || SELF_QUEUE_WAKEUP_RE.test(logTail || '')) {
253
294
  return FAILURE_CLASSES.SELF_QUEUE;
254
295
  }
255
296
 
297
+ // Checked before STUCK_LOOP: the executor ended SCHEDULER_VERDICT: FAIL and
298
+ // stated its own reason — trust that over any log-tail pattern.
299
+ if (verdict === 'sentinel_fail') return FAILURE_CLASSES.EXECUTOR_FAIL;
300
+
301
+ // Only a real, unbounded Bash loop command counts — never prose.
256
302
  const tailWindow = lines.slice(-STUCK_LOOP_WINDOW);
257
- if (tailWindow.some((l) => STUCK_LOOP_RE.test(l))) {
303
+ if (bashCommandsIn(tailWindow).some((cmd) => UNBOUNDED_LOOP_RE.test(cmd) && !TIMEOUT_BOUND_RE.test(cmd))) {
258
304
  return FAILURE_CLASSES.STUCK_LOOP;
259
305
  }
260
306
 
@@ -317,14 +363,31 @@ function readRunMeta(runDir, slug) {
317
363
  }
318
364
  }
319
365
 
320
- function readPrdBody(cwd, slug) {
321
- if (!cwd) return '';
322
- try {
323
- const raw = fs.readFileSync(path.join(resolvePrdWriteDir(cwd), `${slug}.md`), 'utf8');
324
- return splitFrontmatter(raw).body;
325
- } catch {
326
- return '';
366
+ /**
367
+ * Read the parked job's PRD body (frontmatter stripped). Looks where PRDs
368
+ * really live, in order: the job's own Epic prds/, every Epic prds/ of the
369
+ * project, every prds-archived/ twin, then the retired flat dir. Scoped to
370
+ * job.cwd only — never a machine-wide scan. Returns '' when not found; never
371
+ * throws.
372
+ */
373
+ function readPrdBody(job) {
374
+ const cwd = job?.cwd;
375
+ const slug = job?.slug;
376
+ if (!cwd || typeof cwd !== 'string' || !slug) return '';
377
+ const candidates = [];
378
+ const add = (dir) => { if (dir && !candidates.includes(dir)) candidates.push(dir); };
379
+ if (isSafeEpicId(job.epicId)) {
380
+ try { add(resolveEpicPrdWriteDir(cwd, job.epicId)); } catch { /* skip */ }
381
+ }
382
+ try { for (const d of listEpicPrdDirs(cwd)) add(d); } catch { /* skip */ }
383
+ try { for (const d of listArchivedPrdDirs(cwd)) add(d); } catch { /* skip */ }
384
+ try { add(resolvePrdWriteDir(cwd)); } catch { /* skip */ }
385
+ for (const dir of candidates) {
386
+ let raw;
387
+ try { raw = fs.readFileSync(path.join(dir, `${slug}.md`), 'utf8'); } catch { continue; }
388
+ try { return splitFrontmatter(raw).body; } catch { return ''; }
327
389
  }
390
+ return '';
328
391
  }
329
392
 
330
393
  /**
@@ -412,7 +475,7 @@ async function writeRcaReport({ job, runDir, verdict, annotations, investigation
412
475
  const meta = readRunMeta(runDir, job.slug);
413
476
  const logPath = runDir ? path.join(runDir, `${job.slug}.log`) : null;
414
477
  const logTail = logPath ? readTail(logPath, 64 * 1024) : '';
415
- const acText = extractAcceptanceCriteria(readPrdBody(job.cwd, job.slug));
478
+ const acText = extractAcceptanceCriteria(readPrdBody(job));
416
479
  const failureClass = classifyFailure({ verdict, logTail });
417
480
 
418
481
  const markdown = buildRcaMarkdown({
@@ -442,6 +505,7 @@ module.exports = {
442
505
  // Pure helpers, exported for unit tests.
443
506
  humanVerdict,
444
507
  classifyFailure,
508
+ bashCommandsIn,
445
509
  stripHarnessInitEvents,
446
510
  extractAcceptanceCriteria,
447
511
  extractRcaBlock,