claude-code-session-manager 0.129.0 → 0.130.1

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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/assets/AgentLibrary-Dlhtc8Ty.js +2 -0
  3. package/dist/assets/AppSettings-A3KoPcmL.js +2 -0
  4. package/dist/assets/Button-DvTXa_-4.js +1 -0
  5. package/dist/assets/Extensions-Ddb4sQpO.js +13 -0
  6. package/dist/assets/{History-B2x-LMlT.js → History-DcnZxMoU.js} +2 -2
  7. package/dist/assets/Library-LftcMs6C.js +32 -0
  8. package/dist/assets/ListDetail-CnL1azR0.js +1 -0
  9. package/dist/assets/{Memory-CnalwnFf.js → Memory-smN9-Yoo.js} +8 -8
  10. package/dist/assets/{Panel-BzIklgKf.js → Panel-CA6TdCHv.js} +1 -1
  11. package/dist/assets/ProvenanceBadge-Y3DhyiJo.js +1 -0
  12. package/dist/assets/Scheduler-Ca1qo_kp.js +16 -0
  13. package/dist/assets/Settings-BFwlV-as.js +2 -0
  14. package/dist/assets/{SkillReferenceGraph-DOhiCxuL.js → SkillReferenceGraph-2WMsKdmr.js} +1 -1
  15. package/dist/assets/SourceChip-CeprSxwb.js +1 -0
  16. package/dist/assets/SystemPrompt-B8TXIGXo.js +1 -0
  17. package/dist/assets/{TiptapBody-Du6jRBoW.js → TiptapBody-BvxcQ_tS.js} +1 -1
  18. package/dist/assets/{Toggle-Qdi2Z7VD.js → Toggle-keTV_HDb.js} +1 -1
  19. package/dist/assets/ViewTabs-fupn9keJ.js +1 -0
  20. package/dist/assets/VoiceButton-5ETBv9eI.js +1 -0
  21. package/dist/assets/{historyTotals-8ecP_6wF.js → historyTotals-NAZqiuzd.js} +1 -1
  22. package/dist/assets/{index-DtdWBGrI.css → index-Bp8XE9A6.css} +1 -1
  23. package/dist/assets/index-QJxszEhM.js +3086 -0
  24. package/dist/index.html +2 -2
  25. package/dist-web/app.css +1 -1
  26. package/dist-web/app.js +396 -412
  27. package/package.json +1 -1
  28. package/plugins/CLAUDE.md +2 -2
  29. package/plugins/session-manager-dev/.claude-plugin/plugin.json +2 -2
  30. package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +2 -2
  31. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -3
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +62 -0
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +169 -0
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +183 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +39 -0
  36. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +79 -0
  37. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +400 -0
  38. package/scripts/scheduler-mcp-server.cjs +25 -6
  39. package/src/main/agentLibrary.cjs +36 -10
  40. package/src/main/build-info.json +4 -4
  41. package/src/main/config.cjs +15 -0
  42. package/src/main/health.cjs +49 -22
  43. package/src/main/index.cjs +19 -3
  44. package/src/main/ipcSchemas.cjs +36 -3
  45. package/src/main/lib/activeSessions.cjs +6 -2
  46. package/src/main/lib/claude/modelCatalog.cjs +15 -31
  47. package/src/main/lib/claudeConfig.cjs +156 -0
  48. package/src/main/lib/effectiveSettings.cjs +120 -0
  49. package/src/main/lib/epic/delegationReadiness.cjs +3 -3
  50. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +84 -11
  51. package/src/main/lib/git/gitWorktree.cjs +400 -9
  52. package/src/main/lib/git/runtimeStateUntrack.cjs +124 -0
  53. package/src/main/lib/mcpToolCatalog.cjs +8 -2
  54. package/src/main/lib/memoryDirResolve.cjs +2 -8
  55. package/src/main/lib/opsOwnership.cjs +63 -2
  56. package/src/main/lib/persona-macro/builtinMacros.cjs +30 -0
  57. package/src/main/lib/persona-macro/macroLibrary.cjs +34 -6
  58. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +22 -0
  59. package/src/main/lib/updateCheck.cjs +6 -1
  60. package/src/main/pluginInstall.cjs +100 -1
  61. package/src/main/promptSessionsIpc.cjs +39 -1
  62. package/src/main/scheduler.cjs +12 -2
  63. package/src/main/seedDevPlugin.cjs +2 -1
  64. package/src/main/templates/PRD_AUTHORING.md +3 -3
  65. package/src/main/updaterIpc.cjs +5 -1
  66. package/src/main/usage.cjs +5 -20
  67. package/src/main/voiceHotkey.cjs +16 -0
  68. package/src/main/voiceSettings.cjs +24 -0
  69. package/src/main/voiceWizard.cjs +27 -36
  70. package/src/preload/api.d.ts +53 -2
  71. package/src/preload/apiSurface.json +63 -7
  72. package/src/preload/index.cjs +12 -1
  73. package/src/seed/agents/demo-video-builder.md +2 -2
  74. package/src/seed/agents/validator.md +2 -2
  75. package/dist/assets/AgentLibrary-Cp250YHF.js +0 -2
  76. package/dist/assets/Button-DU5UF-6L.js +0 -1
  77. package/dist/assets/DataModel-CPf6f17e.js +0 -1
  78. package/dist/assets/Hooks-BWr33C4Q.js +0 -3
  79. package/dist/assets/Library-DBNLTAa8.js +0 -46
  80. package/dist/assets/ListDetail-BGBw6egp.js +0 -1
  81. package/dist/assets/McpServers-DywZ50Ec.js +0 -2
  82. package/dist/assets/Permissions-mgRifwQc.js +0 -3
  83. package/dist/assets/Plugins-CV42zfid.js +0 -2
  84. package/dist/assets/ProvenanceBadge-DYmX4xgB.js +0 -1
  85. package/dist/assets/SaveBar-DxrAfnlC.js +0 -1
  86. package/dist/assets/Scheduler-iyUl1NDl.js +0 -16
  87. package/dist/assets/ScopeSwitcher-CC8BDPgf.js +0 -1
  88. package/dist/assets/Settings-CWBnQghD.js +0 -4
  89. package/dist/assets/Skills-3Er-9YA9.js +0 -2
  90. package/dist/assets/SystemPrompt-BLxdvZ9K.js +0 -1
  91. package/dist/assets/TagLibrary-BZ6QHYMQ.js +0 -1
  92. package/dist/assets/ViewTabs-BKfFsziD.js +0 -1
  93. package/dist/assets/index-GI6F_j41.js +0 -3083
  94. package/dist/assets/listSkills-C1aWKf0T.js +0 -1
  95. package/dist/assets/settingsSchema-lHTHAabD.js +0 -1
  96. package/dist/assets/skillFrontmatter-8X1Uc282.js +0 -10
  97. package/dist/assets/useAgentsDirWatch-CcsoD1bp.js +0 -1
