claude-code-session-manager 0.130.1 → 0.130.3

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 (58) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +19 -2
  3. package/dist/assets/AgentLibrary-BmrXNwK8.js +2 -0
  4. package/dist/assets/{AppSettings-A3KoPcmL.js → AppSettings-Cs4POznd.js} +1 -1
  5. package/dist/assets/{Button-DvTXa_-4.js → Button-UUr5giu8.js} +1 -1
  6. package/dist/assets/DocumentEditorPane-C46Hj0lz.js +1 -0
  7. package/dist/assets/Extensions-B9QdiNOV.js +2 -0
  8. package/dist/assets/{History-DcnZxMoU.js → History-Bndupj87.js} +2 -2
  9. package/dist/assets/{Library-LftcMs6C.js → Library-DFn0YPIW.js} +5 -5
  10. package/dist/assets/{ListDetail-CnL1azR0.js → ListDetail-DjMn8a_3.js} +1 -1
  11. package/dist/assets/{Panel-CA6TdCHv.js → Panel-CIvb-XXN.js} +1 -1
  12. package/dist/assets/ProjectClaudeConfig-BQQRtMdK.js +25 -0
  13. package/dist/assets/{ProvenanceBadge-Y3DhyiJo.js → ProvenanceBadge-ej8W2ZIK.js} +1 -1
  14. package/dist/assets/{Scheduler-Ca1qo_kp.js → Scheduler-DSVBWqRK.js} +8 -8
  15. package/dist/assets/Settings-DqxUna06.js +2 -0
  16. package/dist/assets/{SkillReferenceGraph-2WMsKdmr.js → SkillReferenceGraph-BEMTdxdD.js} +1 -1
  17. package/dist/assets/Skills-DTXehVS7.js +12 -0
  18. package/dist/assets/{SourceChip-CeprSxwb.js → SourceChip-BrPci8FX.js} +1 -1
  19. package/dist/assets/SystemPrompt-B43hNP0X.js +1 -0
  20. package/dist/assets/{TiptapBody-BvxcQ_tS.js → TiptapBody-B-R2Bpda.js} +1 -1
  21. package/dist/assets/{Toggle-keTV_HDb.js → Toggle-DKb4x1BP.js} +1 -1
  22. package/dist/assets/ViewTabs-CcJdFZgv.js +1 -0
  23. package/dist/assets/{VoiceButton-5ETBv9eI.js → VoiceButton-BSH0UI3u.js} +1 -1
  24. package/dist/assets/{historyTotals-NAZqiuzd.js → historyTotals-5oUEu_fe.js} +1 -1
  25. package/dist/assets/index-C9w-dVzo.js +3090 -0
  26. package/dist/assets/{index-Bp8XE9A6.css → index-CMCcT2yg.css} +1 -1
  27. package/dist/index.html +2 -2
  28. package/dist-web/app.css +1 -1
  29. package/dist-web/app.js +420 -416
  30. package/package.json +1 -1
  31. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +15 -5
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +8 -4
  34. package/src/main/agentLibrary.cjs +81 -29
  35. package/src/main/agentsIpc.cjs +21 -16
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/ipcSchemas.cjs +7 -1
  38. package/src/main/lib/epic/epicWorktreeMerge.cjs +11 -9
  39. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  40. package/src/main/lib/git/gitWorktree.cjs +216 -43
  41. package/src/main/lib/mdNetworkScan.cjs +555 -0
  42. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +18 -5
  43. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  44. package/src/main/lib/persona-macro/macroJobDispatch.cjs +9 -2
  45. package/src/main/lib/scheduler/terminalRunOutcome.cjs +61 -15
  46. package/src/main/projectPages.cjs +32 -7
  47. package/src/main/scheduler/gitTreeGuard.cjs +85 -12
  48. package/src/main/scheduler.cjs +16 -5
  49. package/src/preload/api.d.ts +91 -6
  50. package/src/preload/apiSurface.json +7 -0
  51. package/src/preload/index.cjs +1 -0
  52. package/dist/assets/AgentLibrary-Dlhtc8Ty.js +0 -2
  53. package/dist/assets/Extensions-Ddb4sQpO.js +0 -13
  54. package/dist/assets/Memory-smN9-Yoo.js +0 -25
  55. package/dist/assets/Settings-BFwlV-as.js +0 -2
  56. package/dist/assets/SystemPrompt-B8TXIGXo.js +0 -1
  57. package/dist/assets/ViewTabs-fupn9keJ.js +0 -1
  58. package/dist/assets/index-QJxszEhM.js +0 -3086
