claude-code-session-manager 0.138.0 → 0.140.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +352 -79
  3. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  4. package/dist/assets/History--JwsFnbn.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
  6. package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
  8. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  10. package/dist/assets/Skills-DtRzghn5.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
  12. package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
  15. package/dist/assets/index-CtxruO1L.js +3121 -0
  16. package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +467 -451
  20. package/package.json +17 -6
  21. package/plugins/AGENTS.md +60 -0
  22. package/plugins/CLAUDE.md +1 -60
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  25. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  26. package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  36. package/scripts/README.md +2 -0
  37. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  38. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  39. package/scripts/ops-sweep.cjs +53 -23
  40. package/scripts/scheduler-mcp-server.cjs +360 -35
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +2 -2
  43. package/src/main/config.cjs +112 -8
  44. package/src/main/docEdit.cjs +6 -1
  45. package/src/main/exchanges.cjs +70 -5
  46. package/src/main/files.cjs +7 -27
  47. package/src/main/health.cjs +48 -15
  48. package/src/main/historyAggregator.cjs +172 -63
  49. package/src/main/historyDashboard.cjs +87 -17
  50. package/src/main/index.cjs +78 -4
  51. package/src/main/ipcSchemas.cjs +233 -20
  52. package/src/main/lib/AGENTS.md +54 -0
  53. package/src/main/lib/CLAUDE.md +1 -54
  54. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  55. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  56. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  57. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  58. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  59. package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
  60. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  61. package/src/main/lib/claude/modelPricing.cjs +148 -0
  62. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  63. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  64. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  65. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  66. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  67. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  68. package/src/main/lib/ephemeralCwd.cjs +37 -2
  69. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  70. package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
  71. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  72. package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
  73. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  74. package/src/main/lib/epic/epicSettle.cjs +1 -1
  75. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  76. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  77. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  78. package/src/main/lib/epic/externalRef.cjs +37 -0
  79. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  80. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  81. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  82. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  83. package/src/main/lib/externalContract.cjs +137 -0
  84. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  90. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  91. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  92. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
  93. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  94. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  95. package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
  96. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  97. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  98. package/src/main/lib/git/branchSweep.cjs +209 -4
  99. package/src/main/lib/git/gitWorktree.cjs +41 -5
  100. package/src/main/lib/guardShims.cjs +1 -1
  101. package/src/main/lib/historyRollup.cjs +58 -5
  102. package/src/main/lib/insideHome.cjs +27 -1
  103. package/src/main/lib/mcpToolCatalog.cjs +232 -25
  104. package/src/main/lib/mdDocCensus.cjs +59 -78
  105. package/src/main/lib/mdDocRefs.cjs +71 -93
  106. package/src/main/lib/mdNetworkScan.cjs +245 -250
  107. package/src/main/lib/mdReviewRecord.cjs +22 -9
  108. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  109. package/src/main/lib/opsOwnership.cjs +18 -2
  110. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  111. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  112. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  113. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  114. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  115. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  116. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  117. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  118. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  119. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  120. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  121. package/src/main/lib/prd/prdCreate.cjs +351 -23
  122. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  123. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  124. package/src/main/lib/process/loginItem.cjs +171 -0
  125. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  126. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  127. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  128. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  129. package/src/main/lib/promptSessionSchema.cjs +4 -0
  130. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  131. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  132. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  133. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  134. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  135. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  136. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  137. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  138. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  139. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  140. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  141. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  142. package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
  143. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  144. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  145. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  146. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  147. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  148. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  149. package/src/main/lib/tasks/taskRun.cjs +313 -0
  150. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  151. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  152. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  153. package/src/main/loginItemIpc.cjs +35 -0
  154. package/src/main/loopEfficiencyHandlers.cjs +11 -2
  155. package/src/main/projectPages.cjs +6 -15
  156. package/src/main/promptSessionEvents.cjs +9 -1
  157. package/src/main/queueOps.cjs +260 -3
  158. package/src/main/runVerify.cjs +53 -25
  159. package/src/main/scheduler/AGENTS.md +26 -0
  160. package/src/main/scheduler/CLAUDE.md +1 -26
  161. package/src/main/scheduler/budget.cjs +239 -9
  162. package/src/main/scheduler/cancelDependents.cjs +154 -0
  163. package/src/main/scheduler/prdParser.cjs +4 -1
  164. package/src/main/scheduler/starvation.cjs +20 -18
  165. package/src/main/scheduler.cjs +774 -64
  166. package/src/main/supervisor.cjs +5 -1
  167. package/src/main/templates/PRD_AUTHORING.md +7 -1
  168. package/src/main/transcripts.cjs +62 -7
  169. package/src/main/validationQualityHandlers.cjs +199 -0
  170. package/src/main/webRemote.cjs +132 -20
  171. package/src/preload/api.d.ts +434 -28
  172. package/src/preload/apiSurface.cjs +7 -0
  173. package/src/preload/apiSurface.json +485 -81
  174. package/src/preload/index.cjs +38 -5
  175. package/src/seed/agents/validator.md +19 -8
  176. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  177. package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
  178. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  179. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  180. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  181. package/dist/assets/History-BwO3coo4.js +0 -2
  182. package/dist/assets/Library-BDV69fSe.js +0 -32
  183. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  184. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  185. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  186. package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
  187. package/dist/assets/Settings-COT34hBF.js +0 -2
  188. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  189. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  190. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  191. package/dist/assets/Toggle-CENi19iK.js +0 -1
  192. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  193. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  194. package/dist/assets/index-CgCxpunJ.js +0 -3116
