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,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
+ };
@@ -0,0 +1,294 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * mitigationReview.cjs — re-test the model-mitigations registry when the
5
+ * default executor model changes.
6
+ *
7
+ * The registry (session-manager-operations/architecture/model-mitigations.md)
8
+ * lists every rule that exists only to work around how a model behaves. When
9
+ * the default executor model id changes, some rows may no longer be needed.
10
+ *
11
+ * For every project whose human switch 'Scripts may run Tasks' is ON and that
12
+ * carries the registry file, an hourly tick:
13
+ * 1. resolves the default executor model id — the dev-lead persona's model
14
+ * (overlay-aware), else the Settings model, else agentModelResolve's
15
+ * FALLBACK_MODEL; an alias is mapped to the newest concrete id of its
16
+ * family that modelCatalog found in the CLI binary;
17
+ * 2. compares it with the last-seen id recorded per project in
18
+ * ~/.claude/session-manager/mitigation-review.json (machine-global app
19
+ * state, not an ops namespace — like model-catalog.json);
20
+ * 3. on a change, records the new id and starts ONE review Task through the
21
+ * existing Task start path (POST /admin/tasks: switch check, persona →
22
+ * pinned --model/--effort, slot cap, ledger). Its prompt lists every
23
+ * registry row; it runs read-only (Read, Grep, Glob) as dev-lead, i.e. on
24
+ * the new default model itself, and answers with ONE keep/remove table;
25
+ * 4. posts that table as ONE "Needs you" item (POST /admin/needs-you).
26
+ * Nothing is edited: the human decides which rows (and rules) to retire.
27
+ * The first sighting only records the id (no previous model → no change).
28
+ * With the switch off nothing is recorded, so a change seen while off is still
29
+ * reviewed once the switch is turned on.
30
+ */
31
+
32
+ const fs = require('node:fs');
33
+ const path = require('node:path');
34
+ const crypto = require('node:crypto');
35
+ const { adminPosterFor, extractProposal } = require('./memoryConsolidation.cjs');
36
+ const { OPS_ROOT_DIR } = require('../opsOwnership.cjs');
37
+
38
+ const PIPELINE = 'mitigation-review';
39
+ const MISSION_ID = 'mitigation-review';
40
+ const AGENT = 'dev-lead';
41
+ const NEEDS_YOU_APP = 'mitigation-review';
42
+ const REGISTRY_REL = path.join(OPS_ROOT_DIR, 'architecture', 'model-mitigations.md');
43
+ const STATE_FILE = 'mitigation-review.json';
44
+ const TICK_MS = 60 * 60 * 1000;
45
+ const FIRST_TICK_MS = 10 * 60 * 1000;
46
+ const NEEDS_YOU_WHY_MAX = 1000;
47
+ const PROPOSAL_START = '<<<PROPOSAL';
48
+ const PROPOSAL_END = 'PROPOSAL>>>';
49
+ const READ_ONLY_TOOLS = Object.freeze(['Read', 'Grep', 'Glob']);
50
+ const NO_EDIT_RULE = 'Do NOT delete, edit, move or create any file. You only propose; the human decides.';
51
+
52
+ /** cwd → true while a review for it is being started or is running. */
53
+ const inFlight = new Set();
54
+
55
+ const stripTicks = (s) => String(s || '').trim().replace(/^`+|`+$/g, '').trim();
56
+
57
+ /**
58
+ * Registry table rows (`| MM-<n> | behavior | model | observed | location | needle |`). Pure.
59
+ * @param {string} text
60
+ */
61
+ function parseRegistryRows(text) {
62
+ const rows = [];
63
+ for (const line of String(text || '').split('\n')) {
64
+ const t = line.trim();
65
+ if (!t.startsWith('|')) continue;
66
+ const cells = t.replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => c.trim());
67
+ if (cells.length < 6 || !/^MM-\d+$/.test(cells[0])) continue;
68
+ rows.push({
69
+ id: cells[0],
70
+ behavior: cells[1],
71
+ model: cells[2],
72
+ observed: cells[3],
73
+ location: stripTicks(cells[4]),
74
+ needle: stripTicks(cells[5]),
75
+ });
76
+ }
77
+ return rows;
78
+ }
79
+
80
+ /** Numeric version segments of `claude-<family>-N-M[-YYYYMMDD]` (date suffix dropped). */
81
+ function versionOf(id, family) {
82
+ return id.slice(`claude-${family}-`.length).split('-')
83
+ .filter((s) => /^\d+$/.test(s) && s.length < 8)
84
+ .map(Number);
85
+ }
86
+
87
+ /**
88
+ * An alias (`sonnet`) → the newest concrete id of that family in `ids`; a
89
+ * concrete id, or an alias with no match, is returned as-is. Pure.
90
+ * @param {string} model
91
+ * @param {string[]} ids
92
+ */
93
+ function concreteModelFor(model, ids) {
94
+ const m = String(model || '').trim();
95
+ if (!/^[a-z]+$/.test(m)) return m;
96
+ const prefix = `claude-${m}-`;
97
+ const list = (Array.isArray(ids) ? ids : []).filter((id) => typeof id === 'string' && id.startsWith(prefix));
98
+ if (!list.length) return m;
99
+ let best = list[0];
100
+ let bestV = versionOf(best, m);
101
+ for (const id of list.slice(1)) {
102
+ const v = versionOf(id, m);
103
+ let cmp = 0;
104
+ for (let i = 0; i < Math.max(v.length, bestV.length) && cmp === 0; i++) cmp = (v[i] ?? -1) - (bestV[i] ?? -1);
105
+ if (cmp > 0) { best = id; bestV = v; }
106
+ }
107
+ return best;
108
+ }
109
+
110
+ /**
111
+ * The review Task prompt. Pure.
112
+ * @param {{ cwd: string, from: string, to: string, rows: Array<ReturnType<typeof parseRegistryRows>[number]> }} o
113
+ */
114
+ function buildReviewPrompt({ cwd, from, to, rows }) {
115
+ const list = rows.map((r) => `- ${r.id} | behavior: ${r.behavior} | model: ${r.model} | observed: ${r.observed} | location: ${r.location} | needle: "${r.needle}"`).join('\n');
116
+ return [
117
+ `The default executor model of the project at ${cwd} changed from ${from} to ${to}. You are running on ${to}.`,
118
+ `Re-test every row of the model-mitigations registry (${REGISTRY_REL.split(path.sep).join('/')}) against this model.`,
119
+ '',
120
+ 'HARD RULES',
121
+ `1. ${NO_EDIT_RULE}`,
122
+ '2. Use only read tools (Read, Grep, Glob). Never run a shell command, never write.',
123
+ '3. Your whole answer is ONE table. It is posted as ONE "Needs you" item for the owner; do not split it.',
124
+ '',
125
+ `REGISTRY ROWS (${rows.length})`,
126
+ list,
127
+ '',
128
+ 'STEPS',
129
+ '1. For each row, read its location file and confirm the needle is still there.',
130
+ '2. Judge whether you, the model now running, would still show the recorded behavior without the rule',
131
+ ' (reason from the behavior and how the rule is used; be conservative — keep when unsure).',
132
+ '3. Pick one action per row: keep (still needed) or remove (no longer needed — rule and row retire together).',
133
+ '',
134
+ 'OUTPUT — exactly this, every row listed, nothing before or after:',
135
+ PROPOSAL_START,
136
+ '| Row | Action (keep/remove) | Why |',
137
+ '|---|---|---|',
138
+ '| MM-... | ... | ... |',
139
+ PROPOSAL_END,
140
+ ].join('\n');
141
+ }
142
+
143
+ function stateFile() {
144
+ return path.join(require('../scheduler/schedulerPaths.cjs').schedulerHome(), STATE_FILE);
145
+ }
146
+
147
+ function defaultDeps() {
148
+ return {
149
+ isTaskSwitchOn: (/** @type {string} */ cwd) => require('./taskSwitch.cjs').isTaskSwitchOn(cwd),
150
+ readRegistry: (/** @type {string} */ cwd) => {
151
+ try { return fs.readFileSync(path.join(cwd, REGISTRY_REL), 'utf8'); } catch { return null; }
152
+ },
153
+ resolveDefaultExecutorModel: async (/** @type {string} */ cwd) => {
154
+ const { readOverlayAwarePersonaModel, FALLBACK_MODEL } = require('../claude/agentModelResolve.cjs');
155
+ const { readSettingsModel, resolveModelCatalog } = require('../claude/modelCatalog.cjs');
156
+ let model = readOverlayAwarePersonaModel(AGENT, { cwd });
157
+ if (!model || model === 'inherit') model = readSettingsModel(cwd);
158
+ if (!model || model === 'inherit') model = FALLBACK_MODEL;
159
+ const catalog = await resolveModelCatalog({ cwd });
160
+ return concreteModelFor(model, catalog && catalog.models);
161
+ },
162
+ readState: () => require('../util/atomicFs.cjs').readJsonOrSync(stateFile(), {}),
163
+ writeState: (/** @type {any} */ s) => require('../util/atomicFs.cjs').writeJsonAtomicSync(stateFile(), s),
164
+ };
165
+ }
166
+
167
+ function cwdKey(cwd) {
168
+ return crypto.createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 16);
169
+ }
170
+
171
+ /**
172
+ * Decide and, on a model change, start one review Task for `cwd`.
173
+ * Resolves { started: false, reason } or { started: true, from, to, done }
174
+ * where `done` settles after the Task ran and its Needs you item was posted.
175
+ * Never throws.
176
+ * @param {{ cwd: string, now?: number, deps?: Record<string, any> }} o
177
+ */
178
+ async function maybeStartMitigationReview({ cwd, now = Date.now(), deps = {} } = /** @type {any} */ ({})) {
179
+ const d = { ...defaultDeps(), ...deps };
180
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return { started: false, reason: 'invalid_cwd' };
181
+ const key = path.resolve(cwd);
182
+ try {
183
+ if (!d.isTaskSwitchOn(key)) return { started: false, reason: 'switch_off' };
184
+ if (inFlight.has(key)) return { started: false, reason: 'in_flight' };
185
+ const registry = d.readRegistry(key);
186
+ if (typeof registry !== 'string') return { started: false, reason: 'no_registry' };
187
+ const to = await d.resolveDefaultExecutorModel(key);
188
+ if (typeof to !== 'string' || !to) return { started: false, reason: 'model_unresolved' };
189
+
190
+ const state = d.readState() || {};
191
+ const prev = state[key] && typeof state[key].model === 'string' ? state[key].model : null;
192
+ if (prev === to) return { started: false, reason: 'unchanged' };
193
+ if (prev != null && typeof d.adminPost !== 'function') return { started: false, reason: 'no_admin_server' };
194
+
195
+ d.writeState({ ...state, [key]: { model: to, seenAt: new Date(now).toISOString() } });
196
+ if (prev == null) return { started: false, reason: 'first_seen', to };
197
+
198
+ const rows = parseRegistryRows(registry);
199
+ if (!rows.length) return { started: false, reason: 'no_rows', from: prev, to };
200
+
201
+ const prompt = buildReviewPrompt({ cwd: key, from: prev, to, rows });
202
+ inFlight.add(key);
203
+ const done = runAndPost({ cwd: key, now, prompt, from: prev, to, adminPost: d.adminPost })
204
+ .catch((e) => ({ ok: false, error: e instanceof Error ? e.message : String(e) }))
205
+ .finally(() => { inFlight.delete(key); });
206
+ return { started: true, reason: 'model_changed', from: prev, to, done };
207
+ } catch (e) {
208
+ return { started: false, reason: 'error', error: e instanceof Error ? e.message : String(e) };
209
+ }
210
+ }
211
+
212
+ async function runAndPost({ cwd, now, prompt, from, to, adminPost }) {
213
+ const runId = `${new Date(now).toISOString().slice(0, 10)}-${cwdKey(cwd)}-${to}`;
214
+ const task = await adminPost('/admin/tasks', {
215
+ cwd,
216
+ agent: AGENT,
217
+ missionId: MISSION_ID,
218
+ prompt,
219
+ priority: 'batch',
220
+ timeoutSec: 1800,
221
+ slotWaitSec: 1800,
222
+ caller: { pipeline: PIPELINE, runId, step: 'model_changed' },
223
+ runtime: {
224
+ outputFormat: 'json',
225
+ tools: [...READ_ONLY_TOOLS],
226
+ allowedTools: [...READ_ONLY_TOOLS],
227
+ },
228
+ });
229
+ const b = task && task.body;
230
+ if (!task || task.status !== 200 || !b || b.ok !== true || b.status !== 'ok') {
231
+ return { ok: false, error: (b && (b.error || b.status)) || `http_${task && task.status}`, taskId: b && b.taskId };
232
+ }
233
+ const resultText = b.envelope && typeof b.envelope.result === 'string' ? b.envelope.result : '';
234
+ const proposal = extractProposal(resultText);
235
+ if (!proposal) return { ok: false, error: 'empty_proposal', taskId: b.taskId };
236
+
237
+ const note = `\n…(full table: Task ${b.taskId}, Scheduler → Tasks)`;
238
+ const why = proposal.length > NEEDS_YOU_WHY_MAX
239
+ ? proposal.slice(0, NEEDS_YOU_WHY_MAX - note.length) + note
240
+ : proposal;
241
+ const posted = await adminPost('/admin/needs-you', {
242
+ app: NEEDS_YOU_APP,
243
+ id: `mitigation-review:${runId}`,
244
+ title: `Model changed ${from} → ${to}: model mitigations to remove in ${path.basename(cwd)}`,
245
+ why,
246
+ cwd,
247
+ });
248
+ const ok = !!(posted && posted.status === 200 && posted.body && posted.body.ok);
249
+ return { ok, taskId: b.taskId, needsYou: ok ? posted.body.item : null, error: ok ? undefined : (posted && posted.body && posted.body.error) || 'needs_you_failed' };
250
+ }
251
+
252
+ /**
253
+ * Hourly sweep (first after 10 min) over every project with the switch on.
254
+ * index.cjs calls this once the admin server is up. Returns a stop function.
255
+ * @param {{ adminHttp: any, log?: (msg: string, meta?: any) => void, intervalMs?: number }} o
256
+ */
257
+ function startMitigationReviewTimer({ adminHttp, log = () => {}, intervalMs = TICK_MS }) {
258
+ const adminPost = adminPosterFor(adminHttp);
259
+ const tick = async () => {
260
+ let projects = [];
261
+ try { projects = require('./taskSwitch.cjs').listTaskProjects().filter((p) => p.enabled); } catch { projects = []; }
262
+ for (const p of projects) {
263
+ const r = await maybeStartMitigationReview({ cwd: p.cwd, now: Date.now(), deps: { adminPost } });
264
+ if (r.started) {
265
+ log('mitigation review started', { cwd: p.cwd, from: r.from, to: r.to });
266
+ r.done.then((out) => log('mitigation review finished', { cwd: p.cwd, ...out }));
267
+ } else if (r.reason === 'error') {
268
+ log('mitigation review check failed', { cwd: p.cwd, error: r.error });
269
+ }
270
+ }
271
+ };
272
+ const safeTick = () => { tick().catch(() => {}); };
273
+ const first = setTimeout(safeTick, FIRST_TICK_MS);
274
+ const every = setInterval(safeTick, intervalMs);
275
+ if (typeof first.unref === 'function') first.unref();
276
+ if (typeof every.unref === 'function') every.unref();
277
+ return () => { clearTimeout(first); clearInterval(every); };
278
+ }
279
+
280
+ function _resetForTests() {
281
+ inFlight.clear();
282
+ }
283
+
284
+ module.exports = {
285
+ parseRegistryRows,
286
+ concreteModelFor,
287
+ buildReviewPrompt,
288
+ maybeStartMitigationReview,
289
+ startMitigationReviewTimer,
290
+ PIPELINE,
291
+ REGISTRY_REL,
292
+ READ_ONLY_TOOLS,
293
+ _resetForTests,
294
+ };