@@ -0,0 +1,555 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * mdNetworkScan.cjs — a project's markdown link network, mapped from its root
6
+ * CLAUDE.md, for Project Home's Tools > Review MD network (link map + findings).
7
+ * No LLM, read-only, bounded.
8
+ *
9
+ * Top-level in lib/ because no subfolder fits: it reads the project's own docs,
10
+ * so it is neither project-pages/ (the generated pages/videos library) nor git/
11
+ * (git only lists the files), and it does I/O, so it is not util/. It sits
12
+ * beside memoryMdNetwork.cjs, the other reader of the same docs network.
13
+ *
14
+ * - buildMdNetwork({ files, root, exists }) — pure graph builder over in-memory docs.
15
+ * - scanMdNetwork(cwd, deps) — thin I/O wrapper: one `git ls-files -z`, at most
16
+ * MAX_DOCS docs read (the root, then breadth-first along its links, then the
17
+ * rest shallowest-first, so the cap drops unreachable docs before reachable
18
+ * ones), at most MAX_DOC_BYTES each, READ_BATCH reads in parallel, async fs only.
19
+ * Untracked link targets (e.g. gitignored files) are checked on disk.
20
+ *
21
+ * Followed: inline `[text](target)` links (images too) and `<target.md>`
22
+ * autolinks, outside code fences, inline code and HTML comments. Ignored: any
23
+ * `scheme:` target (http(s):, mailto:, ...), `/absolute` and `//host` targets,
24
+ * and `#anchor`-only links. `#fragment` and `?query` are stripped and the rest
25
+ * resolves against the linking doc's folder. A target outside the project, or
26
+ * one that does not exist, is a broken link.
27
+ */
28
+
29
+ const fs = require('node:fs');
30
+ const path = require('node:path');
31
+ const { execGit } = require('./git/gitExec.cjs');
32
+
33
+ const ROOT_DOC = 'CLAUDE.md';
34
+ const MAX_DOCS = 2000;
35
+ const MAX_DOC_BYTES = 256 * 1024;
36
+ const READ_BATCH = 32;
37
+ /** Longest link destination or title scanned, so a pathological line stays linear. */
38
+ const MAX_LINK_CHARS = 1024;
39
+ /** `git ls-files -z` stdout cap; node's 1 MB default overflows near 15k tracked files. */
40
+ const LS_FILES_MAX_BUFFER = 64 * 1024 * 1024;
41
+ const OWNER_NAMES = new Set(['CLAUDE.md', 'README.md', 'AGENTS.md']);
42
+ const MISSING_CODES = new Set(['ENOENT', 'ENOTDIR', 'EISDIR']);
43
+ const DETAIL_MISSING = 'The link target doesn’t exist.';
44
+ const DETAIL_ESCAPES = 'The link target is outside the project.';
45
+
46
+ const MD_RE = /\.md$/i;
47
+ const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
48
+ const FENCE_RE = /^\s*(`{3,}|~{3,})(.*)$/;
49
+ const INLINE_CODE_RE = /(`+).{0,1024}?\1/g;
50
+ const AUTOLINK_RE = /<([^<>\s]{1,1024})>/g;
51
+
52
+ /**
53
+ * @typedef {{ path: string, text: string }} MdFile a doc: repo-relative POSIX path + text
54
+ * @typedef {{ line: number, target: string, to: string, escapes: boolean }} MdLink
55
+ * `target` as written (fragment/query stripped); `to` resolved repo-relative
56
+ * @typedef {'hub' | 'owner' | 'doc'} MdNetworkNodeType
57
+ * @typedef {{ id: string, path: string, depth: number, type: MdNetworkNodeType, linksOut: number, linkedFrom: number }} MdNetworkNode
58
+ * @typedef {{ from: string, to: string, broken?: boolean }} MdNetworkEdge
59
+ * `to` of a broken edge is the missing (or escaping) resolved target, not a node
60
+ * @typedef {{ type: 'broken-link', file: string, line: number, target: string, to: string, where: string, detail: string }} MdNetworkBrokenLink
61
+ * @typedef {{ type: 'orphan', where: string, count: number, paths: string[], detail: string }} MdNetworkOrphan
62
+ * @typedef {MdNetworkBrokenLink | MdNetworkOrphan} MdNetworkFinding
63
+ * @typedef {{ ok: true, root: string, nodes: MdNetworkNode[], edges: MdNetworkEdge[], findings: MdNetworkFinding[], docs: number, links: number, scopes: string[] }} MdNetwork
64
+ * @typedef {MdNetwork | { ok: false, error: string }} MdNetworkResult
65
+ * @typedef {{ fence: string, inComment: boolean }} LineState an open code fence / HTML comment
66
+ */
67
+
68
+ /**
69
+ * @typedef {object} ScanDeps
70
+ * @property {(cwd: string, args: string[], opts?: { maxBuffer?: number }) => Promise<string>} [execGit]
71
+ * default: git/gitExec.cjs execGit
72
+ * @property {(absPath: string, maxBytes: number) => Promise<string>} [readFile]
73
+ * reads at most `maxBytes` from the start of a file (default: readHead)
74
+ * @property {(absPath: string) => Promise<boolean>} [exists] default: fs.promises.access
75
+ */
76
+
77
+ /** @param {unknown} err @returns {string} */
78
+ function errorText(err) {
79
+ return err instanceof Error ? err.message : String(err);
80
+ }
81
+
82
+ /** @param {unknown} err @param {'code' | 'stderrText'} key @returns {unknown} */
83
+ function errorField(err, key) {
84
+ return err !== null && typeof err === 'object' ? /** @type {Record<string, unknown>} */ (err)[key] : undefined;
85
+ }
86
+
87
+ /** @param {string} a @param {string} b @returns {number} */
88
+ function byCodeUnit(a, b) {
89
+ return a < b ? -1 : a > b ? 1 : 0;
90
+ }
91
+
92
+ /** Repo-relative POSIX form: no `./` or trailing `/`; `.` is the root folder. @param {string} p */
93
+ function toRepoPath(p) {
94
+ return path.posix.normalize(p).replace(/\/+$/, '') || '.';
95
+ }
96
+
97
+ /** @param {string} p @returns {string} the top-level folder, or `.` for a root-level path */
98
+ function topFolder(p) {
99
+ const slash = p.indexOf('/');
100
+ return slash === -1 ? '.' : p.slice(0, slash);
101
+ }
102
+
103
+ /** Every ancestor folder of `paths`. @param {Iterable<string>} paths @returns {Set<string>} */
104
+ function foldersOf(paths) {
105
+ /** @type {Set<string>} */
106
+ const folders = new Set();
107
+ for (const p of paths) {
108
+ for (let i = p.lastIndexOf('/'); i > 0; i = p.lastIndexOf('/', i - 1)) {
109
+ const folder = p.slice(0, i);
110
+ if (folders.has(folder)) break; // its ancestors are already in
111
+ folders.add(folder);
112
+ }
113
+ }
114
+ return folders;
115
+ }
116
+
117
+ /** @param {string} s @param {number} i @returns {number} the first index at or after `i` that is not a space/tab */
118
+ function skipBlanks(s, i) {
119
+ while (s[i] === ' ' || s[i] === '\t') i += 1;
120
+ return i;
121
+ }
122
+
123
+ /** @param {string} s @param {string} ch @param {number} from @returns {number} `ch`'s index within MAX_LINK_CHARS, or -1 */
124
+ function indexWithin(s, ch, from) {
125
+ const i = s.slice(from, from + MAX_LINK_CHARS).indexOf(ch);
126
+ return i === -1 ? -1 : from + i;
127
+ }
128
+
129
+ /**
130
+ * Parses an inline link's destination (+ optional title) starting just after `](`.
131
+ * @param {string} s
132
+ * @param {number} start
133
+ * @returns {{ target: string, end: number } | null} the raw target and the index after `)`
134
+ */
135
+ function parseDestination(s, start) {
136
+ let j = skipBlanks(s, start);
137
+ let target;
138
+ if (s[j] === '<') {
139
+ const close = indexWithin(s, '>', j + 1);
140
+ if (close === -1) return null;
141
+ target = s.slice(j + 1, close);
142
+ j = close + 1;
143
+ } else {
144
+ const from = j;
145
+ const limit = Math.min(s.length, from + MAX_LINK_CHARS);
146
+ let depth = 0;
147
+ for (; j < limit; j += 1) {
148
+ const c = s[j];
149
+ if (c === ' ' || c === '\t') break;
150
+ if (c === '(') depth += 1;
151
+ else if (c === ')') {
152
+ if (depth === 0) break;
153
+ depth -= 1;
154
+ }
155
+ }
156
+ if (j === limit && j < s.length) return null;
157
+ target = s.slice(from, j);
158
+ }
159
+ j = skipBlanks(s, j);
160
+ const quote = s[j];
161
+ if (quote === '"' || quote === "'" || quote === '(') {
162
+ const close = indexWithin(s, quote === '(' ? ')' : quote, j + 1);
163
+ if (close === -1) return null;
164
+ j = skipBlanks(s, close + 1);
165
+ }
166
+ return s[j] === ')' ? { target, end: j + 1 } : null;
167
+ }
168
+
169
+ /** Raw targets of one line's inline links, then of its `<x.md>` autolinks. @param {string} s @returns {string[]} */
170
+ function lineTargets(s) {
171
+ /** @type {string[]} */
172
+ const targets = [];
173
+ let outside = ''; // the line minus its inline links, so `[x](<a.md>)` is not also an autolink
174
+ let last = 0;
175
+ for (let i = s.indexOf(']('); i !== -1; ) {
176
+ const dest = parseDestination(s, i + 2);
177
+ if (dest) {
178
+ targets.push(dest.target);
179
+ outside += `${s.slice(last, i)} `;
180
+ last = dest.end;
181
+ i = s.indexOf('](', dest.end);
182
+ } else {
183
+ i = s.indexOf('](', i + 2);
184
+ }
185
+ }
186
+ outside += s.slice(last);
187
+ for (const m of outside.matchAll(AUTOLINK_RE)) {
188
+ if (MD_RE.test(m[1].replace(/[?#].*$/, ''))) targets.push(m[1]);
189
+ }
190
+ return targets;
191
+ }
192
+
193
+ /** Drops HTML comments (which may span lines) from one line. @param {string} line @param {LineState} state */
194
+ function stripComments(line, state) {
195
+ let out = '';
196
+ let i = 0;
197
+ while (i < line.length) {
198
+ if (state.inComment) {
199
+ const close = line.indexOf('-->', i);
200
+ if (close === -1) return out;
201
+ state.inComment = false;
202
+ i = close + 3;
203
+ } else {
204
+ const open = line.indexOf('<!--', i);
205
+ if (open === -1) return out + line.slice(i);
206
+ out += `${line.slice(i, open)} `;
207
+ state.inComment = true;
208
+ i = open + 4;
209
+ }
210
+ }
211
+ return out;
212
+ }
213
+
214
+ /** The part of one line that can hold links. @param {string} line @param {LineState} state @returns {string} */
215
+ function visibleText(line, state) {
216
+ const fence = state.inComment ? null : FENCE_RE.exec(line);
217
+ if (state.fence) {
218
+ if (fence && fence[1][0] === state.fence[0] && fence[1].length >= state.fence.length && fence[2].trim() === '') {
219
+ state.fence = '';
220
+ }
221
+ return '';
222
+ }
223
+ if (fence && !(fence[1][0] === '`' && fence[2].includes('`'))) {
224
+ state.fence = fence[1];
225
+ return '';
226
+ }
227
+ return stripComments(line.replace(INLINE_CODE_RE, ' '), state);
228
+ }
229
+
230
+ /**
231
+ * The followed link for one raw target written in doc `from`, or null when ignored.
232
+ * @param {string} from @param {string} raw @param {number} line 1-based
233
+ * @returns {MdLink | null}
234
+ */
235
+ function followLink(from, raw, line) {
236
+ const written = raw.trim();
237
+ if (written === '' || written[0] === '#' || written[0] === '/' || SCHEME_RE.test(written)) return null;
238
+ const target = written.replace(/[?#].*$/, '');
239
+ if (target === '') return null;
240
+ let decoded = target;
241
+ try {
242
+ decoded = decodeURIComponent(target);
243
+ } catch {
244
+ // a stray `%` is part of the file name
245
+ }
246
+ const to = toRepoPath(path.posix.join(path.posix.dirname(from), decoded));
247
+ return { line, target, to, escapes: to === '..' || to.startsWith('../') };
248
+ }
249
+
250
+ /**
251
+ * Memo for linksOf: scanMdNetwork walks the docs before buildMdNetwork does, so
252
+ * each doc is parsed once. File objects are treated as immutable.
253
+ * @type {WeakMap<MdFile, MdLink[]>}
254
+ */
255
+ const linkMemo = new WeakMap();
256
+
257
+ /** A doc's followed links, in document order. @param {MdFile} file @returns {MdLink[]} */
258
+ function linksOf(file) {
259
+ const memo = linkMemo.get(file);
260
+ if (memo) return memo;
261
+ const from = toRepoPath(file.path);
262
+ /** @type {MdLink[]} */
263
+ const links = [];
264
+ /** @type {LineState} */
265
+ const state = { fence: '', inComment: false };
266
+ const lines = file.text.split(/\r?\n/);
267
+ for (let n = 0; n < lines.length; n += 1) {
268
+ const visible = visibleText(lines[n], state);
269
+ if (visible === '') continue;
270
+ for (const raw of lineTargets(visible)) {
271
+ const link = followLink(from, raw, n + 1);
272
+ if (link) links.push(link);
273
+ }
274
+ }
275
+ linkMemo.set(file, links);
276
+ return links;
277
+ }
278
+
279
+ /** @param {string} id @param {number} depth @returns {MdNetworkNodeType} */
280
+ function nodeType(id, depth) {
281
+ if (depth === 0) return 'hub';
282
+ return depth === 1 && OWNER_NAMES.has(path.posix.basename(id)) ? 'owner' : 'doc';
283
+ }
284
+
285
+ /** @param {string} root @param {number} count @returns {string} */
286
+ function orphanDetail(root, count) {
287
+ return count === 1
288
+ ? `No link path from ${root} reaches this doc, so agents starting there never find it.`
289
+ : `No link path from ${root} reaches these ${count} docs, so agents starting there never find them.`;
290
+ }
291
+
292
+ /** @param {string} root @returns {MdNetworkResult} */
293
+ function missingRoot(root) {
294
+ return { ok: false, error: `no ${root} at the project root` };
295
+ }
296
+
297
+ /**
298
+ * Pure: the link network reachable from `root` over in-memory docs.
299
+ * `exists(relPath)` vouches for link targets that are neither one of `files`
300
+ * nor a folder holding one (code files, docs left unread, untracked files);
301
+ * without it such targets are missing.
302
+ * @param {{ files?: MdFile[], root?: string, exists?: (relPath: string) => boolean }} [input]
303
+ * @returns {MdNetworkResult}
304
+ */
305
+ function buildMdNetwork({ files = [], root = ROOT_DOC, exists } = {}) {
306
+ try {
307
+ const rootPath = toRepoPath(root);
308
+ /** @type {Map<string, MdFile>} */
309
+ const docs = new Map();
310
+ for (const file of files) {
311
+ if (file && typeof file.path === 'string' && typeof file.text === 'string') docs.set(toRepoPath(file.path), file);
312
+ }
313
+ if (!docs.has(rootPath)) return missingRoot(rootPath);
314
+ const folders = foldersOf(docs.keys());
315
+ /** @param {string} p */
316
+ const present = (p) => p === '.' || docs.has(p) || folders.has(p) || (exists !== undefined && exists(p) === true);
317
+
318
+ /** @type {Map<string, number>} */
319
+ const depth = new Map([[rootPath, 0]]);
320
+ const order = [rootPath]; // BFS order = node order
321
+ /** @type {MdNetworkEdge[]} */
322
+ const edges = [];
323
+ /** @type {MdNetworkFinding[]} */
324
+ const findings = [];
325
+ const edgeKeys = new Set();
326
+ const findingKeys = new Set();
327
+ /** @type {Map<string, number>} */
328
+ const linksOut = new Map();
329
+ /** @type {Map<string, number>} */
330
+ const linkedFrom = new Map();
331
+
332
+ for (let i = 0; i < order.length; i += 1) {
333
+ const from = order[i];
334
+ const file = docs.get(from);
335
+ if (!file) continue;
336
+ const nextDepth = (depth.get(from) ?? 0) + 1;
337
+ for (const link of linksOf(file)) {
338
+ const broken = link.escapes || !present(link.to);
339
+ if (broken) {
340
+ const where = `${from}:${link.line} → ${link.target}`;
341
+ if (!findingKeys.has(where)) {
342
+ findingKeys.add(where);
343
+ const detail = link.escapes ? DETAIL_ESCAPES : DETAIL_MISSING;
344
+ findings.push({ type: 'broken-link', file: from, line: link.line, target: link.target, to: link.to, where, detail });
345
+ }
346
+ } else if (link.to === from || !docs.has(link.to)) {
347
+ continue; // a self link, or a present target that is not a doc: no edge
348
+ }
349
+ const edgeKey = `${from}\0${link.to}`;
350
+ if (edgeKeys.has(edgeKey)) continue;
351
+ edgeKeys.add(edgeKey);
352
+ edges.push(broken ? { from, to: link.to, broken: true } : { from, to: link.to });
353
+ linksOut.set(from, (linksOut.get(from) ?? 0) + 1);
354
+ linkedFrom.set(link.to, (linkedFrom.get(link.to) ?? 0) + 1);
355
+ if (!broken && !depth.has(link.to)) {
356
+ depth.set(link.to, nextDepth);
357
+ order.push(link.to);
358
+ }
359
+ }
360
+ }
361
+
362
+ const nodes = order.map((id) => {
363
+ const d = depth.get(id) ?? 0;
364
+ return { id, path: id, depth: d, type: nodeType(id, d), linksOut: linksOut.get(id) ?? 0, linkedFrom: linkedFrom.get(id) ?? 0 };
365
+ });
366
+
367
+ /** @type {Map<string, string[]>} */
368
+ const orphans = new Map();
369
+ for (const p of docs.keys()) {
370
+ if (depth.has(p)) continue;
371
+ const top = topFolder(p);
372
+ const group = orphans.get(top);
373
+ if (group) group.push(p);
374
+ else orphans.set(top, [p]);
375
+ }
376
+ for (const [top, paths] of [...orphans].sort(([a], [b]) => byCodeUnit(a, b))) {
377
+ paths.sort(byCodeUnit);
378
+ findings.push({ type: 'orphan', where: `${top}/`, count: paths.length, paths, detail: orphanDetail(rootPath, paths.length) });
379
+ }
380
+
381
+ const scopes = [...new Set(order.map(topFolder))].filter((t) => t !== '.').sort(byCodeUnit).map((t) => `${t}/`);
382
+ return { ok: true, root: rootPath, nodes, edges, findings, docs: docs.size, links: edges.length, scopes };
383
+ } catch (err) {
384
+ return { ok: false, error: errorText(err) };
385
+ }
386
+ }
387
+
388
+ /**
389
+ * The first `maxBytes` of a file as UTF-8 (a character split at the cut decodes as U+FFFD).
390
+ * @param {string} absPath @param {number} maxBytes @returns {Promise<string>}
391
+ */
392
+ async function readHead(absPath, maxBytes) {
393
+ const handle = await fs.promises.open(absPath, 'r');
394
+ try {
395
+ const { size } = await handle.stat();
396
+ const buffer = Buffer.allocUnsafe(Math.min(size, maxBytes));
397
+ let filled = 0;
398
+ while (filled < buffer.length) {
399
+ const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);
400
+ if (bytesRead === 0) break;
401
+ filled += bytesRead;
402
+ }
403
+ return buffer.toString('utf8', 0, filled);
404
+ } finally {
405
+ await handle.close();
406
+ }
407
+ }
408
+
409
+ /** @param {string} absPath @returns {Promise<boolean>} */
410
+ function pathExists(absPath) {
411
+ return fs.promises.access(absPath).then(
412
+ () => true,
413
+ () => false,
414
+ );
415
+ }
416
+
417
+ /** The `fatal:`/`error:` line of a failed git call, else its first line. @param {unknown} err @returns {string} */
418
+ function gitFailure(err) {
419
+ const stderr = errorField(err, 'stderrText');
420
+ const text = (typeof stderr === 'string' && stderr.trim()) || errorText(err);
421
+ const lines = text
422
+ .split('\n')
423
+ .map((l) => l.trim())
424
+ .filter(Boolean);
425
+ return lines.find((l) => /^(fatal|error):/.test(l)) ?? lines[0] ?? 'unknown error';
426
+ }
427
+
428
+ /**
429
+ * I/O: scans the git project at `cwd` and builds its network. Never throws.
430
+ * @param {string} cwd the project root (`git ls-files` paths are relative to it)
431
+ * @param {ScanDeps} [deps] injectable I/O; defaults are git + async fs
432
+ * @returns {Promise<MdNetworkResult>}
433
+ */
434
+ async function scanMdNetwork(cwd, deps = {}) {
435
+ try {
436
+ if (typeof cwd !== 'string' || cwd === '') return { ok: false, error: 'cwd must be a non-empty path' };
437
+ /** @type {NonNullable<ScanDeps['execGit']>} */
438
+ const runGit = deps.execGit ?? execGit;
439
+ const readFile = deps.readFile ?? readHead;
440
+ const exists = deps.exists ?? pathExists;
441
+
442
+ let listing;
443
+ try {
444
+ listing = await runGit(cwd, ['ls-files', '-z'], { maxBuffer: LS_FILES_MAX_BUFFER });
445
+ } catch (err) {
446
+ return { ok: false, error: `git ls-files failed: ${gitFailure(err)}` };
447
+ }
448
+ const tracked = String(listing)
449
+ .split('\0')
450
+ .filter((p) => p !== '');
451
+ const trackedSet = new Set(tracked);
452
+ const trackedFolders = foldersOf(tracked);
453
+ const docPaths = tracked.filter((p) => MD_RE.test(p));
454
+ const docSet = new Set(docPaths);
455
+
456
+ /** @type {Set<string>} docs whose read was started; never more than MAX_DOCS */
457
+ const attempted = new Set();
458
+ /** @type {Set<string>} tracked docs missing on disk (deleted, not yet committed) */
459
+ const gone = new Set();
460
+
461
+ /** @param {string} rel @returns {Promise<MdFile | null>} */
462
+ const readOne = async (rel) => {
463
+ attempted.add(rel);
464
+ try {
465
+ const text = await readFile(path.join(cwd, rel), MAX_DOC_BYTES);
466
+ return { path: rel, text: typeof text === 'string' ? text.slice(0, MAX_DOC_BYTES) : '' };
467
+ } catch (err) {
468
+ if (MISSING_CODES.has(String(errorField(err, 'code')))) gone.add(rel);
469
+ else if (rel === ROOT_DOC) throw err;
470
+ return null; // an unreadable doc is skipped; links to it still count as present
471
+ }
472
+ };
473
+ /** @param {string[]} rels @returns {Promise<MdFile[]>} */
474
+ const readAll = async (rels) => {
475
+ /** @type {MdFile[]} */
476
+ const read = [];
477
+ for (let i = 0; i < rels.length; i += READ_BATCH) {
478
+ for (const file of await Promise.all(rels.slice(i, i + READ_BATCH).map(readOne))) {
479
+ if (file) read.push(file);
480
+ }
481
+ }
482
+ return read;
483
+ };
484
+
485
+ // The root is read straight from disk, so an untracked CLAUDE.md still counts.
486
+ const rootFile = await readOne(ROOT_DOC);
487
+ if (!rootFile) return missingRoot(ROOT_DOC);
488
+
489
+ // Breadth-first along links, so the cap never drops a reachable doc for an
490
+ // unreachable one; collect targets git does not vouch for along the way.
491
+ const files = [rootFile];
492
+ const queued = new Set([ROOT_DOC]);
493
+ /** @type {Set<string>} */
494
+ const unvouched = new Set();
495
+ for (let wave = [rootFile]; wave.length > 0; ) {
496
+ /** @type {string[]} */
497
+ const next = [];
498
+ for (const file of wave) {
499
+ for (const link of linksOf(file)) {
500
+ if (link.escapes || queued.has(link.to)) continue;
501
+ if (docSet.has(link.to)) {
502
+ queued.add(link.to);
503
+ next.push(link.to);
504
+ } else if (link.to !== '.' && !trackedSet.has(link.to) && !trackedFolders.has(link.to)) {
505
+ unvouched.add(link.to);
506
+ }
507
+ }
508
+ }
509
+ wave = await readAll(next.slice(0, Math.max(0, MAX_DOCS - attempted.size)));
510
+ files.push(...wave);
511
+ }
512
+
513
+ // The rest, shallowest first (stable sort keeps git's path order), for orphans.
514
+ const room = MAX_DOCS - attempted.size;
515
+ if (room > 0) {
516
+ const rest = docPaths
517
+ .filter((p) => !attempted.has(p))
518
+ .map((p) => ({ p, d: p.split('/').length }))
519
+ .sort((a, b) => a.d - b.d)
520
+ .slice(0, room)
521
+ .map(({ p }) => p);
522
+ files.push(...(await readAll(rest)));
523
+ }
524
+
525
+ // Untracked link targets (e.g. gitignored files) are checked on disk.
526
+ /** @type {Set<string>} */
527
+ const onDisk = new Set();
528
+ const candidates = [...unvouched];
529
+ /** @param {string} rel @returns {Promise<boolean>} */
530
+ const probe = async (rel) => {
531
+ try {
532
+ return (await exists(path.join(cwd, rel))) === true;
533
+ } catch {
534
+ return false;
535
+ }
536
+ };
537
+ for (let i = 0; i < candidates.length; i += READ_BATCH) {
538
+ const batch = candidates.slice(i, i + READ_BATCH);
539
+ const hits = await Promise.all(batch.map(probe));
540
+ batch.forEach((rel, k) => {
541
+ if (hits[k]) onDisk.add(rel);
542
+ });
543
+ }
544
+
545
+ return buildMdNetwork({
546
+ files,
547
+ root: ROOT_DOC,
548
+ exists: (p) => onDisk.has(p) || (!gone.has(p) && (trackedSet.has(p) || trackedFolders.has(p))),
549
+ });
550
+ } catch (err) {
551
+ return { ok: false, error: errorText(err) };
552
+ }
553
+ }
554
+
555
+ module.exports = { buildMdNetwork, scanMdNetwork };
@@ -46,10 +46,21 @@ const ProjectEntrySchema = z.string().refine(
46
46
  `must be "${ALL_PROJECTS}" or an absolute path`,
47
47
  );
48
48
 
49
+ // An OPEN project's absolute cwd — the key a per-project override is written
50
+ // and removed by (agentLibrary.cjs resolves it against openProjects by
51
+ // normalized cwd). Never a folder name: two open projects can share one.
52
+ const ProjectCwdSchema = z.string().min(1).max(4096).refine(
53
+ (/** @type {string} */ v) => isAbsoluteForPlatform(v),
54
+ 'must be an absolute path',
55
+ );
56
+
49
57
  // Mirrors AgentPersonaSaveInput (src/preload/api.d.ts). `tags` is the
50
58
  // Epic-mission WorkType union, NOT a free-form string list — the same
51
59
  // concept as PromptSessionSchema's `tag` / scheduleRetagPrd's `tag`, just
52
60
  // plural here since a persona can be associated with more than one mission.
61
+ // `.strict()`: an unknown key (e.g. the retired `projectName`) is REJECTED,
62
+ // not stripped — a stripped override key used to fall through to the GLOBAL
63
+ // write with the override call's blank description/tools/body.
53
64
  const AgentPersonaSaveSchema = z.object({
54
65
  name: PersonaNameSchema,
55
66
  // Previous filename, when renaming an existing persona. Omit when creating.
@@ -72,18 +83,18 @@ const AgentPersonaSaveSchema = z.object({
72
83
  action: z.string().max(20000).optional(),
73
84
  actionLabel: BoundedString.optional(),
74
85
  title: BoundedString.optional(),
75
- // Set = write this project's frontmatter-only override (model/effort only) instead of the global file.
76
- projectName: BoundedString.optional(),
86
+ // Set (an OPEN project's absolute cwd) = write that project's frontmatter-only
87
+ // override (model/effort only) instead of the global file.
88
+ projectCwd: ProjectCwdSchema.optional(),
77
89
  // Bundled-persona version stamp (seedAgentPersonas.cjs). Omit to carry over
78
90
  // the existing file's stamp unchanged — see agentLibrary.cjs's savePersona.
79
- // Without this field zod's default "strip unknown keys" behavior would
80
- // silently drop it from a save payload that did carry one.
91
+ // Without this field `.strict()` would reject a save payload that carried one.
81
92
  seedVersion: z.number().int().optional(),
82
93
  // Executor-only persona (e.g. dev-lead): New Epic warns when picked as the planning Actor. Never blocks.
83
94
  executorOnly: z.boolean().optional(),
84
95
  // Unbounded — a persona's body is arbitrary system-prompt prose.
85
96
  body: z.string(),
86
- });
97
+ }).strict();
87
98
 
88
99
  /**
89
100
  * Throws a clear, descriptive error (not a raw ZodError dump) when `persona`
@@ -106,4 +117,6 @@ module.exports = {
106
117
  AgentPersonaSaveSchema,
107
118
  assertValidAgentPersonaSave,
108
119
  isAbsoluteForPlatform,
120
+ PersonaNameSchema,
121
+ ProjectCwdSchema,
109
122
  };
@@ -31,7 +31,7 @@ const BUILTIN_MACROS = Object.freeze([
31
31
  tag: 'project-home-builder',
32
32
  surface: 'project-home',
33
33
  projects: ['*'],
34
- builtinVersion: 2,
34
+ builtinVersion: 3,
35
35
  job: Object.freeze({
36
36
  estimateMinutes: 20,
37
37
  entryKind: 'knowledge',
@@ -39,9 +39,10 @@ const BUILTIN_MACROS = Object.freeze([
39
39
  }),
40
40
  priorPrompts: Object.freeze([
41
41
  "Generate this project's Project Home page: one self-contained HTML overview (what it is, who it is for, key features, structure, how to run it, key commands), grounded only in what you read in the repository. Save it with a single project_home_write call.",
42
+ "Generate ONE Knowledge Page for this project as one self-contained HTML page, grounded only in what you read in the repository. The page is named on a 'Page: <name>' line in the additional instructions: Overview (the default when there is no Page line: what it is, who it is for, key features, structure, how to run it, key commands), How it works (architecture and main flows), FAQ (common questions with answers), or 'Custom topic: <text>' (a page about that topic). Build only that page; other pages stay untouched. Save it with a single project_page_write call, passing pageId equal to the id on the 'Entry id' line.",
42
43
  ]),
43
44
  prompt:
44
- "Generate ONE Knowledge Page for this project as one self-contained HTML page, grounded only in what you read in the repository. The page is named on a 'Page: <name>' line in the additional instructions: Overview (the default when there is no Page line: what it is, who it is for, key features, structure, how to run it, key commands), How it works (architecture and main flows), FAQ (common questions with answers), or 'Custom topic: <text>' (a page about that topic). Build only that page; other pages stay untouched. Save it with a single project_page_write call, passing pageId equal to the id on the 'Entry id' line.",
45
+ "Generate ONE Knowledge Page for this project as one self-contained HTML page, grounded only in what you read in the repository. The page is named on a 'Page: <name>' line in the additional instructions: Overview (the default when there is no Page line: what it is, who it is for, key features, structure, how to run it, key commands), How it works (architecture and main flows), FAQ (common questions with answers), or 'Custom topic: <text>' (a page about that topic). A 'Page: Overview' line means the same as no Page line. Write for the reader named on an 'Audience:' line: Newcomers (new to the project: plain words, every term explained), Users (people who use it: what it does for them and how to use it) or Contributors (people who work on its code: name the real files and modules); with no Audience line, write for Newcomers. Size the page to a 'Length:' line: Brief (only the essentials), Standard (the usual depth) or In-depth (thorough, with more sections and more detail); with no Length line, write a Standard page. Read only the sources named on a 'Read from:' line — README & docs, Source tree (the code, its manifest and directory layout) or Git log — and ground every claim in those alone; with 'Read from: nothing selected' or no Read from line, read any of the three. Build only that page; other pages stay untouched. Save it with a single project_page_write call, passing pageId equal to the id on the 'Entry id' line.",
45
46
  }),
46
47
  Object.freeze({
47
48
  id: 'builtin-demo-video',
@@ -50,7 +51,7 @@ const BUILTIN_MACROS = Object.freeze([
50
51
  tag: 'project-home-builder',
51
52
  surface: 'project-home',
52
53
  projects: ['*'],
53
- builtinVersion: 6,
54
+ builtinVersion: 7,
54
55
  job: Object.freeze({
55
56
  estimateMinutes: 60,
56
57
  entryKind: 'video',
@@ -62,9 +63,10 @@ const BUILTIN_MACROS = Object.freeze([
62
63
  'Generate a 30-second demo video for this project as one self-contained HTML/JavaScript animation that presents its main goals and key features, grounded only in what you read in the repository, with a matching on-device narration track: narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_demo_video_write call passing htmlPath.',
63
64
  "Generate a character and cute animated JavaScript video: a 30-second demo of this project as one self-contained HTML/JavaScript animation. Ground everything in what you read in the repository — invent an original mascot character whose look, name and personality match the project's theme and purpose, and tell the project's real goals and key features through it. The character, story and visuals must match the project's theme and purpose as read from the repository. Write the narration script first (hook, problem, solution, three features, call to action), then build every scene to match its line, with fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits the project. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_demo_video_write call passing htmlPath.",
64
65
  "Generate a character and cute animated JavaScript video: a demo of this project as one self-contained HTML/JavaScript animation, 60 seconds long when the additional instructions carry a 'Video length: 60' line and 30 seconds otherwise. Ground everything in what you read in the repository — invent an original mascot character whose look, name and personality match the project's theme and purpose, and tell the project's real goals and key features through it. The character, story and visuals must match the project's theme and purpose as read from the repository. Write the narration script first (hook, problem, solution, key features, call to action), then build every keystone to match its lines, with the pacing and fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits the project. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_demo_video_write call passing htmlPath.",
66
+ "Generate a character and cute animated JavaScript video as one self-contained HTML/JavaScript animation, 60 seconds long when the additional instructions carry a 'Video length: 60' line and 30 seconds otherwise. The video kind is named on a 'Video kind: <name>' line in the additional instructions: Blog post (a video that presents the blog post named on the 'Video target:' line — a post path in this repository or a URL; read it and tell its real content) or Feature (a video about the feature named on the 'Video target:' line, found in the repository); with no Video kind line, make a Project demo of the whole project's main goals and key features. Ground everything in what you read in the repository (and the target) — invent an original mascot character whose look, name and personality match the subject's theme and purpose, and tell its real story through it. Write the narration script first (hook, problem, solution, key points, call to action), then build every keystone to match its lines, with the pacing and fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_video_write call passing the htmlPath and the id on the 'Entry id' line.",
65
67
  ]),
66
68
  prompt:
67
- "Generate a character and cute animated JavaScript video as one self-contained HTML/JavaScript animation, 60 seconds long when the additional instructions carry a 'Video length: 60' line and 30 seconds otherwise. The video kind is named on a 'Video kind: <name>' line in the additional instructions: Blog post (a video that presents the blog post named on the 'Video target:' line — a post path in this repository or a URL; read it and tell its real content) or Feature (a video about the feature named on the 'Video target:' line, found in the repository); with no Video kind line, make a Project demo of the whole project's main goals and key features. Ground everything in what you read in the repository (and the target) — invent an original mascot character whose look, name and personality match the subject's theme and purpose, and tell its real story through it. Write the narration script first (hook, problem, solution, key points, call to action), then build every keystone to match its lines, with the pacing and fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_video_write call passing the htmlPath and the id on the 'Entry id' line.",
69
+ "Generate a character and cute animated JavaScript video as one self-contained HTML/JavaScript animation, 60 seconds long when the additional instructions carry a 'Video length: 60' line and 30 seconds otherwise; a 'Video length: 30' line means 30 seconds. The video kind is named on a 'Video kind: <name>' line in the additional instructions: Blog post (a video that presents the blog post named on the 'Video target:' line — a post path in this repository or a URL; read it and tell its real content) or Feature (a video about the feature named on the 'Video target:' line, found in the repository); with no Video kind line, make a Project demo of the whole project's main goals and key features. A 'Video kind: Project demo' line means that same whole-project demo. Ground everything in what you read in the repository (and the target) — invent an original mascot character whose look, name and personality match the subject's theme and purpose, and tell its real story through it. A 'Character: off' line means no mascot: make a type-led animation in the chosen style that tells the same real story through moving type and shapes, skip the character wherever the persona uses one (design, _character, project_character_write, lip-sync, the character self-check) and save meta.character as null; a 'Character: on' line or no Character line keeps the mascot. Write the narration script first (hook, problem, solution, key points, call to action), then build every keystone to match its lines, with the pacing and fun dynamic elements per the persona. Use the style named on a 'Video style: <name>' line in the additional instructions — Professional, Fun, Animated whiteboard, or Kinetic typography — otherwise pick the one that best fits. A 'Video style: Auto' line means the same: pick the style that best fits. Narrate with Kokoro (kokoro-onnx) using a natural female (af_heart) or male (am_michael) voice per the audio policy in the persona. Save it with a single project_video_write call passing the htmlPath and the id on the 'Entry id' line.",
68
70
  }),
69
71
  Object.freeze({
70
72
  id: 'builtin-review-md-network',