claude-code-session-manager 0.140.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 (204) 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--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.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/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -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
  };
@@ -0,0 +1,300 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * memoryConsolidation.cjs — a weekly, per-project memory review Task.
5
+ *
6
+ * For every project whose human switch 'Scripts may run Tasks' is ON, at most
7
+ * once per 7 days (or earlier, at most once per 24 h, while the project's
8
+ * MEMORY.md index is over the health.cjs memory budget) this starts ONE Task
9
+ * through the existing Task start path — POST /admin/tasks on the app's own
10
+ * loopback admin server (switch check, persona → pinned --model/--effort,
11
+ * slot cap, ledger). The Task:
12
+ * - gets the memoryStale.cjs candidates (memoryTool.stale → scoreMemories)
13
+ * and the index size in its prompt,
14
+ * - runs a maintaining-md-network Drift check, read-only,
15
+ * - answers with ONE keep/move/drop table.
16
+ * This module then posts that table as ONE "Needs you" item
17
+ * (POST /admin/needs-you). Nothing is ever deleted or edited: the Task runs
18
+ * with read-only tools (Read, Grep, Glob) and its prompt forbids writes; the
19
+ * human decides from the Needs you item.
20
+ *
21
+ * Cadence state is the Task ledger itself (caller.pipeline ===
22
+ * PIPELINE) — no new ops namespace, no second writer.
23
+ */
24
+
25
+ const http = require('node:http');
26
+ const crypto = require('node:crypto');
27
+ const path = require('node:path');
28
+
29
+ const PIPELINE = 'memory-consolidation';
30
+ const MISSION_ID = 'memory-consolidation';
31
+ const AGENT = 'dev-lead';
32
+ const NEEDS_YOU_APP = 'memory-consolidation';
33
+ const DAY_MS = 86_400_000;
34
+ const WEEK_MS = 7 * DAY_MS;
35
+ const OVER_BUDGET_MIN_GAP_MS = DAY_MS;
36
+ const TICK_MS = 60 * 60 * 1000;
37
+ const FIRST_TICK_MS = 5 * 60 * 1000;
38
+ const MAX_CANDIDATES = 60;
39
+ const NEEDS_YOU_WHY_MAX = 1000;
40
+ const PROPOSAL_START = '<<<PROPOSAL';
41
+ const PROPOSAL_END = 'PROPOSAL>>>';
42
+ const READ_ONLY_TOOLS = Object.freeze(['Read', 'Grep', 'Glob']);
43
+
44
+ const NO_DELETE_RULE = 'Do NOT delete, move, rename, edit or create any file. You only propose; the human decides.';
45
+
46
+ /** cwd → true while a consolidation for it is being started or is running. */
47
+ const inFlight = new Set();
48
+
49
+ /**
50
+ * The Task prompt. Pure.
51
+ * @param {{ cwd: string, memoryDir?: string|null, candidates?: Array<any>, budget?: { bytes?: number, lines?: number, maxBytes?: number, maxLines?: number, overBudget?: boolean } | null }} o
52
+ * @returns {string}
53
+ */
54
+ function buildConsolidationPrompt({ cwd, memoryDir = null, candidates = [], budget = null } = /** @type {any} */ ({})) {
55
+ const list = (Array.isArray(candidates) ? candidates : []).slice(0, MAX_CANDIDATES);
56
+ const lines = list.length
57
+ ? list.map((c) => {
58
+ const reasons = Array.isArray(c.reasons) && c.reasons.length ? c.reasons.join('; ') : 'no stale signal';
59
+ const dead = Array.isArray(c.deadRefs) && c.deadRefs.length ? ` dead refs: ${c.deadRefs.slice(0, 5).join(', ')}` : '';
60
+ return `- ${c.name} (age ${c.ageDays ?? '?'} d, inbound links ${c.inboundLinks ?? 0}): ${reasons}.${dead}`;
61
+ }).join('\n')
62
+ : '- (no stale candidates were found)';
63
+ const budgetLine = budget && Number.isFinite(budget.bytes)
64
+ ? `MEMORY.md index: ${budget.bytes} bytes / ${budget.lines} lines (budget ${budget.maxBytes} bytes / ${budget.maxLines} lines)${budget.overBudget ? ' — OVER BUDGET: Claude Code loads only the first 200 lines / 25 KB, so entries past that are invisible.' : '.'}`
65
+ : 'MEMORY.md index size: unknown.';
66
+
67
+ return [
68
+ `You are reviewing the auto-memory and markdown network of the project at ${cwd}.`,
69
+ '',
70
+ 'HARD RULES',
71
+ `1. ${NO_DELETE_RULE}`,
72
+ '2. Use only read tools (Read, Grep, Glob). Never run a shell command, never write.',
73
+ '3. Your whole answer is ONE keep/move/drop table. It is posted as ONE "Needs you" item for the owner; do not split it.',
74
+ '',
75
+ 'INPUTS',
76
+ `Memory folder: ${memoryDir || '(unknown — skip memory files you cannot read)'}`,
77
+ budgetLine,
78
+ 'Stale candidates (memoryStale scoreMemories):',
79
+ lines,
80
+ '',
81
+ 'STEPS',
82
+ '1. Read each candidate memory file and the MEMORY.md index.',
83
+ '2. Run a maintaining-md-network Drift check (read-only): if',
84
+ ' plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md exists in this project, follow its',
85
+ ' "Drift check" mode; otherwise check that every fact lives in exactly one place and that links and',
86
+ ' paths in CLAUDE.md / AGENTS.md / docs / memories resolve.',
87
+ '3. For each candidate and each drift finding pick one action:',
88
+ ' keep (still true and needed), move (belongs in a named doc or memory — give the target), drop (stale or duplicated).',
89
+ '',
90
+ 'OUTPUT — exactly this, nothing before or after:',
91
+ PROPOSAL_START,
92
+ '| Item | Action (keep/move/drop) | Target (for move) | Why |',
93
+ '|---|---|---|---|',
94
+ '| ... | ... | ... | ... |',
95
+ PROPOSAL_END,
96
+ ].join('\n');
97
+ }
98
+
99
+ /** The table between the markers, else the whole result text, trimmed. */
100
+ function extractProposal(text) {
101
+ const s = String(text || '');
102
+ const a = s.indexOf(PROPOSAL_START);
103
+ const b = s.indexOf(PROPOSAL_END, a + 1);
104
+ if (a !== -1 && b !== -1) return s.slice(a + PROPOSAL_START.length, b).trim();
105
+ return s.trim();
106
+ }
107
+
108
+ function cwdKey(cwd) {
109
+ return crypto.createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 16);
110
+ }
111
+
112
+ /** Loopback JSON POST to the app's own admin server (index.cjs passes it). */
113
+ function adminPosterFor(adminHttp) {
114
+ return (/** @type {string} */ urlPath, /** @type {any} */ body) => new Promise((resolve, reject) => {
115
+ const server = adminHttp && adminHttp.server;
116
+ const addr = server && typeof server.address === 'function' ? server.address() : null;
117
+ if (!addr || typeof addr !== 'object' || !adminHttp.token) {
118
+ reject(new Error('admin server is not running'));
119
+ return;
120
+ }
121
+ const data = Buffer.from(JSON.stringify(body), 'utf8');
122
+ const req = http.request({
123
+ hostname: '127.0.0.1',
124
+ port: addr.port,
125
+ method: 'POST',
126
+ path: urlPath,
127
+ headers: { Authorization: `Bearer ${adminHttp.token}`, 'Content-Type': 'application/json', 'Content-Length': data.length },
128
+ }, (res) => {
129
+ let raw = '';
130
+ res.setEncoding('utf8');
131
+ res.on('data', (c) => { raw += c; });
132
+ res.on('end', () => {
133
+ let json = null;
134
+ try { json = JSON.parse(raw); } catch { /* non-JSON reply */ }
135
+ resolve({ status: res.statusCode, body: json });
136
+ });
137
+ });
138
+ req.setTimeout(0);
139
+ req.on('error', reject);
140
+ req.end(data);
141
+ });
142
+ }
143
+
144
+ function defaultDeps() {
145
+ return {
146
+ isTaskSwitchOn: (/** @type {string} */ cwd) => require('./taskSwitch.cjs').isTaskSwitchOn(cwd),
147
+ listTasks: (/** @type {string} */ cwd, /** @type {any} */ o) => require('./taskLedger.cjs').listTasks(cwd, o),
148
+ measureBudget: (/** @type {string} */ cwd) => {
149
+ const health = require('../../health.cjs');
150
+ const m = health.measureProjectMemory(cwd);
151
+ if (!m) return null;
152
+ const budget = health.resolveMemoryBudget();
153
+ const { component } = health.evaluateMemoryBudget([m], budget);
154
+ return { dir: m.dir, bytes: m.bytes, lines: m.lines, maxBytes: budget.maxBytes, maxLines: budget.maxLines, overBudget: component.ok === false };
155
+ },
156
+ staleCandidates: async (/** @type {string} */ cwd) => {
157
+ const r = await require('../../memoryTool.cjs').stale({ cwd });
158
+ return (r && Array.isArray(r.entries) ? r.entries : []).filter((e) => e && e.stale);
159
+ },
160
+ };
161
+ }
162
+
163
+ /** Last consolidation start (ms) within the window, else null. */
164
+ async function lastStartMs(listTasks, cwd, sinceMs) {
165
+ const { tasks } = await listTasks(cwd, { pipeline: PIPELINE, since: new Date(sinceMs).toISOString(), limit: 1 });
166
+ const t = tasks && tasks[0];
167
+ const ms = t ? Date.parse(t.startedAt) : NaN;
168
+ return Number.isFinite(ms) ? ms : null;
169
+ }
170
+
171
+ /**
172
+ * Decide and, when due, start one consolidation Task for `cwd`.
173
+ * Resolves { started: false, reason } or { started: true, reason, done } where
174
+ * `done` settles after the Task ran and its Needs you item was posted. Never throws.
175
+ *
176
+ * @param {{ cwd: string, now?: number, deps?: {
177
+ * isTaskSwitchOn?: (cwd: string) => boolean,
178
+ * listTasks?: (cwd: string, o: any) => Promise<{ tasks: any[] }>,
179
+ * measureBudget?: (cwd: string) => any,
180
+ * staleCandidates?: (cwd: string) => Promise<any[]>,
181
+ * adminPost?: (path: string, body: any) => Promise<{ status: number, body: any }>,
182
+ * } }} o
183
+ */
184
+ async function maybeStartConsolidation({ cwd, now = Date.now(), deps = {} } = /** @type {any} */ ({})) {
185
+ const d = { ...defaultDeps(), ...deps };
186
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return { started: false, reason: 'invalid_cwd' };
187
+ const key = path.resolve(cwd);
188
+ try {
189
+ if (!d.isTaskSwitchOn(key)) return { started: false, reason: 'switch_off' };
190
+ if (inFlight.has(key)) return { started: false, reason: 'in_flight' };
191
+ if (typeof d.adminPost !== 'function') return { started: false, reason: 'no_admin_server' };
192
+
193
+ let budget = null;
194
+ try { budget = d.measureBudget(key); } catch { budget = null; }
195
+ const overBudget = !!(budget && budget.overBudget);
196
+
197
+ const last = await lastStartMs(d.listTasks, key, now - WEEK_MS);
198
+ if (last != null) {
199
+ if (!overBudget) return { started: false, reason: 'not_due' };
200
+ if (now - last < OVER_BUDGET_MIN_GAP_MS) return { started: false, reason: 'not_due' };
201
+ }
202
+
203
+ let candidates = [];
204
+ try { candidates = await d.staleCandidates(key); } catch { candidates = []; }
205
+
206
+ const prompt = buildConsolidationPrompt({ cwd: key, memoryDir: budget ? budget.dir : null, candidates, budget });
207
+ const reason = last == null ? 'weekly' : 'over_budget';
208
+ inFlight.add(key);
209
+ const done = runAndPost({ cwd: key, now, prompt, reason, adminPost: d.adminPost })
210
+ .catch((e) => ({ ok: false, error: e instanceof Error ? e.message : String(e) }))
211
+ .finally(() => { inFlight.delete(key); });
212
+ return { started: true, reason, done };
213
+ } catch (e) {
214
+ return { started: false, reason: 'error', error: e instanceof Error ? e.message : String(e) };
215
+ }
216
+ }
217
+
218
+ async function runAndPost({ cwd, now, prompt, reason, adminPost }) {
219
+ const runId = `${new Date(now).toISOString().slice(0, 10)}-${cwdKey(cwd)}`;
220
+ const task = await adminPost('/admin/tasks', {
221
+ cwd,
222
+ agent: AGENT,
223
+ missionId: MISSION_ID,
224
+ prompt,
225
+ priority: 'batch',
226
+ timeoutSec: 1800,
227
+ slotWaitSec: 1800,
228
+ caller: { pipeline: PIPELINE, runId, step: reason },
229
+ runtime: {
230
+ outputFormat: 'json',
231
+ tools: [...READ_ONLY_TOOLS],
232
+ allowedTools: [...READ_ONLY_TOOLS],
233
+ },
234
+ });
235
+ const b = task && task.body;
236
+ if (!task || task.status !== 200 || !b || b.ok !== true || b.status !== 'ok') {
237
+ return { ok: false, error: (b && (b.error || b.status)) || `http_${task && task.status}`, taskId: b && b.taskId };
238
+ }
239
+ const resultText = b.envelope && typeof b.envelope.result === 'string' ? b.envelope.result : '';
240
+ const proposal = extractProposal(resultText);
241
+ if (!proposal) return { ok: false, error: 'empty_proposal', taskId: b.taskId };
242
+
243
+ const note = `\n…(full table: Task ${b.taskId}, Scheduler → Tasks)`;
244
+ const why = proposal.length > NEEDS_YOU_WHY_MAX
245
+ ? proposal.slice(0, NEEDS_YOU_WHY_MAX - note.length) + note
246
+ : proposal;
247
+ const posted = await adminPost('/admin/needs-you', {
248
+ app: NEEDS_YOU_APP,
249
+ id: `memory-consolidation:${runId}`,
250
+ title: `Memory review for ${path.basename(cwd)}: keep / move / drop`,
251
+ why,
252
+ cwd,
253
+ });
254
+ const ok = !!(posted && posted.status === 200 && posted.body && posted.body.ok);
255
+ return { ok, taskId: b.taskId, needsYou: ok ? posted.body.item : null, error: ok ? undefined : (posted && posted.body && posted.body.error) || 'needs_you_failed' };
256
+ }
257
+
258
+ /**
259
+ * Hourly sweep (first after 5 min) over every project with the switch on.
260
+ * index.cjs calls this once the admin server is up. Returns a stop function.
261
+ * @param {{ adminHttp: any, log?: (msg: string, meta?: any) => void, intervalMs?: number }} o
262
+ */
263
+ function startConsolidationTimer({ adminHttp, log = () => {}, intervalMs = TICK_MS }) {
264
+ const adminPost = adminPosterFor(adminHttp);
265
+ const tick = async () => {
266
+ let projects = [];
267
+ try { projects = require('./taskSwitch.cjs').listTaskProjects().filter((p) => p.enabled); } catch { projects = []; }
268
+ for (const p of projects) {
269
+ const r = await maybeStartConsolidation({ cwd: p.cwd, now: Date.now(), deps: { adminPost } });
270
+ if (r.started) {
271
+ log('memory consolidation started', { cwd: p.cwd, reason: r.reason });
272
+ r.done.then((out) => log('memory consolidation finished', { cwd: p.cwd, ...out }));
273
+ } else if (r.reason === 'error') {
274
+ log('memory consolidation check failed', { cwd: p.cwd, error: r.error });
275
+ }
276
+ }
277
+ };
278
+ const safeTick = () => { tick().catch(() => {}); };
279
+ const first = setTimeout(safeTick, FIRST_TICK_MS);
280
+ const every = setInterval(safeTick, intervalMs);
281
+ if (typeof first.unref === 'function') first.unref();
282
+ if (typeof every.unref === 'function') every.unref();
283
+ return () => { clearTimeout(first); clearInterval(every); };
284
+ }
285
+
286
+ function _resetForTests() {
287
+ inFlight.clear();
288
+ }
289
+
290
+ module.exports = {
291
+ buildConsolidationPrompt,
292
+ maybeStartConsolidation,
293
+ startConsolidationTimer,
294
+ extractProposal,
295
+ adminPosterFor,
296
+ PIPELINE,
297
+ NO_DELETE_RULE,
298
+ READ_ONLY_TOOLS,
299
+ _resetForTests,
300
+ };