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
@@ -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
+ };