@@ -0,0 +1,373 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * toolRiskMarks.cjs — the one module that reads, validates, writes and
5
+ * matches per-tool risk marks kept in the Claude config layers:
6
+ *
7
+ * System = ~/.claude/tool-risk.json
8
+ * Project = <projectRoot>/.claude/tool-risk.json (main checkout, never a worktree)
9
+ *
10
+ * File format, version 1 (pinned):
11
+ * { "version": 1, "interactive"?: boolean, "marks": { "<rule>": "<mark>" } }
12
+ *
13
+ * A rule is an MCP tool name (`mcp__srv__tool`), a server wildcard
14
+ * (`mcp__srv__*`), a Bash prefix (`Bash(npm publish:*)`) or an exact Bash
15
+ * command (`Bash(git push --force)`). A call is the PreToolUse shape
16
+ * `{ tool, input? }`; for Bash, `input.command` is the command line.
17
+ *
18
+ * Precedence: layer first (any matching Project rule beats every System rule),
19
+ * then specificity inside the layer (MCP exact > server wildcard; Bash exact >
20
+ * longer prefix > shorter prefix). A compound Bash command resolves each
21
+ * simple command and returns a blocking result if any one blocks.
22
+ *
23
+ * Pure apart from readMarksLayer / writeMarksLayer. No side effects at
24
+ * require time. readMarksLayer and resolveMark never throw.
25
+ *
26
+ * The Bash splitter/tokenizer copies the approach of
27
+ * scripts/hooks/lib/guard-destructive-git-policy.cjs (src/main never
28
+ * requires from scripts/).
29
+ */
30
+
31
+ const fs = require('node:fs');
32
+ const path = require('node:path');
33
+ const { writeJsonAtomic, readJsonOrSync } = require('../util/atomicFs.cjs');
34
+
35
+ const MARKS = Object.freeze(['read', 'write', 'irreversible', 'money', 'public']);
36
+ const BLOCKING_MARKS = new Set(['irreversible', 'money', 'public']);
37
+ const MARK_SET = new Set(MARKS);
38
+
39
+ const FILE_NAME = 'tool-risk.json';
40
+ const FORMAT_VERSION = 1;
41
+ const TOP_LEVEL_KEYS = new Set(['version', 'interactive', 'marks']);
42
+
43
+ const NAME_RE = /^[A-Za-z0-9_.-]+$/;
44
+ const ENV_ASSIGN_RE = /^[A-Za-z_][A-Za-z0-9_]*=/;
45
+ const WRAPPERS = new Set(['env', 'sudo', 'command', 'exec', 'nohup', 'time']);
46
+ // sudo flags that consume the next word as their argument.
47
+ const SUDO_ARG_FLAGS = new Set(['-u', '-g', '-C', '-D', '-h', '-p', '-r', '-t', '-U', '-R', '-T']);
48
+ const SHELLS = new Set(['bash', 'sh']);
49
+
50
+ function systemMarksPath(homeDir) {
51
+ return path.join(homeDir, '.claude', FILE_NAME);
52
+ }
53
+
54
+ function projectMarksPath(projectRoot) {
55
+ return path.join(projectRoot, '.claude', FILE_NAME);
56
+ }
57
+
58
+ function isPlainObject(v) {
59
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
60
+ }
61
+
62
+ // ── Bash parsing ────────────────────────────────────────────────────────────
63
+
64
+ /** Quote-aware split on top-level `&&`, `||`, `;`, `|`, and newlines. */
65
+ function splitTopLevel(cmd) {
66
+ const parts = [];
67
+ let cur = '';
68
+ let inSingle = false;
69
+ let inDouble = false;
70
+ for (let i = 0; i < cmd.length; i++) {
71
+ const c = cmd[i];
72
+ if (inSingle) {
73
+ cur += c;
74
+ if (c === "'") inSingle = false;
75
+ continue;
76
+ }
77
+ if (inDouble) {
78
+ cur += c;
79
+ if (c === '"' && cmd[i - 1] !== '\\') inDouble = false;
80
+ continue;
81
+ }
82
+ if (c === "'") { inSingle = true; cur += c; continue; }
83
+ if (c === '"') { inDouble = true; cur += c; continue; }
84
+ const two = cmd.slice(i, i + 2);
85
+ if (two === '&&' || two === '||') { parts.push(cur); cur = ''; i++; continue; }
86
+ if (c === ';' || c === '|' || c === '\n') { parts.push(cur); cur = ''; continue; }
87
+ cur += c;
88
+ }
89
+ parts.push(cur);
90
+ return parts.map((s) => s.trim()).filter(Boolean);
91
+ }
92
+
93
+ /** Quote-aware whitespace tokenizer. Returns null on an unterminated quote. */
94
+ function tokenize(str) {
95
+ const tokens = [];
96
+ let cur = '';
97
+ let started = false;
98
+ let inSingle = false;
99
+ let inDouble = false;
100
+ for (let i = 0; i < str.length; i++) {
101
+ const c = str[i];
102
+ if (inSingle) {
103
+ if (c === "'") inSingle = false; else cur += c;
104
+ started = true;
105
+ continue;
106
+ }
107
+ if (inDouble) {
108
+ if (c === '"') inDouble = false; else cur += c;
109
+ started = true;
110
+ continue;
111
+ }
112
+ if (c === "'") { inSingle = true; started = true; continue; }
113
+ if (c === '"') { inDouble = true; started = true; continue; }
114
+ if (/\s/.test(c)) {
115
+ if (started) { tokens.push(cur); cur = ''; started = false; }
116
+ continue;
117
+ }
118
+ cur += c;
119
+ started = true;
120
+ }
121
+ if (started) tokens.push(cur);
122
+ if (inSingle || inDouble) return null;
123
+ return tokens;
124
+ }
125
+
126
+ /** Drop leading VAR=value words and env/sudo/command/exec/nohup/time wrappers. */
127
+ function stripPrefixes(tokens) {
128
+ let i = 0;
129
+ for (;;) {
130
+ while (i < tokens.length && ENV_ASSIGN_RE.test(tokens[i])) i++;
131
+ if (i >= tokens.length || !WRAPPERS.has(tokens[i])) break;
132
+ const wrapper = tokens[i++];
133
+ while (i < tokens.length && tokens[i].startsWith('-') && tokens[i] !== '--') {
134
+ const flag = tokens[i++];
135
+ if (wrapper === 'sudo' && SUDO_ARG_FLAGS.has(flag)) i++;
136
+ }
137
+ if (tokens[i] === '--') i++;
138
+ }
139
+ return tokens.slice(i);
140
+ }
141
+
142
+ /** Index of the `-c` script argument for `bash -c '<cmd>'` / `sh -lc '<cmd>'`, or -1. */
143
+ function shellScriptIndex(tokens) {
144
+ if (!SHELLS.has(tokens[0])) return -1;
145
+ for (let i = 1; i < tokens.length; i++) {
146
+ const t = tokens[i];
147
+ if (!t.startsWith('-') || t.startsWith('--')) return -1;
148
+ if (t.slice(1).includes('c')) return i + 1 < tokens.length ? i + 1 : -1;
149
+ }
150
+ return -1;
151
+ }
152
+
153
+ /**
154
+ * Split a command line into simple commands (token arrays), unwrapping one
155
+ * level of `bash -c` / `sh -c`. A wrapper's outer form is kept too, so a rule
156
+ * on `bash` itself still matches.
157
+ */
158
+ function simpleCommands(command, depth = 0) {
159
+ const out = [];
160
+ for (const part of splitTopLevel(command)) {
161
+ const raw = tokenize(part);
162
+ if (!raw) continue;
163
+ const tokens = stripPrefixes(raw);
164
+ if (tokens.length === 0) continue;
165
+ out.push(tokens);
166
+ if (depth === 0) {
167
+ const idx = shellScriptIndex(tokens);
168
+ if (idx !== -1) out.push(...simpleCommands(tokens[idx], depth + 1));
169
+ }
170
+ }
171
+ return out;
172
+ }
173
+
174
+ // ── Rules ───────────────────────────────────────────────────────────────────
175
+
176
+ /**
177
+ * @returns {{kind:'mcp', server:string, tool:string|null}
178
+ * | {kind:'bash', prefix:string[], exact:boolean} | null}
179
+ */
180
+ function parseRule(rule) {
181
+ if (typeof rule !== 'string') return null;
182
+ if (rule.trim() === '' || /[\r\n]/.test(rule)) return null;
183
+ if (rule.startsWith('mcp__')) {
184
+ const rest = rule.slice(5);
185
+ const sep = rest.indexOf('__');
186
+ const server = sep === -1 ? rest : rest.slice(0, sep);
187
+ if (!server || !NAME_RE.test(server)) return null;
188
+ if (sep === -1) return { kind: 'mcp', server, tool: null };
189
+ const tool = rest.slice(sep + 2);
190
+ if (tool === '*') return { kind: 'mcp', server, tool: null };
191
+ if (!tool || !NAME_RE.test(tool)) return null;
192
+ return { kind: 'mcp', server, tool };
193
+ }
194
+ const m = /^Bash\((.*)\)$/.exec(rule);
195
+ if (!m) return null;
196
+ let inner = m[1];
197
+ let exact = true;
198
+ if (inner.endsWith(':*')) { inner = inner.slice(0, -2); exact = false; }
199
+ const prefix = tokenize(inner);
200
+ if (!prefix || prefix.length === 0) return null;
201
+ return { kind: 'bash', prefix, exact };
202
+ }
203
+
204
+ function toParsed(rule) {
205
+ if (isPlainObject(rule) && (rule.kind === 'mcp' || rule.kind === 'bash')) return rule;
206
+ return parseRule(rule);
207
+ }
208
+
209
+ function tokensMatch(parsed, tokens) {
210
+ if (parsed.exact && tokens.length !== parsed.prefix.length) return false;
211
+ if (tokens.length < parsed.prefix.length) return false;
212
+ for (let i = 0; i < parsed.prefix.length; i++) {
213
+ if (tokens[i] !== parsed.prefix[i]) return false;
214
+ }
215
+ return true;
216
+ }
217
+
218
+ function mcpMatches(parsed, toolName) {
219
+ if (typeof toolName !== 'string') return false;
220
+ if (parsed.tool === null) return toolName.startsWith(`mcp__${parsed.server}__`);
221
+ return toolName === `mcp__${parsed.server}__${parsed.tool}`;
222
+ }
223
+
224
+ function bashCommandOf(call) {
225
+ if (!call || call.tool !== 'Bash' || !isPlainObject(call.input)) return null;
226
+ return typeof call.input.command === 'string' ? call.input.command : null;
227
+ }
228
+
229
+ /** Does `rule` (string or parseRule result) match `call`? Never throws. */
230
+ function ruleMatches(rule, call) {
231
+ try {
232
+ const parsed = toParsed(rule);
233
+ if (!parsed || !call) return false;
234
+ if (parsed.kind === 'mcp') return mcpMatches(parsed, call.tool);
235
+ const command = bashCommandOf(call);
236
+ if (command === null) return false;
237
+ return simpleCommands(command).some((tokens) => tokensMatch(parsed, tokens));
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ /** Higher = more specific. */
244
+ function specificity(parsed) {
245
+ if (parsed.kind === 'mcp') return parsed.tool === null ? 1 : 2;
246
+ return (parsed.exact ? 1e6 : 0) + parsed.prefix.length;
247
+ }
248
+
249
+ // ── Validation + fs ─────────────────────────────────────────────────────────
250
+
251
+ /** @returns {{ok:true} | {ok:false, error:string}} */
252
+ function validateMarksFile(obj) {
253
+ if (!isPlainObject(obj)) return { ok: false, error: 'tool-risk file must be a JSON object' };
254
+ for (const key of Object.keys(obj)) {
255
+ if (!TOP_LEVEL_KEYS.has(key)) return { ok: false, error: `unknown top-level key "${key}"` };
256
+ }
257
+ if (obj.version !== FORMAT_VERSION) {
258
+ return { ok: false, error: `"version" must be ${FORMAT_VERSION} (got ${JSON.stringify(obj.version)})` };
259
+ }
260
+ if (obj.interactive !== undefined && typeof obj.interactive !== 'boolean') {
261
+ return { ok: false, error: '"interactive" must be a boolean' };
262
+ }
263
+ if (!isPlainObject(obj.marks)) return { ok: false, error: '"marks" must be an object' };
264
+ for (const [rule, mark] of Object.entries(obj.marks)) {
265
+ if (!parseRule(rule)) return { ok: false, error: `marks key "${rule}" is not a valid rule (use mcp__server__tool, mcp__server__*, Bash(prefix:*) or Bash(exact))` };
266
+ if (!MARK_SET.has(mark)) return { ok: false, error: `marks key "${rule}" has unknown mark ${JSON.stringify(mark)} (expected one of ${MARKS.join(', ')})` };
267
+ }
268
+ return { ok: true };
269
+ }
270
+
271
+ const UNPARSEABLE = Object.freeze({});
272
+
273
+ /** Read one layer. Never throws. */
274
+ function readMarksLayer(file) {
275
+ try {
276
+ if (typeof file !== 'string' || file === '') {
277
+ return { ok: false, exists: false, error: 'no tool-risk file path given', file: file ?? null };
278
+ }
279
+ if (!fs.existsSync(file)) return { ok: true, exists: false, marks: {}, interactive: false, file };
280
+ const obj = readJsonOrSync(file, UNPARSEABLE);
281
+ if (obj === UNPARSEABLE) return { ok: false, exists: true, error: `${file}: unreadable or not valid JSON`, file };
282
+ const v = validateMarksFile(obj);
283
+ if (!v.ok) return { ok: false, exists: true, error: `${file}: ${v.error}`, file };
284
+ return { ok: true, exists: true, marks: { ...obj.marks }, interactive: obj.interactive === true, file };
285
+ } catch (e) {
286
+ return { ok: false, exists: true, error: `${file}: ${e && e.message ? e.message : String(e)}`, file };
287
+ }
288
+ }
289
+
290
+ /** Validate, then write atomically. @returns {Promise<{ok:true}|{ok:false,error:string}>} */
291
+ async function writeMarksLayer(file, obj) {
292
+ const v = validateMarksFile(obj);
293
+ if (!v.ok) return v;
294
+ const out = { version: FORMAT_VERSION };
295
+ if (obj.interactive !== undefined) out.interactive = obj.interactive;
296
+ out.marks = { ...obj.marks };
297
+ await writeJsonAtomic(file, out);
298
+ return { ok: true };
299
+ }
300
+
301
+ // ── Resolution ──────────────────────────────────────────────────────────────
302
+
303
+ function layerEntries(layerObj) {
304
+ if (!layerObj || layerObj.ok === false || !isPlainObject(layerObj.marks)) return [];
305
+ const out = [];
306
+ for (const [rule, mark] of Object.entries(layerObj.marks)) {
307
+ const parsed = parseRule(rule);
308
+ if (parsed && MARK_SET.has(mark)) out.push({ rule, mark, parsed });
309
+ }
310
+ return out;
311
+ }
312
+
313
+ /** Best match in one layer for a predicate over parsed rules. */
314
+ function bestInLayer(entries, matches) {
315
+ let best = null;
316
+ let bestScore = -1;
317
+ for (const e of entries) {
318
+ if (!matches(e.parsed)) continue;
319
+ const s = specificity(e.parsed);
320
+ if (s > bestScore) { best = e; bestScore = s; }
321
+ }
322
+ return best;
323
+ }
324
+
325
+ function resolveUnit(layers, matches) {
326
+ for (const { name, obj, entries } of layers) {
327
+ const hit = bestInLayer(entries, matches);
328
+ if (hit) return { mark: hit.mark, rule: hit.rule, layer: name, file: (obj && obj.file) || null };
329
+ }
330
+ return null;
331
+ }
332
+
333
+ /**
334
+ * @returns {{mark:string, rule:string, layer:'project'|'system', file:string|null} | null}
335
+ * Never throws.
336
+ */
337
+ function resolveMark(call, layersIn) {
338
+ try {
339
+ const { system, project } = layersIn || {};
340
+ if (!call || typeof call.tool !== 'string') return null;
341
+ const layers = [
342
+ { name: 'project', obj: project, entries: layerEntries(project) },
343
+ { name: 'system', obj: system, entries: layerEntries(system) },
344
+ ];
345
+ if (call.tool !== 'Bash') {
346
+ return resolveUnit(layers, (p) => p.kind === 'mcp' && mcpMatches(p, call.tool));
347
+ }
348
+ const command = bashCommandOf(call);
349
+ if (command === null) return null;
350
+ let result = null;
351
+ for (const tokens of simpleCommands(command)) {
352
+ const r = resolveUnit(layers, (p) => p.kind === 'bash' && tokensMatch(p, tokens));
353
+ if (!r) continue;
354
+ if (!result || MARKS.indexOf(r.mark) > MARKS.indexOf(result.mark)) result = r;
355
+ }
356
+ return result;
357
+ } catch {
358
+ return null;
359
+ }
360
+ }
361
+
362
+ module.exports = {
363
+ MARKS,
364
+ BLOCKING_MARKS,
365
+ systemMarksPath,
366
+ projectMarksPath,
367
+ parseRule,
368
+ ruleMatches,
369
+ readMarksLayer,
370
+ validateMarksFile,
371
+ writeMarksLayer,
372
+ resolveMark,
373
+ };
@@ -7,20 +7,40 @@
7
7
  * with every npx hash dir). A `KIT_VERSION` stamp file records which kit
8
8
  * version is installed; files are overwritten only when the stamp differs, so
9
9
  * a normal boot is one small read. Bump KIT_VERSION whenever any kit file
10
- * changes behaviour.
10
+ * changes. KIT_DIGEST pins the kit files' bytes; seedKit.test.cjs fails when
11
+ * the digest drifts, so a kit edit cannot ship without a bump.
11
12
  *
12
13
  * Fire-and-forget from index.cjs: errors are logged, never thrown.
13
14
  * Kill-switch: SM_SEED_DEMO_VIDEO_KIT_DISABLE=1.
14
15
  */
15
16
  const fs = require('node:fs');
17
+ const crypto = require('node:crypto');
16
18
  const path = require('node:path');
17
19
  const { schedulerHome } = require('../scheduler/schedulerPaths.cjs');
18
20
  const { writeTextAtomic } = require('../util/atomicFs.cjs');
19
21
 
20
- const KIT_VERSION = '2';
21
- const KIT_FILES = ['checks.cjs', 'sound.cjs', 'capture.cjs', 'frames.cjs', 'character.cjs', 'playwrightLoader.cjs'];
22
+ const KIT_VERSION = '3';
23
+ // sha256 of kitDigest(__dirname). Update together with a KIT_VERSION bump.
24
+ const KIT_DIGEST = 'b3bb70c8984d8b794a20a68d36c22e2f7fe97cdfad8215f5ae7294c47388571c';
25
+ const KIT_FILES = Object.freeze(['checks.cjs', 'sound.cjs', 'capture.cjs', 'frames.cjs', 'character.cjs', 'playwrightLoader.cjs']);
22
26
  const STAMP_FILE = 'KIT_VERSION';
23
27
 
28
+ /** The single list of kit files (paths relative to the kit dir) the seeder copies. */
29
+ function kitFiles() {
30
+ return [...KIT_FILES];
31
+ }
32
+
33
+ /** Pure: sha256 hex over kitFiles() sorted by relative path, each as path + NUL + bytes. */
34
+ function kitDigest(srcDir) {
35
+ const h = crypto.createHash('sha256');
36
+ for (const f of kitFiles().sort()) {
37
+ h.update(f);
38
+ h.update(Buffer.from([0]));
39
+ h.update(fs.readFileSync(path.join(srcDir, f)));
40
+ }
41
+ return h.digest('hex');
42
+ }
43
+
24
44
  function kitDestDir() {
25
45
  return path.join(schedulerHome(), 'demo-video-kit');
26
46
  }
@@ -31,11 +51,12 @@ async function seedDemoVideoKit({ logger = console, writeLog = () => {}, destDir
31
51
  const stampPath = path.join(destDir, STAMP_FILE);
32
52
  let installed = null;
33
53
  try { installed = fs.readFileSync(stampPath, 'utf8').trim(); } catch { /* no stamp yet */ }
34
- const filesPresent = KIT_FILES.every((f) => fs.existsSync(path.join(destDir, f)));
54
+ const files = kitFiles();
55
+ const filesPresent = files.every((f) => fs.existsSync(path.join(destDir, f)));
35
56
  if (installed === String(kitVersion) && filesPresent) return { seeded: false, reason: 'current' };
36
57
 
37
58
  fs.mkdirSync(destDir, { recursive: true });
38
- for (const f of KIT_FILES) {
59
+ for (const f of files) {
39
60
  await writeTextAtomic(path.join(destDir, f), fs.readFileSync(path.join(srcDir, f), 'utf8'));
40
61
  }
41
62
  // Stamp last: a crash mid-copy leaves the old/no stamp, so the next boot retries.
@@ -49,4 +70,4 @@ async function seedDemoVideoKit({ logger = console, writeLog = () => {}, destDir
49
70
  }
50
71
  }
51
72
 
52
- module.exports = { seedDemoVideoKit, kitDestDir, KIT_VERSION, KIT_FILES };
73
+ module.exports = { seedDemoVideoKit, kitDestDir, kitFiles, kitDigest, KIT_VERSION, KIT_DIGEST, KIT_FILES };
@@ -28,6 +28,13 @@
28
28
  * (cwd) resolves back to cwd unchanged, which is not a redirect and must
29
29
  * not be refused.)
30
30
  *
31
+ * Plus one for a MISSING cwd: a path that does not exist and lies lexically
32
+ * inside os.tmpdir() (resolved or realpath'd) is ephemeral. Verified live
33
+ * 2026-11-22: a reconcile pass recreated queue.json inside
34
+ * /tmp/sm-sbx-probe-LrKw/work, deleted half an hour earlier and remembered
35
+ * only as a ~/.claude/projects transcript dir — classifyCwd cannot inspect a
36
+ * path that is gone, so it looked like an ordinary project.
37
+ *
31
38
  * Deliberately NOT a blanket "anywhere under os.tmpdir()" prefix match: this
32
39
  * codebase's own scheduler test suite routinely mkdtemp()s a fake project cwd
33
40
  * under os.tmpdir() (documented convention — see e.g.
@@ -35,6 +42,8 @@
35
42
  * unrelated use that a blanket match would wrongly refuse.
36
43
  */
37
44
 
45
+ const fs = require('node:fs');
46
+ const os = require('node:os');
38
47
  const path = require('node:path');
39
48
  const { classifyCwd } = require('./cwdClassify.cjs');
40
49
 
@@ -48,9 +57,35 @@ const { classifyCwd } = require('./cwdClassify.cjs');
48
57
  * opsOwnership.assertOpsWrite refuses separately (writes only — dispatch and
49
58
  * reads stay open).
50
59
  */
51
- function isEphemeralCwd(cwd) {
60
+ function isInside(child, parent) {
61
+ const rel = path.relative(parent, child);
62
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
63
+ }
64
+
65
+ function tmpRoots() {
66
+ const roots = [path.resolve(os.tmpdir())];
67
+ try { roots.push(fs.realpathSync(os.tmpdir())); } catch { /* tmpdir unresolvable — lexical root only */ }
68
+ return roots;
69
+ }
70
+
71
+ /**
72
+ * `refuseMissingInTmp` (default true) applies the MISSING-under-tmpdir rule.
73
+ * opsOwnership.resolveProjectRoot passes false: it is a path resolver shared
74
+ * by readers (fix-plan flat-dir fallback, drill-down transcript lookups) and
75
+ * by callers that run their own existence check first (delegationReadiness's
76
+ * "does not exist on disk"); refusing there broke them all (7071526a). The
77
+ * writers that must never recreate a deleted tmp cwd call this predicate
78
+ * directly (opsErrorLog) or check existence themselves (queueStore.writeSplit).
79
+ */
80
+ function isEphemeralCwd(cwd, { refuseMissingInTmp = true } = {}) {
52
81
  if (!cwd || typeof cwd !== 'string' || !path.isAbsolute(cwd)) return false;
53
- const { kind } = classifyCwd(path.resolve(cwd));
82
+ const abs = path.resolve(cwd);
83
+ if (refuseMissingInTmp) {
84
+ let exists = true;
85
+ try { exists = fs.existsSync(abs); } catch { exists = true; }
86
+ if (!exists && tmpRoots().some((root) => isInside(abs, root))) return true;
87
+ }
88
+ const { kind } = classifyCwd(abs);
54
89
  return kind === 'ephemeral' || kind === 'worktree';
55
90
  }
56
91
 
@@ -325,6 +325,23 @@ function readDevMarketplacePath(homeDir) {
325
325
  return typeof p === 'string' && p ? p : null;
326
326
  }
327
327
 
328
+ const DEV_PLUGIN_NAME = 'session-manager-dev';
329
+
330
+ /**
331
+ * Folder Claude Code actually loads the dev plugin from: the 'session-manager-dev'
332
+ * entry's source in <marketplacePath>/.claude-plugin/marketplace.json, resolved
333
+ * against marketplacePath. Null when the manifest is missing/malformed or the
334
+ * entry has no non-empty string source.
335
+ */
336
+ function readDevPluginSourceDir(marketplacePath) {
337
+ const manifest = readJsonOrSync(path.join(marketplacePath, '.claude-plugin', 'marketplace.json'), null);
338
+ const plugins = Array.isArray(manifest?.plugins) ? manifest.plugins : [];
339
+ const entry = plugins.find((p) => p && p.name === DEV_PLUGIN_NAME);
340
+ return entry && typeof entry.source === 'string' && entry.source
341
+ ? path.resolve(marketplacePath, entry.source)
342
+ : null;
343
+ }
344
+
328
345
  function checkDevPlugin({ homeDir }) {
329
346
  const settings = readJsonOrSync(path.join(homeDir, '.claude', 'settings.json'), null);
330
347
  const enabled = settings?.enabledPlugins?.[DEV_PLUGIN_ENABLED_KEY] === true;
@@ -348,30 +365,44 @@ function checkDevPlugin({ homeDir }) {
348
365
  fix: DEV_PLUGIN_REINSTALL_FIX,
349
366
  };
350
367
  }
351
- const skillFile = path.join(installPath, 'skills', 'develop', 'SKILL.md');
352
- if (!fs.existsSync(skillFile)) {
368
+
369
+ const marketplacePath = readDevMarketplacePath(homeDir);
370
+ if (!marketplacePath) {
371
+ return {
372
+ ...base,
373
+ ok: false,
374
+ detail: `'${DEV_PLUGIN_MARKETPLACE}' marketplace not registered in ~/.claude/plugins/known_marketplaces.json`,
375
+ fix: DEV_PLUGIN_REINSTALL_FIX,
376
+ };
377
+ }
378
+ if (!fs.existsSync(marketplacePath)) {
353
379
  return {
354
380
  ...base,
355
381
  ok: false,
356
- detail: `${DEV_PLUGIN_ENABLED_KEY} enabled but ${skillFile} is missing`,
382
+ detail: `'${DEV_PLUGIN_MARKETPLACE}' marketplace folder ${marketplacePath} no longer exists`,
357
383
  fix: DEV_PLUGIN_REINSTALL_FIX,
358
384
  };
359
385
  }
360
386
 
361
- const marketplacePath = readDevMarketplacePath(homeDir);
362
- if (!marketplacePath) {
387
+ // The install record's installPath (a ~/.claude/plugins/cache/ snapshot) is
388
+ // never read by Claude Code for a directory marketplace — it loads the
389
+ // plugin in place from the manifest's source folder, so check THAT copy.
390
+ const manifestFile = path.join(marketplacePath, '.claude-plugin', 'marketplace.json');
391
+ const sourceDir = readDevPluginSourceDir(marketplacePath);
392
+ if (!sourceDir) {
363
393
  return {
364
394
  ...base,
365
395
  ok: false,
366
- detail: `'${DEV_PLUGIN_MARKETPLACE}' marketplace not registered in ~/.claude/plugins/known_marketplaces.json`,
396
+ detail: `${manifestFile} is missing, malformed, or has no '${DEV_PLUGIN_NAME}' entry with a string source`,
367
397
  fix: DEV_PLUGIN_REINSTALL_FIX,
368
398
  };
369
399
  }
370
- if (!fs.existsSync(marketplacePath)) {
400
+ const skillFile = path.join(sourceDir, 'skills', 'develop', 'SKILL.md');
401
+ if (!fs.existsSync(skillFile)) {
371
402
  return {
372
403
  ...base,
373
404
  ok: false,
374
- detail: `'${DEV_PLUGIN_MARKETPLACE}' marketplace folder ${marketplacePath} no longer exists`,
405
+ detail: `${DEV_PLUGIN_ENABLED_KEY} enabled but ${skillFile} (the copy sessions load) is missing`,
375
406
  fix: DEV_PLUGIN_REINSTALL_FIX,
376
407
  };
377
408
  }
@@ -379,7 +410,7 @@ function checkDevPlugin({ homeDir }) {
379
410
  return {
380
411
  ...base,
381
412
  ok: true,
382
- detail: `${DEV_PLUGIN_ENABLED_KEY} enabled in ~/.claude/settings.json and installed on disk`,
413
+ detail: `${DEV_PLUGIN_ENABLED_KEY} enabled; sessions load it from ${sourceDir}`,
383
414
  fix: null,
384
415
  };
385
416
  }
@@ -862,6 +893,7 @@ async function ensureGuardsInstalled(cwd, { homeDir = os.homedir() } = {}) {
862
893
 
863
894
  module.exports = {
864
895
  checkDevPlugin,
896
+ DEV_PLUGIN_REINSTALL_FIX,
865
897
  checkDelegationReadiness,
866
898
  ensureGuardsInstalled,
867
899
  logAutoInstallEvent,
@@ -882,4 +914,5 @@ module.exports = {
882
914
  SELF_SCHEDULE_GUARD_MATCHER,
883
915
  GUARD_DEFS,
884
916
  checkGuard,
917
+ installGuard,
885
918
  };