claude-code-session-manager 0.132.0 → 0.133.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 (84) hide show
  1. package/README.md +3 -3
  2. package/dist/assets/{AgentLibrary-C09MlPFx.js → AgentLibrary-DOAG-mcG.js} +1 -1
  3. package/dist/assets/{AppSettings-DvDKsCnD.js → AppSettings-BHKM_AKh.js} +2 -2
  4. package/dist/assets/{Button-BzG_KdBC.js → Button-CmO1wmPw.js} +1 -1
  5. package/dist/assets/{DocumentEditorPane-fm6zsnLM.js → DocumentEditorPane-8QMNrNRt.js} +1 -1
  6. package/dist/assets/{Extensions-DgxKT_OZ.js → Extensions-Boo21B3b.js} +2 -2
  7. package/dist/assets/{History-Nd3bKjBq.js → History-C4epd1hp.js} +1 -1
  8. package/dist/assets/{Library-R71t6VAB.js → Library-CrgzRQzL.js} +1 -1
  9. package/dist/assets/{ListDetail-CG50Ul7c.js → ListDetail-DA7y1DQ-.js} +1 -1
  10. package/dist/assets/{Panel-C7EFG4eU.js → Panel-D-WMBhKH.js} +1 -1
  11. package/dist/assets/{ProjectClaudeConfig-J92iNEGC.js → ProjectClaudeConfig-CuUADpIu.js} +1 -1
  12. package/dist/assets/{ProvenanceBadge-C3KB3ILO.js → ProvenanceBadge-B7AsoRk6.js} +1 -1
  13. package/dist/assets/{Scheduler-DeYBA7uc.js → Scheduler-C86gRh51.js} +1 -1
  14. package/dist/assets/{Settings-B6r7N4v-.js → Settings-B4Q9DwVS.js} +1 -1
  15. package/dist/assets/{SkillReferenceGraph-D7bt3fyB.js → SkillReferenceGraph-DX4ZgvlY.js} +1 -1
  16. package/dist/assets/{Skills-GpxtUrFP.js → Skills-DqKI37yi.js} +1 -1
  17. package/dist/assets/{SourceChip-uyVMCZc7.js → SourceChip-C974LROr.js} +1 -1
  18. package/dist/assets/{SystemPrompt-Cv25uFSM.js → SystemPrompt-C502jIwO.js} +1 -1
  19. package/dist/assets/{TiptapBody-uP8fJkbM.js → TiptapBody-DwNXN6Ki.js} +1 -1
  20. package/dist/assets/{Toggle-DRs80cX-.js → Toggle-C2OsxnPK.js} +1 -1
  21. package/dist/assets/{ViewTabs-BDkvvzJ8.js → ViewTabs-DBxKGbAK.js} +1 -1
  22. package/dist/assets/{VoiceButton-Cmtz2sQt.js → VoiceButton-C680wpmX.js} +1 -1
  23. package/dist/assets/{historyTotals-DHwAXunq.js → historyTotals-Cz-VYPEc.js} +1 -1
  24. package/dist/assets/{index-oXqzajWV.css → index-CMwAikUb.css} +1 -1
  25. package/dist/assets/index-Dh5geJe3.js +3111 -0
  26. package/dist/index.html +2 -2
  27. package/dist-web/app.css +1 -1
  28. package/dist-web/app.js +427 -413
  29. package/package.json +1 -1
  30. package/src/main/build-info.json +4 -4
  31. package/src/main/chatRunner.cjs +77 -14
  32. package/src/main/index.cjs +13 -0
  33. package/src/main/ipcSchemas.cjs +54 -0
  34. package/src/main/lib/CLAUDE.md +2 -0
  35. package/src/main/lib/agent-cli/adapters/antigravity.cjs +147 -0
  36. package/src/main/lib/agent-cli/adapters/codex.cjs +170 -0
  37. package/src/main/lib/agent-cli/adapters/cursor.cjs +138 -0
  38. package/src/main/lib/agent-cli/adapters/gemini.cjs +119 -0
  39. package/src/main/lib/agent-cli/adapters/opencode.cjs +117 -0
  40. package/src/main/lib/agent-cli/agentCliEvents.cjs +94 -0
  41. package/src/main/lib/agent-cli/agentCliIpc.cjs +109 -0
  42. package/src/main/lib/agent-cli/agentCliRegistry.cjs +213 -0
  43. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +152 -0
  44. package/src/main/lib/agent-cli/agentCliTurn.cjs +99 -0
  45. package/src/main/lib/app-preview/appPreviewIpc.cjs +125 -0
  46. package/src/main/lib/app-preview/appPreviewManager.cjs +317 -0
  47. package/src/main/lib/app-preview/appPreviewScripts.cjs +106 -0
  48. package/src/main/lib/app-preview/appPreviewSweep.cjs +92 -0
  49. package/src/main/lib/chatBootRecovery.cjs +41 -1
  50. package/src/main/lib/claude/agentEffortResolve.cjs +11 -3
  51. package/src/main/lib/epic/activeIndexMerge.cjs +25 -2
  52. package/src/main/lib/epic/archivedTranscript.cjs +39 -6
  53. package/src/main/lib/epic/epicChanges.cjs +466 -0
  54. package/src/main/lib/epic/epicMint.cjs +45 -1
  55. package/src/main/lib/epic/epicReopen.cjs +8 -2
  56. package/src/main/lib/epic/epicSpawnPlan.cjs +12 -0
  57. package/src/main/lib/epic/epicWorktreeMerge.cjs +39 -4
  58. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +9 -4
  59. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  60. package/src/main/lib/git/gitExec.cjs +9 -1
  61. package/src/main/lib/git/gitWorktree.cjs +94 -0
  62. package/src/main/lib/git/unifiedDiff.cjs +207 -0
  63. package/src/main/lib/mdDocCensus.cjs +364 -0
  64. package/src/main/lib/mdDocRefs.cjs +249 -0
  65. package/src/main/lib/mdNetworkScan.cjs +158 -15
  66. package/src/main/lib/persona-macro/macroJobDispatch.cjs +4 -1
  67. package/src/main/lib/persona-macro/macroJobIpc.cjs +1 -1
  68. package/src/main/lib/prd/prdCreate.cjs +7 -2
  69. package/src/main/lib/prd/prdFrontmatter.cjs +10 -3
  70. package/src/main/lib/promptSessionSchema.cjs +6 -0
  71. package/src/main/lib/remoteTranscriptTail.cjs +23 -4
  72. package/src/main/lib/scheduler/landedSinceRun.cjs +2 -1
  73. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  74. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  75. package/src/main/projectPages.cjs +14 -3
  76. package/src/main/scheduler/gitTreeGuard.cjs +2 -1
  77. package/src/main/scheduler/prdParser.cjs +2 -1
  78. package/src/main/scheduler.cjs +7 -2
  79. package/src/main/transcripts.cjs +18 -4
  80. package/src/main/webRemote.cjs +10 -5
  81. package/src/preload/api.d.ts +147 -2
  82. package/src/preload/apiSurface.json +56 -0
  83. package/src/preload/index.cjs +22 -0
  84. package/dist/assets/index-CBCdyHbZ.js +0 -3097