@@ -0,0 +1,400 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * drift-check.cjs — dependency-free drift check for a repo's markdown network.
5
+ *
6
+ * node drift-check.cjs [--root <dir>] [--map <path>] [--file <path>]...
7
+ * [--exclude <prefix>]... [--checks links,paths,limits,contents] [--strict-paths]
8
+ *
9
+ * Prints one JSON object { root, map, notes, checkedFiles, findings, counts } to stdout.
10
+ * Exit 0 = no findings, 1 = findings, 2 = usage error / missing root.
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const { spawnSync } = require('child_process');
16
+
17
+ const ALL_CHECKS = ['links', 'paths', 'limits', 'contents'];
18
+ const LIMIT_ALWAYS_LOADED = 200;
19
+ const LIMIT_MAP = 70;
20
+ const CONTENTS_MIN_LINES = 100;
21
+ const CONTENTS_WINDOW = 60;
22
+
23
+ class UsageError extends Error {}
24
+
25
+ function parseArgs(argv) {
26
+ const opts = { root: null, map: null, files: [], excludes: [], checks: ALL_CHECKS.slice(), strictPaths: false };
27
+ const needValue = (i, flag) => {
28
+ if (i + 1 >= argv.length || argv[i + 1].startsWith('--')) {
29
+ throw new UsageError(`missing value for ${flag}`);
30
+ }
31
+ return argv[i + 1];
32
+ };
33
+ for (let i = 0; i < argv.length; i++) {
34
+ const a = argv[i];
35
+ if (a === '--root') opts.root = needValue(i++, a);
36
+ else if (a === '--map') opts.map = needValue(i++, a);
37
+ else if (a === '--file') opts.files.push(needValue(i++, a));
38
+ else if (a === '--exclude') opts.excludes.push(needValue(i++, a));
39
+ else if (a === '--strict-paths') opts.strictPaths = true;
40
+ else if (a === '--checks') {
41
+ const list = needValue(i++, a).split(',').map((s) => s.trim()).filter(Boolean);
42
+ for (const c of list) {
43
+ if (!ALL_CHECKS.includes(c)) throw new UsageError(`unknown check: ${c}`);
44
+ }
45
+ if (list.length === 0) throw new UsageError('empty --checks');
46
+ opts.checks = list;
47
+ } else throw new UsageError(`unknown argument: ${a}`);
48
+ }
49
+ return opts;
50
+ }
51
+
52
+ const toPosix = (p) => p.split(path.sep).join('/');
53
+
54
+ function walk(root, dir, out) {
55
+ let entries;
56
+ try {
57
+ entries = fs.readdirSync(dir, { withFileTypes: true });
58
+ } catch {
59
+ return;
60
+ }
61
+ for (const e of entries) {
62
+ if (e.name === '.git' || e.name === 'node_modules') continue;
63
+ const full = path.join(dir, e.name);
64
+ if (e.isDirectory()) walk(root, full, out);
65
+ else if (e.isFile() && e.name.endsWith('.md')) out.push(toPosix(path.relative(root, full)));
66
+ }
67
+ }
68
+
69
+ function listTracked(root) {
70
+ const r = spawnSync('git', ['-C', root, 'ls-files', '-z'], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
71
+ if (!r.error && r.status === 0) return r.stdout.split('\0').filter(Boolean);
72
+ const out = [];
73
+ walkAll(root, root, out);
74
+ return out;
75
+ }
76
+
77
+ function walkAll(root, dir, out) {
78
+ let entries;
79
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
80
+ for (const e of entries) {
81
+ if (e.name === '.git' || e.name === 'node_modules') continue;
82
+ const full = path.join(dir, e.name);
83
+ if (e.isDirectory()) walkAll(root, full, out);
84
+ else if (e.isFile()) out.push(toPosix(path.relative(root, full)));
85
+ }
86
+ }
87
+
88
+ function listDocs(root) {
89
+ const r = spawnSync('git', ['-C', root, 'ls-files', '-z', '--', '*.md'], { encoding: 'utf8' });
90
+ if (!r.error && r.status === 0) {
91
+ return { git: true, files: r.stdout.split('\0').filter(Boolean).filter((f) => fs.existsSync(path.join(root, f))) };
92
+ }
93
+ const out = [];
94
+ walk(root, root, out);
95
+ return { git: false, files: out };
96
+ }
97
+
98
+ /** Blank out inline code spans (keeps length) so links inside them are ignored. */
99
+ function blankCode(line) {
100
+ return line.replace(/`[^`]*`/g, (m) => ' '.repeat(m.length));
101
+ }
102
+
103
+ const IGNORE_MARKER = '<!-- drift-check-ignore -->';
104
+ const DOMAIN_RE = /^([a-z0-9-]+\.)+[a-z]{2,}$/i;
105
+ const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
106
+
107
+ function isRepoPathCandidate(span) {
108
+ if (!span.includes('/')) return false;
109
+ if (/[\s*?<>{}|=$]/.test(span)) return false;
110
+ if (/^[~/@]/.test(span)) return false;
111
+ if (SCHEME_RE.test(span)) return false;
112
+ if (/(\.\.\.|…)$/.test(span)) return false;
113
+ if (span.split('/').some((seg) => seg === '...' || seg === '…')) return false;
114
+ const first = span.split('/')[0];
115
+ if (DOMAIN_RE.test(first)) return false;
116
+ return true;
117
+ }
118
+
119
+ /** Parse a doc once: returns { lines, links, spans }. */
120
+ function parseDoc(text) {
121
+ const rawLines = text.split('\n');
122
+ const links = [];
123
+ const spans = [];
124
+ const importTokens = [];
125
+ const ignoredLines = new Set();
126
+ let fence = null;
127
+ let inComment = false;
128
+ rawLines.forEach((raw, idx) => {
129
+ const lineNo = idx + 1;
130
+ const fm = /^\s*(```+|~~~+)/.exec(raw);
131
+ if (!inComment && fm) {
132
+ const marker = fm[1][0];
133
+ if (fence === null) fence = marker;
134
+ else if (fence === marker) fence = null;
135
+ return;
136
+ }
137
+ if (fence !== null) return;
138
+ if (raw.includes(IGNORE_MARKER)) ignoredLines.add(lineNo);
139
+ // strip HTML comments (possibly spanning lines)
140
+ let line = '';
141
+ let rest = raw;
142
+ while (rest.length) {
143
+ if (inComment) {
144
+ const end = rest.indexOf('-->');
145
+ if (end === -1) { rest = ''; break; }
146
+ rest = rest.slice(end + 3);
147
+ inComment = false;
148
+ } else {
149
+ const start = rest.indexOf('<!--');
150
+ if (start === -1) { line += rest; rest = ''; break; }
151
+ line += rest.slice(0, start);
152
+ rest = rest.slice(start + 4);
153
+ inComment = true;
154
+ }
155
+ }
156
+ const noCode = blankCode(line);
157
+ const linkRe = /!?\[[^\]]*\]\(\s*(<[^>]*>|[^)\s]+)(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/g;
158
+ let m;
159
+ while ((m = linkRe.exec(noCode))) {
160
+ let t = m[1];
161
+ if (t.startsWith('<') && t.endsWith('>')) t = t.slice(1, -1);
162
+ links.push({ line: lineNo, target: t });
163
+ }
164
+ const impRe = /(?:^|\s)@(\S+)/g;
165
+ while ((m = impRe.exec(noCode))) importTokens.push(m[1]);
166
+ const spanRe = /`([^`]+)`/g;
167
+ while ((m = spanRe.exec(line))) spans.push({ line: lineNo, span: m[1].trim() });
168
+ });
169
+ return { lines: rawLines, links, spans, importTokens, ignoredLines };
170
+ }
171
+
172
+ const MAX_IMPORT_HOPS = 4;
173
+
174
+ /** Claude Code `@path` imports of a doc: absolute .md paths inside root. */
175
+ function parseImports(text, fileAbs, root) {
176
+ const out = [];
177
+ for (let tok of parseDoc(text).importTokens) {
178
+ tok = tok.replace(/[.,;:!?)\]}'"]+$/, '');
179
+ if (!tok || tok.startsWith('~')) continue;
180
+ if (!/\.md$/i.test(tok)) continue;
181
+ const abs = path.resolve(path.dirname(fileAbs), tok);
182
+ const rel = path.relative(root, abs);
183
+ if (rel.startsWith('..') || path.isAbsolute(rel)) continue;
184
+ if (!out.includes(abs)) out.push(abs);
185
+ }
186
+ return out;
187
+ }
188
+
189
+ const docInfoCache = new Map(); // abs -> { lines, imports } | null (per process; reset each run)
190
+
191
+ function docInfo(fileAbs, root) {
192
+ if (docInfoCache.has(fileAbs)) return docInfoCache.get(fileAbs);
193
+ let info = null;
194
+ try {
195
+ const text = fs.readFileSync(fileAbs, 'utf8');
196
+ info = { lines: countLines(text), imports: parseImports(text, fileAbs, root) };
197
+ } catch { /* missing target: ignored */ }
198
+ docInfoCache.set(fileAbs, info);
199
+ return info;
200
+ }
201
+
202
+ /** Own lines + lines of recursively imported .md files (<= 4 hops, each file once). */
203
+ function expandedLineCount(fileAbs, root, seen = new Set(), depth = 0) {
204
+ if (seen.has(fileAbs)) return 0;
205
+ const info = docInfo(fileAbs, root);
206
+ if (!info) return 0;
207
+ seen.add(fileAbs);
208
+ let total = info.lines;
209
+ if (depth < MAX_IMPORT_HOPS) {
210
+ for (const imp of info.imports) total += expandedLineCount(imp, root, seen, depth + 1);
211
+ }
212
+ return total;
213
+ }
214
+
215
+ const countLines = (text) => {
216
+ const n = text.split('\n').length;
217
+ return text.endsWith('\n') ? n - 1 : n;
218
+ };
219
+
220
+ function hasContentsList(lines) {
221
+ if (lines.some((l) => /^#{1,6}\s+(table of contents|contents)\s*#*\s*$/i.test(l))) return true;
222
+ const n = lines.slice(0, CONTENTS_WINDOW).filter((l) => /^\s*(?:[-*+]|\d+[.)])\s.*\]\(#/.test(l)).length;
223
+ return n >= 3;
224
+ }
225
+
226
+ function hasPathsFrontmatter(text) {
227
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
228
+ return !!m && /^paths\s*:/m.test(m[1]);
229
+ }
230
+
231
+ function runDriftCheck(options) {
232
+ const opts = Object.assign({ root: null, map: null, files: [], excludes: [], checks: ALL_CHECKS, strictPaths: false }, options);
233
+ const root = path.resolve(opts.root || process.cwd());
234
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
235
+ throw new UsageError(`root is not a directory: ${root}`);
236
+ }
237
+ const checks = new Set(opts.checks);
238
+ docInfoCache.clear();
239
+
240
+ let docs;
241
+ let isGit;
242
+ if (opts.files.length) {
243
+ docs = opts.files.map((f) => toPosix(path.relative(root, path.resolve(root, f))));
244
+ isGit = spawnSync('git', ['-C', root, 'rev-parse', '--git-dir'], { encoding: 'utf8' }).status === 0;
245
+ } else {
246
+ const l = listDocs(root);
247
+ docs = l.files;
248
+ isGit = l.git;
249
+ }
250
+ const excludes = opts.excludes.map((e) => toPosix(e).replace(/^\.\//, ''));
251
+ docs = docs.filter((f) => !excludes.some((e) => f.startsWith(e))).sort();
252
+ docs = docs.filter((f) => fs.existsSync(path.join(root, f)));
253
+
254
+ // map
255
+ let map = null;
256
+ if (opts.map) {
257
+ map = toPosix(path.relative(root, path.resolve(root, opts.map)));
258
+ if (!fs.existsSync(path.join(root, map))) throw new UsageError(`map not found: ${opts.map}`);
259
+ } else {
260
+ const rootFiles = ['CLAUDE.md', 'AGENTS.md'].map((n) => path.join(root, n)).filter((p) => fs.existsSync(p));
261
+ const candidates = [...rootFiles];
262
+ for (const p of rootFiles) {
263
+ const info = docInfo(p, root);
264
+ for (const imp of info ? info.imports : []) if (!candidates.includes(imp)) candidates.push(imp);
265
+ }
266
+ for (const p of candidates) {
267
+ let t;
268
+ try { t = fs.readFileSync(p, 'utf8'); } catch { continue; }
269
+ if (/<!--\s*md-network-map/.test(t)) { map = toPosix(path.relative(root, p)); break; }
270
+ }
271
+ }
272
+ const notes = [];
273
+ if (map === null) notes.push('no md-network-map comment found; the 70-line map limit was not applied');
274
+
275
+ let trackedList = null;
276
+ const tracked = () => (trackedList || (trackedList = listTracked(root)));
277
+ const findings = [];
278
+ const missing = []; // { file, line, target, cands }
279
+ const missingLinks = []; // same shape; broken-link candidates, dropped when gitignored
280
+
281
+ for (const rel of docs) {
282
+ const abs = path.join(root, rel);
283
+ let text;
284
+ try { text = fs.readFileSync(abs, 'utf8'); } catch { continue; }
285
+ const docDir = path.dirname(abs);
286
+ const needParse = checks.has('links') || checks.has('paths') || checks.has('contents');
287
+ const parsed = needParse ? parseDoc(text) : null;
288
+ const lineCount = countLines(text);
289
+
290
+ if (checks.has('links')) {
291
+ for (const l of parsed.links) {
292
+ if (parsed.ignoredLines.has(l.line)) continue;
293
+ let t = l.target;
294
+ if (t.startsWith('#') || t.startsWith('//') || SCHEME_RE.test(t)) continue;
295
+ if (/\{\{|\}\}|\$\{|<[^>]*>/.test(t)) continue; // template placeholder, not a path
296
+ t = t.replace(/[#?].*$/, '');
297
+ if (!t) continue;
298
+ try { t = decodeURI(t); } catch { /* keep raw */ }
299
+ const fromRoot = path.resolve(root, t.replace(/^\/+/, ''));
300
+ const siteRoute = /^\/(?!\/)/.test(t) && !fs.existsSync(fromRoot);
301
+ if (siteRoute && !opts.strictPaths) continue;
302
+ if (!fs.existsSync(path.resolve(docDir, t)) && !fs.existsSync(fromRoot)) {
303
+ const cands = [path.resolve(docDir, t), fromRoot]
304
+ .map((p) => toPosix(path.relative(root, p)))
305
+ .filter((p) => p && !p.startsWith('..'));
306
+ missingLinks.push({ file: rel, line: l.line, target: l.target, cands });
307
+ }
308
+ }
309
+ }
310
+
311
+ if (checks.has('paths')) {
312
+ for (const s of parsed.spans) {
313
+ if (parsed.ignoredLines.has(s.line)) continue;
314
+ if (!isRepoPathCandidate(s.span)) continue;
315
+ const t = s.span.replace(/:\d+(?:-\d+)?$/, '');
316
+ if (!t || !t.includes('/')) continue;
317
+ const a = path.resolve(root, t);
318
+ const b = path.resolve(docDir, t);
319
+ if (fs.existsSync(a) || fs.existsSync(b)) continue;
320
+ const segs = t.split('/').filter(Boolean);
321
+ const last = segs[segs.length - 1] || '';
322
+ const anchored = /\.[A-Za-z0-9]+$/.test(last) || t.endsWith('/') || fs.existsSync(path.join(root, segs[0] || ''));
323
+ if (!anchored) continue;
324
+ const tt = t.replace(/\/+$/, '');
325
+ const matches = tracked().filter((f) => f === tt || f.endsWith('/' + tt) || f.startsWith(tt + '/') || f.includes('/' + tt + '/'));
326
+ if (matches.length) {
327
+ if (opts.strictPaths) {
328
+ findings.push({ kind: 'unanchored-path', file: rel, line: s.line, target: s.span, matches: matches.slice(0, 3) });
329
+ }
330
+ continue;
331
+ }
332
+ const cands = [a, b]
333
+ .map((p) => toPosix(path.relative(root, p)) + (t.endsWith('/') ? '/' : ''))
334
+ .filter((p) => p && !p.startsWith('..'));
335
+ missing.push({ file: rel, line: s.line, target: s.span, cands });
336
+ }
337
+ }
338
+
339
+ if (checks.has('limits')) {
340
+ const base = path.posix.basename(rel);
341
+ const isRule = /(^|\/)\.claude\/rules\/.+\.md$/.test(rel) && !hasPathsFrontmatter(text);
342
+ const alwaysLoaded = base === 'CLAUDE.md' || base === 'AGENTS.md' || isRule;
343
+ const isMap = !!map && rel === map;
344
+ if (alwaysLoaded || isMap) {
345
+ const expandedLines = expandedLineCount(abs, root);
346
+ if (alwaysLoaded && expandedLines > LIMIT_ALWAYS_LOADED) {
347
+ findings.push({ kind: 'over-line-limit', file: rel, lines: lineCount, expandedLines, limit: LIMIT_ALWAYS_LOADED });
348
+ }
349
+ if (isMap && expandedLines > LIMIT_MAP) {
350
+ findings.push({ kind: 'over-line-limit', file: rel, lines: lineCount, expandedLines, limit: LIMIT_MAP });
351
+ }
352
+ }
353
+ }
354
+
355
+ if (checks.has('contents') && lineCount > CONTENTS_MIN_LINES && !hasContentsList(parsed.lines)) {
356
+ findings.push({ kind: 'no-contents-list', file: rel, lines: lineCount });
357
+ }
358
+ }
359
+
360
+ if (missing.length || missingLinks.length) {
361
+ let ignored = new Set();
362
+ if (isGit) {
363
+ const input = [...new Set([...missing, ...missingLinks].flatMap((m) => m.cands))].join('\n') + '\n';
364
+ const r = spawnSync('git', ['-C', root, 'check-ignore', '--stdin'], { input, encoding: 'utf8' });
365
+ if (!r.error) ignored = new Set(r.stdout.split('\n').filter(Boolean));
366
+ }
367
+ for (const m of missing) {
368
+ if (m.cands.some((c) => ignored.has(c))) continue;
369
+ findings.push({ kind: 'missing-path', file: m.file, line: m.line, target: m.target });
370
+ }
371
+ for (const m of missingLinks) {
372
+ if (m.cands.some((c) => ignored.has(c))) continue;
373
+ findings.push({ kind: 'broken-link', file: m.file, line: m.line, target: m.target });
374
+ }
375
+ }
376
+
377
+ findings.sort((x, y) => (x.file < y.file ? -1 : x.file > y.file ? 1 : (x.line || 0) - (y.line || 0)));
378
+ const counts = {};
379
+ for (const f of findings) counts[f.kind] = (counts[f.kind] || 0) + 1;
380
+ return { root: toPosix(root), map, notes, checkedFiles: docs, findings, counts };
381
+ }
382
+
383
+ function main() {
384
+ let result;
385
+ try {
386
+ result = runDriftCheck(parseArgs(process.argv.slice(2)));
387
+ } catch (err) {
388
+ if (err instanceof UsageError) {
389
+ process.stderr.write(`drift-check: ${err.message}\n`);
390
+ process.exit(2);
391
+ }
392
+ throw err;
393
+ }
394
+ process.stdout.write(JSON.stringify(result, null, 2) + '\n');
395
+ process.exit(result.findings.length ? 1 : 0);
396
+ }
397
+
398
+ module.exports = { runDriftCheck, parseArgs };
399
+
400
+ if (require.main === module) main();
@@ -18,7 +18,7 @@
18
18
  * project_video_write({ cwd?, videoId, title, kind, lengthS, html? | htmlPath?, meta? }) -> POST /admin/project-home/videos/write
19
19
  *
20
20
  * macro_list({ cwd? }) -> GET /admin/macros?cwd=<encoded>
21
- * macro_save({ cwd?, id?, label, agentName, tag, prompt }) -> POST /admin/macros/save
21
+ * macro_save({ cwd?, id?, label, agentName, tag, prompt, inputs?, surface?, projects?, humanRequestQuote? }) -> POST /admin/macros/save
22
22
  * macro_delete({ id }) -> POST /admin/macros/delete
23
23
  * customer_feedback_list({ pull?, includeHidden? }) -> GET /admin/customer-feedback/inbox
24
24
  * customer_feedback_set_status({ id, status, note? }) -> POST /admin/customer-feedback/status
@@ -609,6 +609,9 @@ const TOOLS = [
609
609
  agentName: { type: 'string', description: 'Persona to run the macro as (e.g. "builder").' },
610
610
  tag: { type: 'string', description: 'Mission tag for the macro.' },
611
611
  prompt: { type: 'string', description: 'The opening prompt the macro sends. Write input placeholders as {{name}}; each is filled from the matching entry in `inputs` when the macro is pressed.' },
612
+ surface: { type: 'string', enum: ['sessions', 'project-home'], description: "Where the macro shows: 'sessions' = Sessions HOT KEYS strip, 'project-home' = Project Home button row." },
613
+ projects: { type: 'array', items: { type: 'string' }, description: 'Optional: only ["*"] is accepted, to show the macro in every project. Needs humanRequestQuote and a Session Manager chat session.' },
614
+ humanRequestQuote: { type: 'string', description: 'With projects ["*"]: the exact words the human typed in this chat that ask for every/all projects.' },
612
615
  inputs: {
613
616
  type: 'array',
614
617
  description: 'Optional input fields the human fills in before the macro runs. Prompt placeholders are written as {{name}}. Omit on update to keep the existing inputs; pass [] to clear them.',
@@ -708,16 +711,20 @@ function jobToolScopeRefusal(toolName) {
708
711
  // A macro is a human's button and its delete cannot be undone, so this runs
709
712
  // only in a session a human is attached to. headlessQueueRefusal does not fit:
710
713
  // it lets an architect job through.
711
- function macroDeleteRefusal() {
714
+ function humanSessionRefusal(message) {
712
715
  if (process.env.SM_SCHEDULER_JOB_SLUG || !process.env.SM_CHAT_SESSION_ID) {
713
- return errorResult(
714
- 'refused: macro_delete runs only in a Session Manager chat or terminal session, because a macro goes only when a human asks. '
715
- + 'Say in your final result which macro should go; the human can remove it from the HOT KEYS panel.',
716
- );
716
+ return errorResult(message);
717
717
  }
718
718
  return null;
719
719
  }
720
720
 
721
+ function macroDeleteRefusal() {
722
+ return humanSessionRefusal(
723
+ 'refused: macro_delete runs only in a Session Manager chat or terminal session, because a macro goes only when a human asks. '
724
+ + 'Say in your final result which macro should go; the human can remove it from the HOT KEYS panel.',
725
+ );
726
+ }
727
+
721
728
  // Named + exported (see module.exports below) so mcpToolCatalog.test.cjs's
722
729
  // sibling can exercise session_manager_help's argument handling directly —
723
730
  // mocking node:fs/promises + global.fetch to drive adminRequest — without
@@ -1049,11 +1056,23 @@ async function handleCallTool(request) {
1049
1056
  if (missing.length > 0) {
1050
1057
  return errorResult(`missing or invalid required argument(s): ${missing.join(', ')}`);
1051
1058
  }
1059
+ if (args.projects !== undefined) {
1060
+ const refusal = humanSessionRefusal(
1061
+ 'refused: a macro shown in every project is saved only in a Session Manager chat session where the human asked for it. '
1062
+ + 'Say in your final result that the human can set Show in every project in the macro editor.',
1063
+ );
1064
+ if (refusal) return refusal;
1065
+ }
1052
1066
  const cwd = resolveCwdArg(args);
1053
1067
  const payload = { cwd, label: args.label, agentName: args.agentName, tag: args.tag, prompt: args.prompt };
1054
1068
  if (typeof args.id === 'string' && args.id) payload.id = args.id;
1055
1069
  if (Array.isArray(args.inputs)) payload.inputs = args.inputs;
1070
+ if (typeof args.surface === 'string') payload.surface = args.surface;
1071
+ if (Array.isArray(args.projects)) payload.projects = args.projects;
1072
+ if (typeof args.humanRequestQuote === 'string') payload.humanRequestQuote = args.humanRequestQuote;
1073
+ payload.originClaudeSessionId = process.env.SM_CHAT_SESSION_ID;
1056
1074
  const result = await adminRequest('POST', '/admin/macros/save', payload);
1075
+ if (result?.ok === false) return errorResult(result.error ?? 'macro_save failed');
1057
1076
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
1058
1077
  }
1059
1078
  if (name === 'macro_delete') {
@@ -72,7 +72,28 @@ function decodeLine(s) {
72
72
  * unchanged (not Claude-Code-visible either) so a save from the Agent
73
73
  * Library editor never erases the stamp a hand-edit should keep intact.
74
74
  */
75
- function serializePersona({ name, description, tools, model, effort, color, tags, projects, action, actionLabel, title, seedVersion, executorOnly, body }) {
75
+ const MANAGED_PERSONA_KEYS = new Set(['name', 'description', 'tools', 'model', 'effort', 'color', 'tags', 'projects', 'action', 'actionLabel', 'title', 'seedVersion', 'executorOnly']);
76
+
77
+ /**
78
+ * Raw text lines of every top-level frontmatter key block in `raw` whose key
79
+ * is NOT in `managed` (key line + its continuation lines), verbatim.
80
+ */
81
+ function extractUnmanagedLines(raw, managed) {
82
+ if (typeof raw !== 'string' || !raw.startsWith('---\n')) return [];
83
+ const end = raw.indexOf('\n---', 4);
84
+ if (end === -1) return [];
85
+ const out = [];
86
+ let keep = false;
87
+ for (const line of raw.slice(4, end).split('\n')) {
88
+ const m = line.match(/^([A-Za-z][A-Za-z0-9_-]*)\s*:/);
89
+ if (m) keep = !managed.has(m[1]);
90
+ if (keep) out.push(line);
91
+ }
92
+ while (out.length && out[out.length - 1].trim() === '') out.pop();
93
+ return out;
94
+ }
95
+
96
+ function serializePersona({ name, description, tools, model, effort, color, tags, projects, action, actionLabel, title, seedVersion, executorOnly, body, preservedLines }) {
76
97
  const lines = ['---', `name: ${name}`];
77
98
  if (description) lines.push(`description: ${description}`);
78
99
  if (tools && tools.length) lines.push(`tools: ${tools.join(', ')}`);
@@ -86,6 +107,7 @@ function serializePersona({ name, description, tools, model, effort, color, tags
86
107
  if (title) lines.push(`title: ${title}`);
87
108
  if (typeof seedVersion === 'number' && Number.isFinite(seedVersion)) lines.push(`seedVersion: ${seedVersion}`);
88
109
  if (executorOnly === true) lines.push('executorOnly: true');
110
+ if (Array.isArray(preservedLines) && preservedLines.length) lines.push(...preservedLines);
89
111
  lines.push('---', '');
90
112
  return lines.join('\n') + (body || '').trim() + '\n';
91
113
  }
@@ -104,26 +126,26 @@ async function saveOverlay({ name, projectName, model, effort, loadSessions, val
104
126
  const project = projects.find((p) => p.name === projectName);
105
127
  if (!project) throw new Error(`project not open: ${projectName}`);
106
128
  const target = validatePath(path.join(project.cwd, '.claude', 'agents', `${name}.md`));
107
- let fm = {};
129
+ let preserved = [];
108
130
  try {
109
- const existing = splitFrontmatter(await fsp.readFile(target, 'utf8'));
131
+ const rawExisting = await fsp.readFile(target, 'utf8');
132
+ const existing = splitFrontmatter(rawExisting);
110
133
  if (existing.body.trim() !== '') {
111
134
  throw new Error(`${name} has a full-body override in ${projectName} — edit ${target} directly; it is not converted to a frontmatter-only override`);
112
135
  }
113
- fm = existing.fm;
136
+ preserved = extractUnmanagedLines(rawExisting, new Set(['model', 'effort']));
114
137
  } catch (e) {
115
138
  if (e.code !== 'ENOENT') throw e;
116
139
  }
117
- const next = { ...fm };
140
+ const managedLines = [];
118
141
  for (const [k, v] of [['model', model], ['effort', effort]]) {
119
- if (v && v !== 'inherit') next[k] = v;
120
- else delete next[k];
142
+ if (v && v !== 'inherit') managedLines.push(`${k}: ${v}`);
121
143
  }
122
- if (Object.keys(next).length === 0) {
144
+ if (managedLines.length === 0 && preserved.length === 0) {
123
145
  await removeOverride({ name, projectName, loadSessions, validatePath });
124
146
  return { ok: true, path: target, removed: true };
125
147
  }
126
- const lines = ['---', ...Object.entries(next).map(([k, v]) => `${k}: ${v}`), '---', ''];
148
+ const lines = ['---', ...managedLines, ...preserved, '---', ''];
127
149
  await writeTextAtomic(target, lines.join('\n'));
128
150
  return { ok: true, path: target };
129
151
  }
@@ -176,6 +198,10 @@ async function savePersona({
176
198
  let resolvedAction = action;
177
199
  let resolvedActionLabel = actionLabel;
178
200
  let resolvedExecutorOnly = executorOnly;
201
+ let preservedLines = [];
202
+ try {
203
+ preservedLines = extractUnmanagedLines(fsSync.readFileSync(target, 'utf8'), MANAGED_PERSONA_KEYS);
204
+ } catch { /* no existing file — nothing to preserve */ }
179
205
  if ([seedVersion, title, projects, action, actionLabel, executorOnly].some((v) => v === undefined)) {
180
206
  try {
181
207
  const { fm } = splitFrontmatter(fsSync.readFileSync(target, 'utf8'));
@@ -190,7 +216,7 @@ async function savePersona({
190
216
  if (resolvedActionLabel === undefined && fm.actionLabel) resolvedActionLabel = decodeLine(fm.actionLabel);
191
217
  } catch { /* no existing file (or unreadable) — nothing to carry over */ }
192
218
  }
193
- const text = serializePersona({ name, description, tools, model, effort, color, tags, projects: resolvedProjects, action: resolvedAction, actionLabel: resolvedActionLabel, title: resolvedTitle, seedVersion: resolvedSeedVersion, executorOnly: resolvedExecutorOnly, body });
219
+ const text = serializePersona({ name, description, tools, model, effort, color, tags, projects: resolvedProjects, action: resolvedAction, actionLabel: resolvedActionLabel, title: resolvedTitle, seedVersion: resolvedSeedVersion, executorOnly: resolvedExecutorOnly, body, preservedLines });
194
220
  await writeTextAtomic(target, text);
195
221
  if (originalName && originalName !== name) {
196
222
  const oldReal = validatePath(path.join(globalDir, `${originalName}.md`));
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.129.0",
3
- "gitSha": "6bb933179c6b91ea91b4ef8bfe113b95fae19466",
4
- "gitShortSha": "6bb93317",
2
+ "version": "0.130.1",
3
+ "gitSha": "c44cbe32642cfc821a0014f430cd6db3235e48e8",
4
+ "gitShortSha": "c44cbe32",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-11-06T22:56:53.741Z",
6
+ "builtAt": "2026-11-07T08:09:17.697Z",
7
7
  "dirty": false
8
8
  }
@@ -157,6 +157,10 @@ function validateWrite(realAbs) {
157
157
  let realRoot;
158
158
  try { realRoot = canon(root); } catch { realRoot = root; }
159
159
  if (within(realAbs, realRoot)) {
160
+ // Project-scope MCP servers live in <root>/.mcp.json — the one
161
+ // root-level file allowed (exact match on the realpath, so a symlink
162
+ // escaping the root resolves elsewhere and is refused).
163
+ if (realAbs === path.join(realRoot, '.mcp.json')) return;
160
164
  const claudeSub = path.join(realRoot, '.claude');
161
165
  if (within(realAbs, claudeSub)) {
162
166
  return;
@@ -354,6 +358,16 @@ async function listDir(abs, { filesOnly = false, dirsOnly = false, includeHidden
354
358
  }
355
359
  }
356
360
 
361
+ /** True only when writeTextAtomic would pass its path checks (validatePath + validateWrite). */
362
+ function canWrite(abs) {
363
+ try {
364
+ validateWrite(validatePath(expandHome(abs)));
365
+ return true;
366
+ } catch {
367
+ return false;
368
+ }
369
+ }
370
+
357
371
  async function exists(abs) {
358
372
  try {
359
373
  abs = validatePath(expandHome(abs));
@@ -498,6 +512,7 @@ function registerConfigHandlers() {
498
512
  }));
499
513
  ipcMain.handle('config:write-text', v(s.configWriteText, ({ path: p, text, writer }) => writeTextAtomic(p, text, { writer })));
500
514
  ipcMain.handle('config:list-dir', v(s.configListDir, ({ path: p, opts }) => listDir(p, opts || {})));
515
+ ipcMain.handle('config:can-write', v(s.configPath, ({ path: p }) => canWrite(p)));
501
516
  ipcMain.handle('config:exists', v(s.configPath, ({ path: p }) => exists(p)));
502
517
  ipcMain.handle('config:parse-imports', v(s.configParseImports, async ({ path: p }) => {
503
518
  try {