@@ -0,0 +1,364 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * mdDocCensus.cjs — a per-doc census of a project's tracked markdown: how agents
6
+ * meet each doc (role), whether it sits in a machine-written record collection,
7
+ * and when git last changed it. Pure — no I/O; the Review MD network scan runs
8
+ * git, reads the docs and hands the results in.
9
+ *
10
+ * Top-level in lib/ because no subfolder fits: it sits beside mdNetworkScan.cjs,
11
+ * the reader of the same docs network, and like it is neither project-pages/
12
+ * nor git/ (it only parses git's output) nor util/ (it is domain logic).
13
+ *
14
+ * - censusMdDocs(input) — roles, record collections, recency, counts.
15
+ * - parseGitLog(stdout) — `git log --max-count=2000 --no-renames
16
+ * --format=%x01%ct --name-only -z` stdout -> newest-first { ms, files }.
17
+ * - importsOf(text, fromPath) — the path.md imports (at-sign prefixed) a doc makes.
18
+ *
19
+ * Roles, by precedence: map (the root + its transitive imports, depth <= 5)
20
+ * > scoped (any other CLAUDE.md / AGENTS.md / CLAUDE.local.md) > agent
21
+ * (.claude/, skills/<x>/, plugins/<x>/agents|commands/) > record (in a record
22
+ * collection, unreachable, not a README/CLAUDE/AGENTS/index) > doc.
23
+ *
24
+ * Never throws on malformed input: invalid entries are skipped.
25
+ */
26
+
27
+ const path = require('node:path');
28
+
29
+ const ROOT_DOC = 'CLAUDE.md';
30
+ const MAX_IMPORT_DEPTH = 5;
31
+ const COLLECTION_MIN_DOCS = 20;
32
+ const COLLECTION_MAX_LINKED_SHARE = 0.05;
33
+ const WRITE_ONCE_MAX_COMMITS = 2;
34
+ const WRITE_ONCE_MIN_SHARE = 0.8;
35
+ const MAX_CODE_REF_FILES = 10;
36
+ const MAX_DEAD_REFS = 10;
37
+ const MAX_CHANGED_SINCE = 20;
38
+
39
+ const MD_RE = /\.md$/i;
40
+ const FENCE_RE = /^\s*(`{3,}|~{3,})(.*)$/;
41
+ const INLINE_CODE_RE = /(`+).{0,1024}?\1/g;
42
+ const IMPORT_RE = /(^|\s)@(\S+)/g;
43
+ const TRAILING_PUNCT_RE = /[),.;:!?'"\]]+$/;
44
+ const AGENT_RE = /(^|\/)\.claude\/|(^|\/)skills\/[^/]+\/|(^|\/)plugins\/[^/]+\/(agents|commands)\//;
45
+ const SCOPED_NAMES = new Set(['CLAUDE.md', 'AGENTS.md', 'CLAUDE.local.md']);
46
+ const NEVER_RECORD_NAMES = new Set(['README.md', 'CLAUDE.md', 'AGENTS.md', 'index.md']);
47
+
48
+ /**
49
+ * @typedef {'map' | 'scoped' | 'agent' | 'record' | 'doc'} MdDocRole
50
+ * @typedef {{ path: string, ms: number }} MdChangedSince
51
+ * @typedef {{ path: string, role: MdDocRole, depth: number | null, lines: number | null, bytes: number | null, lastCommitMs: number | null, commits: number, linkedFrom: number, codeRefs: number, codeRefFiles: string[], deadRefs: string[], changedSince: MdChangedSince[], collection: string | null }} MdDoc
52
+ * @typedef {{ folder: string, docs: number, linked: number, lastCommitMs: number | null, source: 'heuristic' | 'override' }} MdRecordCollection
53
+ * @typedef {{ tracked: number, network: number, records: number, unlinked: number, byRole: Record<MdDocRole, number> }} MdCensusCounts
54
+ * @typedef {{ docs: MdDoc[], collections: MdRecordCollection[], counts: MdCensusCounts, gitWindow: { commits: number, oldestMs: number | null }, warnings: string[] }} MdCensus
55
+ * @typedef {{ path: string, text?: string | null, lines?: number | null, bytes?: number | null }} MdCensusDocInput
56
+ * @typedef {{ ms: number, files: string[] }} GitLogEntry
57
+ * @typedef {{ deadRefs: string[], changedSince: MdChangedSince[] }} MdDocRefs
58
+ * @typedef {object} CensusInput
59
+ * @property {string} [root] the root doc (default CLAUDE.md)
60
+ * @property {MdCensusDocInput[]} docs every tracked .md, repo-relative POSIX
61
+ * @property {Map<string, { depth: number, linkedFrom: number }>} reachable docs links reach from the root
62
+ * @property {GitLogEntry[]} [log] newest first
63
+ * @property {Map<string, MdDocRefs>} [refs]
64
+ * @property {Map<string, string[]>} [codeMentions] doc path -> code files naming it
65
+ * @property {string[]} [recordFolders] folders forced to be record collections
66
+ * @property {string[]} [docFolders] folders (and subfolders) never record collections
67
+ */
68
+
69
+ /** @param {unknown} v @returns {v is number} */
70
+ function isFiniteNumber(v) {
71
+ return typeof v === 'number' && Number.isFinite(v);
72
+ }
73
+
74
+ /** @param {unknown} v @returns {number | null} */
75
+ function numOrNull(v) {
76
+ return isFiniteNumber(v) ? v : null;
77
+ }
78
+
79
+ /** @param {string} p @returns {string} the last path segment */
80
+ function baseName(p) {
81
+ return p.slice(p.lastIndexOf('/') + 1);
82
+ }
83
+
84
+ /** Folder form with a trailing slash, or '' for the repo root / invalid. @param {unknown} f @returns {string} */
85
+ function toFolder(f) {
86
+ if (typeof f !== 'string') return '';
87
+ const norm = path.posix.normalize(f.trim()).replace(/^\.\/+/, '').replace(/\/+$/, '');
88
+ if (!norm || norm === '.' || norm.startsWith('../') || norm === '..' || norm.startsWith('/')) return '';
89
+ return `${norm}/`;
90
+ }
91
+
92
+ /** Every ancestor folder of `p`, shallowest first, each with a trailing slash. @param {string} p @returns {string[]} */
93
+ function foldersOf(p) {
94
+ /** @type {string[]} */
95
+ const out = [];
96
+ for (let i = p.indexOf('/'); i > 0; i = p.indexOf('/', i + 1)) out.push(p.slice(0, i + 1));
97
+ return out;
98
+ }
99
+
100
+ /**
101
+ * The `@path.md` imports in `text`, outside fenced and inline code, resolved
102
+ * against `fromPath`'s folder. Skips `@~/...`, absolute and escaping targets.
103
+ * @param {string} text @param {string} fromPath @returns {string[]}
104
+ */
105
+ function importsOf(text, fromPath) {
106
+ if (typeof text !== 'string' || typeof fromPath !== 'string') return [];
107
+ const dir = path.posix.dirname(fromPath);
108
+ /** @type {string[]} */
109
+ const out = [];
110
+ const seen = new Set();
111
+ let fence = '';
112
+ for (const line of text.split(/\r?\n/)) {
113
+ const f = FENCE_RE.exec(line);
114
+ if (fence) {
115
+ if (f && f[1][0] === fence[0] && f[1].length >= fence.length && f[2].trim() === '') fence = '';
116
+ continue;
117
+ }
118
+ if (f && !(f[1][0] === '`' && f[2].includes('`'))) {
119
+ fence = f[1];
120
+ continue;
121
+ }
122
+ const visible = line.replace(INLINE_CODE_RE, ' ');
123
+ for (const m of visible.matchAll(IMPORT_RE)) {
124
+ const target = m[2].replace(TRAILING_PUNCT_RE, '');
125
+ if (!MD_RE.test(target) || target.startsWith('~') || target.startsWith('/')) continue;
126
+ const resolved = path.posix.normalize(path.posix.join(dir, target));
127
+ if (resolved === '..' || resolved.startsWith('../') || resolved.startsWith('/')) continue;
128
+ if (seen.has(resolved)) continue;
129
+ seen.add(resolved);
130
+ out.push(resolved);
131
+ }
132
+ }
133
+ return out;
134
+ }
135
+
136
+ /**
137
+ * Parse `git log --max-count=2000 --no-renames --format=%x01%ct --name-only -z`.
138
+ * @param {string} stdout @returns {GitLogEntry[]} newest first; [] when empty or unparseable
139
+ */
140
+ function parseGitLog(stdout) {
141
+ if (typeof stdout !== 'string' || !stdout.includes('\x01')) return [];
142
+ /** @type {GitLogEntry[]} */
143
+ const out = [];
144
+ const chunks = stdout.split('\x01');
145
+ for (let i = 1; i < chunks.length; i += 1) {
146
+ const m = /^(\d+)/.exec(chunks[i]);
147
+ if (!m) continue;
148
+ const ms = Number(m[1]) * 1000;
149
+ if (!Number.isFinite(ms)) continue;
150
+ const files = chunks[i]
151
+ .slice(m[1].length)
152
+ .split(/[\0\n]/)
153
+ .map((s) => s.trim())
154
+ .filter((s) => s !== '');
155
+ out.push({ ms, files });
156
+ }
157
+ return out;
158
+ }
159
+
160
+ /** @param {unknown} list @param {number} cap @returns {string[]} */
161
+ function stringList(list, cap) {
162
+ if (!Array.isArray(list)) return [];
163
+ return list.filter((s) => typeof s === 'string').slice(0, cap);
164
+ }
165
+
166
+ /** @param {unknown} list @returns {MdChangedSince[]} */
167
+ function changedSinceList(list) {
168
+ if (!Array.isArray(list)) return [];
169
+ /** @type {MdChangedSince[]} */
170
+ const out = [];
171
+ for (const e of list) {
172
+ if (out.length >= MAX_CHANGED_SINCE) break;
173
+ if (e && typeof e === 'object' && typeof e.path === 'string' && isFiniteNumber(e.ms)) out.push({ path: e.path, ms: e.ms });
174
+ }
175
+ return out;
176
+ }
177
+
178
+ /**
179
+ * The census of a project's tracked docs.
180
+ * @param {CensusInput} input @returns {MdCensus}
181
+ */
182
+ function censusMdDocs(input) {
183
+ const {
184
+ root = ROOT_DOC,
185
+ docs = [],
186
+ reachable = new Map(),
187
+ log = [],
188
+ refs,
189
+ codeMentions,
190
+ recordFolders = [],
191
+ docFolders = [],
192
+ } = input || /** @type {CensusInput} */ ({ docs: [], reachable: new Map() });
193
+ /** @type {string[]} */
194
+ const warnings = [];
195
+
196
+ // Valid, distinct docs in input order.
197
+ /** @type {MdCensusDocInput[]} */
198
+ const list = [];
199
+ const seen = new Set();
200
+ let invalid = 0;
201
+ for (const d of Array.isArray(docs) ? docs : []) {
202
+ if (!d || typeof d !== 'object' || typeof d.path !== 'string' || d.path === '') {
203
+ invalid += 1;
204
+ continue;
205
+ }
206
+ if (seen.has(d.path)) {
207
+ warnings.push(`Duplicate doc skipped: ${d.path}`);
208
+ continue;
209
+ }
210
+ seen.add(d.path);
211
+ list.push(d);
212
+ }
213
+ if (invalid > 0) warnings.push(`${invalid} invalid doc entr${invalid === 1 ? 'y' : 'ies'} skipped.`);
214
+ const reach = reachable instanceof Map ? reachable : new Map();
215
+
216
+ // Recency.
217
+ /** @type {Map<string, { last: number, commits: number }>} */
218
+ const recency = new Map();
219
+ let windowCommits = 0;
220
+ /** @type {number | null} */
221
+ let oldestMs = null;
222
+ for (const e of Array.isArray(log) ? log : []) {
223
+ if (!e || typeof e !== 'object' || !isFiniteNumber(e.ms) || !Array.isArray(e.files)) continue;
224
+ windowCommits += 1;
225
+ oldestMs = oldestMs === null ? e.ms : Math.min(oldestMs, e.ms);
226
+ for (const f of new Set(e.files)) {
227
+ if (typeof f !== 'string') continue;
228
+ const r = recency.get(f);
229
+ if (r) {
230
+ r.commits += 1;
231
+ r.last = Math.max(r.last, e.ms);
232
+ } else recency.set(f, { last: e.ms, commits: 1 });
233
+ }
234
+ }
235
+
236
+ // Map: root + transitive @-imports.
237
+ /** @type {Map<string, string | null | undefined>} */
238
+ const textOf = new Map(list.map((d) => [d.path, d.text]));
239
+ const mapSet = new Set();
240
+ if (typeof root === 'string' && textOf.has(root)) {
241
+ mapSet.add(root);
242
+ let frontier = [root];
243
+ for (let depth = 1; depth <= MAX_IMPORT_DEPTH && frontier.length > 0; depth += 1) {
244
+ /** @type {string[]} */
245
+ const next = [];
246
+ for (const from of frontier) {
247
+ const text = textOf.get(from);
248
+ if (typeof text !== 'string') continue;
249
+ for (const to of importsOf(text, from)) {
250
+ if (!textOf.has(to) || mapSet.has(to)) continue;
251
+ mapSet.add(to);
252
+ next.push(to);
253
+ }
254
+ }
255
+ frontier = next;
256
+ }
257
+ }
258
+ /** @param {string} p */
259
+ const isReachable = (p) => reach.has(p) || mapSet.has(p);
260
+
261
+ // Record collections.
262
+ const blocked = (Array.isArray(docFolders) ? docFolders : []).map(toFolder).filter(Boolean);
263
+ /** @param {string} folder */
264
+ const isBlocked = (folder) => blocked.some((b) => folder.startsWith(b));
265
+ /** @type {Map<string, { docs: number, linked: number, withCommits: number, writeOnce: number, last: number | null }>} */
266
+ const stats = new Map();
267
+ for (const d of list) {
268
+ const r = recency.get(d.path);
269
+ for (const folder of foldersOf(d.path)) {
270
+ let s = stats.get(folder);
271
+ if (!s) {
272
+ s = { docs: 0, linked: 0, withCommits: 0, writeOnce: 0, last: null };
273
+ stats.set(folder, s);
274
+ }
275
+ s.docs += 1;
276
+ if (isReachable(d.path)) s.linked += 1;
277
+ if (r) {
278
+ s.withCommits += 1;
279
+ if (r.commits <= WRITE_ONCE_MAX_COMMITS) s.writeOnce += 1;
280
+ s.last = s.last === null ? r.last : Math.max(s.last, r.last);
281
+ }
282
+ }
283
+ }
284
+ /** @type {MdRecordCollection[]} */
285
+ const collections = [];
286
+ /** @param {string} folder */
287
+ const insideChosen = (folder) => collections.some((c) => folder.startsWith(c.folder));
288
+ const overrides = [...new Set((Array.isArray(recordFolders) ? recordFolders : []).map(toFolder).filter(Boolean))].sort(
289
+ (a, b) => a.length - b.length,
290
+ );
291
+ for (const folder of overrides) {
292
+ if (insideChosen(folder)) continue;
293
+ const s = stats.get(folder);
294
+ if (!s) warnings.push(`Record folder override matches no doc: ${folder}`);
295
+ collections.push({ folder, docs: s ? s.docs : 0, linked: s ? s.linked : 0, lastCommitMs: s ? s.last : null, source: 'override' });
296
+ }
297
+ const candidates = [...stats.keys()].sort((a, b) => a.split('/').length - b.split('/').length || (a < b ? -1 : a > b ? 1 : 0));
298
+ for (const folder of candidates) {
299
+ if (isBlocked(folder) || insideChosen(folder) || overrides.some((o) => o.startsWith(folder))) continue;
300
+ const s = /** @type {NonNullable<ReturnType<typeof stats.get>>} */ (stats.get(folder));
301
+ if (s.docs < COLLECTION_MIN_DOCS || s.linked > s.docs * COLLECTION_MAX_LINKED_SHARE) continue;
302
+ if (s.withCommits > 0 && s.writeOnce < s.withCommits * WRITE_ONCE_MIN_SHARE) continue;
303
+ collections.push({ folder, docs: s.docs, linked: s.linked, lastCommitMs: s.last, source: 'heuristic' });
304
+ }
305
+ collections.sort((a, b) => b.docs - a.docs || (a.folder < b.folder ? -1 : a.folder > b.folder ? 1 : 0));
306
+ /** @param {string} p @returns {string | null} */
307
+ const collectionOf = (p) => {
308
+ const c = collections.find((col) => p.startsWith(col.folder));
309
+ return c ? c.folder : null;
310
+ };
311
+
312
+ // Per-doc rows.
313
+ /** @type {Record<MdDocRole, number>} */
314
+ const byRole = { map: 0, scoped: 0, agent: 0, record: 0, doc: 0 };
315
+ let network = 0;
316
+ let unlinked = 0;
317
+ /** @type {MdDoc[]} */
318
+ const out = [];
319
+ for (const d of list) {
320
+ const p = d.path;
321
+ const name = baseName(p);
322
+ const hit = reach.get(p);
323
+ const depth = hit && isFiniteNumber(hit.depth) ? hit.depth : null;
324
+ const reachableDoc = isReachable(p);
325
+ const folder = collectionOf(p);
326
+ /** @type {MdDocRole} */
327
+ let role = 'doc';
328
+ if (mapSet.has(p)) role = 'map';
329
+ else if (SCOPED_NAMES.has(name)) role = 'scoped';
330
+ else if (AGENT_RE.test(p)) role = 'agent';
331
+ else if (folder && !reachableDoc && !NEVER_RECORD_NAMES.has(name)) role = 'record';
332
+ byRole[role] += 1;
333
+ if (reachableDoc) network += 1;
334
+ if (role === 'doc' && depth === null) unlinked += 1;
335
+ const r = recency.get(p);
336
+ const mentions = codeMentions instanceof Map ? stringList(codeMentions.get(p), Infinity) : [];
337
+ const ref = refs instanceof Map ? refs.get(p) : undefined;
338
+ out.push({
339
+ path: p,
340
+ role,
341
+ depth,
342
+ lines: numOrNull(d.lines),
343
+ bytes: numOrNull(d.bytes),
344
+ lastCommitMs: r ? r.last : null,
345
+ commits: r ? r.commits : 0,
346
+ linkedFrom: hit && isFiniteNumber(hit.linkedFrom) ? hit.linkedFrom : 0,
347
+ codeRefs: mentions.length,
348
+ codeRefFiles: mentions.slice(0, MAX_CODE_REF_FILES),
349
+ deadRefs: ref ? stringList(ref.deadRefs, MAX_DEAD_REFS) : [],
350
+ changedSince: ref ? changedSinceList(ref.changedSince) : [],
351
+ collection: role === 'record' ? folder : null,
352
+ });
353
+ }
354
+
355
+ return {
356
+ docs: out,
357
+ collections,
358
+ counts: { tracked: out.length, network, records: byRole.record, unlinked, byRole },
359
+ gitWindow: { commits: windowCommits, oldestMs },
360
+ warnings,
361
+ };
362
+ }
363
+
364
+ module.exports = { censusMdDocs, parseGitLog, importsOf };
@@ -0,0 +1,249 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * mdDocRefs — pure helpers for a markdown doc's currency and usage:
6
+ * - backtickPaths: the repo-path-shaped inline-code tokens a doc names;
7
+ * - assessRefs: which named paths no longer exist, and which existing files
8
+ * were committed after the doc last changed;
9
+ * - mentionPatterns / parseMentions: the fixed-string patterns for a
10
+ * `git grep -F -o --null` run and the parse of its output into
11
+ * doc -> code files that name it.
12
+ * No fs, no git: all IO is injected (`exists`, `lastCommitOf`) or done by the
13
+ * caller (scanMdNetwork). Fence/comment handling mirrors mdNetworkScan.cjs.
14
+ */
15
+
16
+ const path = require('node:path');
17
+
18
+ const MAX_TOKENS = 200;
19
+ const MAX_CHANGED = 20;
20
+ const MAX_PATTERNS = 4000;
21
+
22
+ const FENCE_RE = /^\s*(`{3,}|~{3,})(.*)$/;
23
+ const INLINE_CODE_RE = /(`+)(.{0,1024}?)\1/g;
24
+ const BAD_START_RE = /^(?:[/~$<]|http)/i;
25
+ const BAD_CHAR_RE = /[*{}<>:]/;
26
+ const EXT_RE = /\.[A-Za-z0-9]{1,8}$/;
27
+
28
+ /**
29
+ * @typedef {{ fence: string, inComment: boolean }} LineState
30
+ * @typedef {{ path: string, ms: number }} ChangedRef
31
+ * @typedef {{
32
+ * docPath: string,
33
+ * linkTargets: string[],
34
+ * tokens: string[],
35
+ * docMs: number | null,
36
+ * exists: (repoPath: string) => boolean,
37
+ * lastCommitOf: (repoPath: string) => number | null | undefined,
38
+ * }} AssessInput
39
+ */
40
+
41
+ /** Drops HTML comments (which may span lines) from one line. @param {string} line @param {LineState} state */
42
+ function stripComments(line, state) {
43
+ let out = '';
44
+ let i = 0;
45
+ while (i < line.length) {
46
+ if (state.inComment) {
47
+ const close = line.indexOf('-->', i);
48
+ if (close === -1) return out;
49
+ state.inComment = false;
50
+ i = close + 3;
51
+ } else {
52
+ const open = line.indexOf('<!--', i);
53
+ if (open === -1) return out + line.slice(i);
54
+ out += `${line.slice(i, open)} `;
55
+ state.inComment = true;
56
+ i = open + 4;
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /** One line outside fences, comments removed (inline code kept). @param {string} line @param {LineState} state */
63
+ function visibleLine(line, state) {
64
+ const fence = state.inComment ? null : FENCE_RE.exec(line);
65
+ if (state.fence) {
66
+ if (fence && fence[1][0] === state.fence[0] && fence[1].length >= state.fence.length && fence[2].trim() === '') {
67
+ state.fence = '';
68
+ }
69
+ return '';
70
+ }
71
+ if (fence && !(fence[1][0] === '`' && fence[2].includes('`'))) {
72
+ state.fence = fence[1];
73
+ return '';
74
+ }
75
+ return stripComments(line, state);
76
+ }
77
+
78
+ /** The repo-path form of one inline-code token, or null. @param {string} raw @returns {string | null} */
79
+ function pathToken(raw) {
80
+ const t = raw.trim();
81
+ if (t === '' || !t.includes('/') || /\s/.test(t) || BAD_START_RE.test(t)) return null;
82
+ const bare = t.replace(/:\d+$/, '').replace(/#.*$/, '');
83
+ if (bare === '' || BAD_CHAR_RE.test(bare)) return null;
84
+ if (!bare.endsWith('/') && !EXT_RE.test(bare)) return null;
85
+ return bare;
86
+ }
87
+
88
+ /**
89
+ * Distinct path-shaped inline-code tokens outside fenced code and HTML comments,
90
+ * in document order, at most MAX_TOKENS. O(text length).
91
+ * @param {string} text
92
+ * @returns {string[]}
93
+ */
94
+ function backtickPaths(text) {
95
+ if (typeof text !== 'string' || text === '') return [];
96
+ /** @type {LineState} */
97
+ const state = { fence: '', inComment: false };
98
+ const seen = new Set();
99
+ /** @type {string[]} */
100
+ const out = [];
101
+ for (const line of text.split(/\r?\n/)) {
102
+ const visible = visibleLine(line, state);
103
+ if (visible === '' || !visible.includes('`')) continue;
104
+ for (const m of visible.matchAll(INLINE_CODE_RE)) {
105
+ const tok = pathToken(m[2]);
106
+ if (tok === null || seen.has(tok)) continue;
107
+ seen.add(tok);
108
+ out.push(tok);
109
+ if (out.length >= MAX_TOKENS) return out;
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+
115
+ /** Normalised repo path, or null when it escapes the repo. @param {string} p @returns {string | null} */
116
+ function repoPath(p) {
117
+ const n = path.posix.normalize(p).replace(/\/+$/, '');
118
+ if (n === '' || n === '.' || n === '..' || n.startsWith('../')) return null;
119
+ return n;
120
+ }
121
+
122
+ /**
123
+ * Dead refs (tokens that resolve nowhere) and existing file refs committed
124
+ * after the doc (newest first, at most MAX_CHANGED).
125
+ * @param {AssessInput} input
126
+ * @returns {{ deadRefs: string[], changedSince: ChangedRef[] }}
127
+ */
128
+ function assessRefs({ docPath, linkTargets, tokens, docMs, exists, lastCommitOf }) {
129
+ const dir = path.posix.dirname(docPath);
130
+ /** @type {string[]} */
131
+ const deadRefs = [];
132
+ const deadSeen = new Set();
133
+ /** @type {string[]} */
134
+ const fileRefs = [];
135
+ const fileSeen = new Set();
136
+ /** @param {string} p */
137
+ const addFile = (p) => {
138
+ if (p === docPath || fileSeen.has(p)) return;
139
+ fileSeen.add(p);
140
+ fileRefs.push(p);
141
+ };
142
+ for (const t of Array.isArray(linkTargets) ? linkTargets : []) {
143
+ const p = typeof t === 'string' ? repoPath(t) : null;
144
+ if (p) addFile(p);
145
+ }
146
+ for (const tok of Array.isArray(tokens) ? tokens : []) {
147
+ if (typeof tok !== 'string' || tok === '') continue;
148
+ const isFolder = tok.endsWith('/');
149
+ const root = repoPath(tok);
150
+ const local = dir === '.' ? null : repoPath(path.posix.join(dir, tok));
151
+ const candidates = [root, local].filter((c) => c !== null);
152
+ if (candidates.length === 0) continue;
153
+ const hit = candidates.find((c) => exists(c));
154
+ if (hit === undefined) {
155
+ const dead = /** @type {string} */ (root ?? candidates[0]);
156
+ if (!deadSeen.has(dead)) {
157
+ deadSeen.add(dead);
158
+ deadRefs.push(dead);
159
+ }
160
+ continue;
161
+ }
162
+ if (!isFolder) addFile(hit);
163
+ }
164
+ /** @type {ChangedRef[]} */
165
+ const changed = [];
166
+ for (const p of fileRefs) {
167
+ const ms = lastCommitOf(p);
168
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) continue;
169
+ if (docMs === null || docMs === undefined || ms > docMs) changed.push({ path: p, ms });
170
+ }
171
+ changed.sort((a, b) => b.ms - a.ms || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
172
+ return { deadRefs, changedSince: changed.slice(0, MAX_CHANGED) };
173
+ }
174
+
175
+ /**
176
+ * Fixed-string patterns naming each doc: its full path, plus parent/basename
177
+ * when the path has 3+ segments and no other doc shares that suffix.
178
+ * @param {string[]} docPaths
179
+ * @returns {{ patterns: string[], owner: Map<string, string> }}
180
+ */
181
+ function mentionPatterns(docPaths) {
182
+ const docs = [...new Set((Array.isArray(docPaths) ? docPaths : []).filter((p) => typeof p === 'string' && p !== ''))];
183
+ /** @type {Map<string, Set<string>>} */
184
+ const claims = new Map();
185
+ /** @param {string} pattern @param {string} doc */
186
+ const claim = (pattern, doc) => {
187
+ const set = claims.get(pattern) ?? new Set();
188
+ set.add(doc);
189
+ claims.set(pattern, set);
190
+ };
191
+ /** @type {[string, string, boolean][]} pattern, doc, isSuffix */
192
+ const ordered = [];
193
+ for (const doc of docs) {
194
+ claim(doc, doc);
195
+ ordered.push([doc, doc, false]);
196
+ const segs = doc.split('/');
197
+ if (segs.length >= 3) {
198
+ const suffix = segs.slice(-2).join('/');
199
+ claim(suffix, doc);
200
+ ordered.push([suffix, doc, true]);
201
+ }
202
+ }
203
+ /** @type {string[]} */
204
+ const patterns = [];
205
+ /** @type {Map<string, string>} */
206
+ const owner = new Map();
207
+ for (const [pattern, doc, isSuffix] of ordered) {
208
+ if (patterns.length >= MAX_PATTERNS) break;
209
+ if (owner.has(pattern)) continue;
210
+ if (isSuffix && /** @type {Set<string>} */ (claims.get(pattern)).size >= 2) continue;
211
+ patterns.push(pattern);
212
+ owner.set(pattern, doc);
213
+ }
214
+ return { patterns, owner };
215
+ }
216
+
217
+ /**
218
+ * Parse `git grep --no-color -I -F -o --null -e <p>...` output ('<file>\0<match>'
219
+ * per line) into doc path -> distinct code files, first-seen order. Never throws.
220
+ * @param {string} stdout
221
+ * @param {Map<string, string>} owner
222
+ * @returns {Map<string, string[]>}
223
+ */
224
+ function parseMentions(stdout, owner) {
225
+ /** @type {Map<string, string[]>} */
226
+ const out = new Map();
227
+ if (typeof stdout !== 'string' || !(owner instanceof Map)) return out;
228
+ /** @type {Map<string, Set<string>>} */
229
+ const seen = new Map();
230
+ for (const line of stdout.split('\n')) {
231
+ const nul = line.indexOf('\0');
232
+ if (nul < 1) continue;
233
+ const file = line.slice(0, nul);
234
+ const doc = owner.get(line.slice(nul + 1).replace(/\r$/, ''));
235
+ if (doc === undefined) continue;
236
+ let files = seen.get(doc);
237
+ if (!files) {
238
+ files = new Set();
239
+ seen.set(doc, files);
240
+ out.set(doc, []);
241
+ }
242
+ if (files.has(file)) continue;
243
+ files.add(file);
244
+ /** @type {string[]} */ (out.get(doc)).push(file);
245
+ }
246
+ return out;
247
+ }
248
+
249
+ module.exports = { backtickPaths, assessRefs, mentionPatterns, parseMentions };