claude-code-session-manager 0.139.0 → 0.141.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 (154) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-DExeJhqQ.js +2 -0
  3. package/dist/assets/History-DJMiuXyK.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-CTp2tkZ4.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-Bf1Cf8UL.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-BWPpypf9.js} +1 -1
  7. package/dist/assets/Scheduler-cyr61UAC.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-Ba4TkX2C.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-C1v91GEO.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-BrcWVpiW.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-DXhOWFG0.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-qivnDV6K.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-CMCPTKqC.js} +1 -1
  14. package/dist/assets/index-B2TQz3nd.js +3121 -0
  15. package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +423 -426
  19. package/package.json +5 -2
  20. package/plugins/AGENTS.md +60 -0
  21. package/plugins/CLAUDE.md +1 -60
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +29 -19
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  33. package/scripts/README.md +1 -0
  34. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  35. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  36. package/scripts/ops-sweep.cjs +53 -23
  37. package/scripts/scheduler-mcp-server.cjs +205 -18
  38. package/src/main/build-info.json +4 -4
  39. package/src/main/config.cjs +112 -8
  40. package/src/main/docEdit.cjs +6 -1
  41. package/src/main/files.cjs +7 -27
  42. package/src/main/health.cjs +48 -15
  43. package/src/main/historyAggregator.cjs +88 -5
  44. package/src/main/historyDashboard.cjs +69 -4
  45. package/src/main/index.cjs +56 -2
  46. package/src/main/ipcSchemas.cjs +122 -16
  47. package/src/main/lib/AGENTS.md +54 -0
  48. package/src/main/lib/CLAUDE.md +1 -54
  49. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  50. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  51. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  52. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  53. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  54. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  55. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  56. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  57. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  58. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  59. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  60. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  61. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  62. package/src/main/lib/ephemeralCwd.cjs +37 -2
  63. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  64. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  65. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  66. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  67. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  68. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  69. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  70. package/src/main/lib/externalContract.cjs +31 -5
  71. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  72. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  73. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  74. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  75. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  76. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  77. package/src/main/lib/git/branchSweep.cjs +209 -4
  78. package/src/main/lib/git/gitWorktree.cjs +41 -5
  79. package/src/main/lib/guardShims.cjs +1 -1
  80. package/src/main/lib/historyRollup.cjs +26 -0
  81. package/src/main/lib/insideHome.cjs +27 -1
  82. package/src/main/lib/mcpToolCatalog.cjs +132 -13
  83. package/src/main/lib/mdDocCensus.cjs +59 -78
  84. package/src/main/lib/mdDocRefs.cjs +71 -93
  85. package/src/main/lib/mdNetworkScan.cjs +245 -250
  86. package/src/main/lib/mdReviewRecord.cjs +22 -9
  87. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  88. package/src/main/lib/opsOwnership.cjs +18 -2
  89. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  90. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  91. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  92. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  93. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  94. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  95. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  96. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  97. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  98. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  99. package/src/main/lib/prd/prdCreate.cjs +377 -23
  100. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  101. package/src/main/lib/prd/prdFrontmatter.cjs +121 -3
  102. package/src/main/lib/process/loginItem.cjs +171 -0
  103. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  104. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  105. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  106. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  107. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  108. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  109. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  110. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  111. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  112. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  113. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  114. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  115. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  116. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  117. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  118. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  119. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  120. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  121. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  122. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  123. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  124. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  125. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  126. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  127. package/src/main/lib/tasks/taskRun.cjs +313 -0
  128. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  129. package/src/main/loginItemIpc.cjs +35 -0
  130. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  131. package/src/main/projectPages.cjs +6 -15
  132. package/src/main/promptSessionEvents.cjs +9 -1
  133. package/src/main/queueOps.cjs +260 -3
  134. package/src/main/runVerify.cjs +53 -25
  135. package/src/main/scheduler/AGENTS.md +26 -0
  136. package/src/main/scheduler/CLAUDE.md +1 -26
  137. package/src/main/scheduler/budget.cjs +239 -9
  138. package/src/main/scheduler/cancelDependents.cjs +154 -0
  139. package/src/main/scheduler/prdParser.cjs +19 -1
  140. package/src/main/scheduler/reviewLadder.cjs +36 -3
  141. package/src/main/scheduler/starvation.cjs +89 -18
  142. package/src/main/scheduler.cjs +1080 -89
  143. package/src/main/supervisor.cjs +5 -1
  144. package/src/main/templates/PRD_AUTHORING.md +14 -1
  145. package/src/main/validationQualityHandlers.cjs +199 -0
  146. package/src/main/webRemote.cjs +10 -2
  147. package/src/preload/api.d.ts +364 -21
  148. package/src/preload/apiSurface.json +89 -10
  149. package/src/preload/index.cjs +23 -2
  150. package/src/seed/agents/validator.md +19 -8
  151. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  152. package/dist/assets/History-DDnqaLyw.js +0 -2
  153. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  154. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -4,10 +4,16 @@
4
4
  * drift-check.cjs — dependency-free drift check for a repo's markdown network.
5
5
  *
6
6
  * node drift-check.cjs [--root <dir>] [--map <path>] [--file <path>]...
7
- * [--exclude <prefix>]... [--checks links,paths,limits,contents[,orphans]] [--strict-paths]
7
+ * [--exclude <prefix>]... [--checks links,paths,limits,contents,pairs[,orphans][,duplicates]] [--strict-paths]
8
+ *
9
+ * `pairs` (default) checks the AGENTS.md pair layout: a CLAUDE.md beside an AGENTS.md must open
10
+ * with `@AGENTS.md`, a nested AGENTS.md needs a CLAUDE.md stub beside it when the repo root has a
11
+ * CLAUDE.md, and no line may be kept in both files of a pair.
8
12
  *
9
13
  * `orphans` is opt-in (not in the default set): docs no chain of references from the root
10
- * CLAUDE.md reaches, by the maintaining-md-network SKILL.md link convention.
14
+ * CLAUDE.md reaches, by the maintaining-md-network SKILL.md link convention. `duplicates` is opt-in
15
+ * too: pairs of checked docs sharing the same text, from mdDuplicates.findDuplicates (the function
16
+ * the app's src/main/lib/mdNetworkScan.cjs runs).
11
17
  *
12
18
  * Prints one JSON object { root, map, notes, findings, counts, checkedFiles } to stdout.
13
19
  * Exit 0 = no findings, 1 = findings, 2 = usage error / missing root.
@@ -16,9 +22,13 @@
16
22
  const fs = require('fs');
17
23
  const path = require('path');
18
24
  const { spawnSync } = require('child_process');
25
+ // The link convention (links, imports, backticked paths; code and comments skipped) is written
26
+ // once, in the sibling mdLinks.cjs — same folder, so this script stays dependency-free.
27
+ const { linksOf, rawLinksOf, visibleLine, importsOf, backtickPaths, toRepoPath, isAgentsStub } = require('./mdLinks.cjs');
28
+ const { findDuplicates, normalize } = require('./mdDuplicates.cjs');
19
29
 
20
- const ALL_CHECKS = ['links', 'paths', 'limits', 'contents', 'orphans'];
21
- const DEFAULT_CHECKS = ['links', 'paths', 'limits', 'contents'];
30
+ const ALL_CHECKS = ['links', 'paths', 'limits', 'contents', 'pairs', 'orphans', 'duplicates'];
31
+ const DEFAULT_CHECKS = ['links', 'paths', 'limits', 'contents', 'pairs'];
22
32
  const LIMIT_ALWAYS_LOADED = 200;
23
33
  const LIMIT_MAP = 70;
24
34
  const CONTENTS_MIN_LINES = 100;
@@ -99,14 +109,10 @@ function listDocs(root) {
99
109
  return { git: false, files: out };
100
110
  }
101
111
 
102
- /** Blank out inline code spans (keeps length) so links inside them are ignored. */
103
- function blankCode(line) {
104
- return line.replace(/`[^`]*`/g, (m) => ' '.repeat(m.length));
105
- }
106
-
107
112
  const IGNORE_MARKER = '<!-- drift-check-ignore -->';
108
113
  const DOMAIN_RE = /^([a-z0-9-]+\.)+[a-z]{2,}$/i;
109
114
  const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
115
+ const SPAN_RE = /`([^`]+)`/g;
110
116
 
111
117
  function isRepoPathCandidate(span) {
112
118
  if (!span.includes('/')) return false;
@@ -120,115 +126,46 @@ function isRepoPathCandidate(span) {
120
126
  return true;
121
127
  }
122
128
 
123
- /** Parse a doc once: returns { lines, links, spans }. */
129
+ /**
130
+ * Parse a doc once for the links / paths / contents checks: its lines, every link destination
131
+ * as written (mdLinks.rawLinksOf), the inline code spans on lines outside fences and comments
132
+ * (mdLinks.visibleLine), and the lines carrying the ignore marker.
133
+ */
124
134
  function parseDoc(text) {
125
- const rawLines = text.split('\n');
126
- const links = [];
135
+ const lines = text.split('\n');
127
136
  const spans = [];
128
- const importTokens = [];
129
- const autolinks = [];
130
- const refTokens = [];
131
137
  const ignoredLines = new Set();
132
- let fence = null;
133
- let inComment = false;
134
- rawLines.forEach((raw, idx) => {
138
+ const state = { fence: '', inComment: false };
139
+ lines.forEach((raw, idx) => {
135
140
  const lineNo = idx + 1;
136
- const fm = /^\s*(```+|~~~+)/.exec(raw);
137
- if (!inComment && fm) {
138
- const marker = fm[1][0];
139
- if (fence === null) fence = marker;
140
- else if (fence === marker) fence = null;
141
- return;
142
- }
143
- if (fence !== null) return;
144
141
  if (raw.includes(IGNORE_MARKER)) ignoredLines.add(lineNo);
145
- // strip HTML comments (possibly spanning lines)
146
- let line = '';
147
- let rest = raw;
148
- while (rest.length) {
149
- if (inComment) {
150
- const end = rest.indexOf('-->');
151
- if (end === -1) { rest = ''; break; }
152
- rest = rest.slice(end + 3);
153
- inComment = false;
154
- } else {
155
- const start = rest.indexOf('<!--');
156
- if (start === -1) { line += rest; rest = ''; break; }
157
- line += rest.slice(0, start);
158
- rest = rest.slice(start + 4);
159
- inComment = true;
160
- }
161
- }
162
- const noCode = blankCode(line);
163
- const linkRe = /!?\[[^\]]*\]\(\s*(<[^>]*>|[^)\s]+)(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/g;
164
- let m;
165
- while ((m = linkRe.exec(noCode))) {
166
- let t = m[1];
167
- if (t.startsWith('<') && t.endsWith('>')) t = t.slice(1, -1);
168
- links.push({ line: lineNo, target: t });
169
- }
170
- for (const am of noCode.replace(linkRe, ' ').matchAll(AUTOLINK_RE)) {
171
- if (/\.md$/i.test(am[1].replace(/[?#].*$/, ''))) autolinks.push({ line: lineNo, target: am[1] });
172
- }
173
- for (const cm of line.matchAll(MULTI_CODE_RE)) {
174
- const tok = pathToken(cm[2]);
175
- if (tok !== null && !refTokens.includes(tok)) refTokens.push(tok);
176
- }
177
- const impRe = /(?:^|\s)@(\S+)/g;
178
- while ((m = impRe.exec(noCode))) importTokens.push(m[1]);
179
- const spanRe = /`([^`]+)`/g;
180
- while ((m = spanRe.exec(line))) spans.push({ line: lineNo, span: m[1].trim() });
142
+ for (const m of visibleLine(raw, state).matchAll(SPAN_RE)) spans.push({ line: lineNo, span: m[1].trim() });
181
143
  });
182
- return { lines: rawLines, links, spans, importTokens, autolinks, refTokens, ignoredLines };
144
+ const links = rawLinksOf(text).map((l) => ({ line: l.line, target: l.raw }));
145
+ return { lines, links, spans, ignoredLines };
183
146
  }
184
147
 
185
148
  const MAX_IMPORT_HOPS = 4;
186
149
 
187
- const AUTOLINK_RE = /<([^<>\s]{1,1024})>/g;
188
- const MULTI_CODE_RE = /(`+)(.{0,1024}?)\1/g;
189
-
190
- /** A backticked repo-path token (SKILL.md link convention), or null. */
191
- function pathToken(raw) {
192
- const t = raw.trim();
193
- if (t === '' || !t.includes('/') || /\s/.test(t) || /^(?:[/~$<]|http)/i.test(t)) return null;
194
- const bare = t.replace(/:\d+$/, '').replace(/#.*$/, '');
195
- if (bare === '' || /[*{}<>:]/.test(bare)) return null;
196
- if (!bare.endsWith('/') && !/\.[A-Za-z0-9]{1,8}$/.test(bare)) return null;
197
- return bare;
198
- }
199
-
200
- /** Repo-relative POSIX form: no `./` or trailing `/`; `.` is the root. */
201
- const toRepoPath = (p) => path.posix.normalize(p).replace(/\/+$/, '') || '.';
202
150
  const escapesRoot = (p) => p === '..' || p.startsWith('../') || p.startsWith('/');
203
151
 
204
152
  /**
205
- * Docs a parsed doc references, by SKILL.md's link convention (the same rule as the
206
- * app's src/main/lib/mdNetworkScan.cjs): markdown links and `<x.md>` autolinks resolved
207
- * against the doc's folder; `@path.md` imports resolved against the doc's folder;
208
- * backticked `.md` paths, repo-root form first, then doc-relative. Only targets that are
209
- * docs (per `isDoc`) count.
153
+ * Docs a doc references, by SKILL.md's link convention (mdLinks.cjs, shared with the app's
154
+ * src/main/lib/mdNetworkScan.cjs): markdown links and `<x.md>` autolinks and `@path.md`
155
+ * imports resolved against the doc's folder; backticked `.md` paths, repo-root form first,
156
+ * then doc-relative. Only targets that are docs (per `isDoc`) count.
210
157
  */
211
- function docRefs(from, parsed, isDoc) {
158
+ function docRefs(from, text, isDoc) {
212
159
  const dir = path.posix.dirname(from);
213
160
  const out = [];
214
161
  const add = (to) => { if (to !== from && !out.includes(to)) out.push(to); };
215
- for (const l of [...parsed.links, ...parsed.autolinks]) {
216
- const written = l.target.trim();
217
- if (written === '' || written[0] === '#' || written[0] === '/' || SCHEME_RE.test(written)) continue;
218
- const target = written.replace(/[?#].*$/, '');
219
- if (target === '') continue;
220
- let decoded = target;
221
- try { decoded = decodeURIComponent(target); } catch { /* a stray % is part of the name */ }
222
- const to = toRepoPath(path.posix.join(dir, decoded));
223
- if (!escapesRoot(to) && isDoc(to)) add(to);
162
+ for (const l of linksOf({ path: from, text })) {
163
+ if (!l.escapes && isDoc(l.to)) add(l.to);
224
164
  }
225
- for (let tok of parsed.importTokens) {
226
- tok = tok.replace(/[),.;:!?'"\]]+$/, '');
227
- if (!/\.md$/i.test(tok) || tok.startsWith('~') || tok.startsWith('/')) continue;
228
- const to = toRepoPath(path.posix.join(dir, tok));
229
- if (!escapesRoot(to) && isDoc(to)) add(to);
165
+ for (const to of importsOf(text, from)) {
166
+ if (isDoc(to)) add(to);
230
167
  }
231
- for (const tok of parsed.refTokens) {
168
+ for (const tok of backtickPaths(text)) {
232
169
  if (!tok.endsWith('.md')) continue;
233
170
  const forms = dir === '.' ? [toRepoPath(tok)] : [toRepoPath(tok), toRepoPath(path.posix.join(dir, tok))];
234
171
  const to = forms.find((f) => !escapesRoot(f) && isDoc(f));
@@ -248,7 +185,7 @@ function reachableDocs(root, allDocs) {
248
185
  const from = queue.shift();
249
186
  let text;
250
187
  try { text = fs.readFileSync(path.join(root, from), 'utf8'); } catch { continue; }
251
- for (const to of docRefs(from, parseDoc(text), isDoc)) {
188
+ for (const to of docRefs(from, text, isDoc)) {
252
189
  if (!seen.has(to)) { seen.add(to); queue.push(to); }
253
190
  }
254
191
  }
@@ -257,19 +194,10 @@ function reachableDocs(root, allDocs) {
257
194
 
258
195
  const ROOT_DOC = 'CLAUDE.md';
259
196
 
260
- /** Claude Code `@path` imports of a doc: absolute .md paths inside root. */
197
+ /** Claude Code `@path` imports of a doc (mdLinks.importsOf): absolute .md paths inside root. */
261
198
  function parseImports(text, fileAbs, root) {
262
- const out = [];
263
- for (let tok of parseDoc(text).importTokens) {
264
- tok = tok.replace(/[.,;:!?)\]}'"]+$/, '');
265
- if (!tok || tok.startsWith('~')) continue;
266
- if (!/\.md$/i.test(tok)) continue;
267
- const abs = path.resolve(path.dirname(fileAbs), tok);
268
- const rel = path.relative(root, abs);
269
- if (rel.startsWith('..') || path.isAbsolute(rel)) continue;
270
- if (!out.includes(abs)) out.push(abs);
271
- }
272
- return out;
199
+ const from = toPosix(path.relative(root, fileAbs));
200
+ return importsOf(text, from).map((rel) => path.join(root, rel));
273
201
  }
274
202
 
275
203
  const docInfoCache = new Map(); // abs -> { lines, imports } | null (per process; reset each run)
@@ -314,6 +242,59 @@ function hasPathsFrontmatter(text) {
314
242
  return !!m && /^paths\s*:/m.test(m[1]);
315
243
  }
316
244
 
245
+ /**
246
+ * Comparable lines of a doc: { line, text, key } for every non-blank, non-heading line outside
247
+ * code fences, keyed by mdDuplicates.normalize (the duplicate check's normalization).
248
+ */
249
+ function comparableLines(text) {
250
+ const out = [];
251
+ let fence = null;
252
+ text.split(/\r?\n/).forEach((raw, idx) => {
253
+ const m = /^\s*(`{3,}|~{3,})/.exec(raw);
254
+ if (fence) {
255
+ if (m && m[1][0] === fence[0] && m[1].length >= fence.length) fence = null;
256
+ return;
257
+ }
258
+ if (m) { fence = m[1]; return; }
259
+ if (raw.trim() === '' || /^\s{0,3}#{1,6}(\s|$)/.test(raw)) return;
260
+ const key = normalize(raw).join(' ');
261
+ if (key) out.push({ line: idx + 1, text: raw, key });
262
+ });
263
+ return out;
264
+ }
265
+
266
+ /** The AGENTS.md pair layout findings for the checked docs. */
267
+ function pairFindings(root, docs) {
268
+ const out = [];
269
+ const exists = (rel) => fs.existsSync(path.join(root, rel));
270
+ const read = (rel) => { try { return fs.readFileSync(path.join(root, rel), 'utf8'); } catch { return null; } };
271
+ const rootHasClaude = exists(ROOT_DOC);
272
+ for (const rel of docs) {
273
+ const base = path.posix.basename(rel);
274
+ const dir = path.posix.dirname(rel);
275
+ const sibling = (name) => (dir === '.' ? name : `${dir}/${name}`);
276
+ if (base === 'CLAUDE.md') {
277
+ const agentsFile = sibling('AGENTS.md');
278
+ if (!exists(agentsFile)) continue;
279
+ const claudeText = read(rel);
280
+ const agentsText = read(agentsFile);
281
+ if (claudeText === null || agentsText === null) continue;
282
+ if (!isAgentsStub(claudeText)) out.push({ kind: 'claude-md-stub-missing-import', file: rel });
283
+ const agentsByKey = new Map();
284
+ for (const l of comparableLines(agentsText)) if (!agentsByKey.has(l.key)) agentsByKey.set(l.key, l.line);
285
+ const seen = new Set();
286
+ for (const l of comparableLines(claudeText)) {
287
+ if (seen.has(l.key) || !agentsByKey.has(l.key)) continue;
288
+ seen.add(l.key);
289
+ out.push({ kind: 'fact-in-both', file: rel, claudeFile: rel, agentsFile, line: l.line, agentsLine: agentsByKey.get(l.key), text: l.text });
290
+ }
291
+ } else if (base === 'AGENTS.md' && rootHasClaude && !exists(sibling('CLAUDE.md'))) {
292
+ out.push({ kind: 'agents-md-not-loaded', file: rel });
293
+ }
294
+ }
295
+ return out;
296
+ }
297
+
317
298
  function runDriftCheck(options) {
318
299
  const opts = Object.assign({ root: null, map: null, files: [], excludes: [], checks: DEFAULT_CHECKS, strictPaths: false }, options);
319
300
  const root = path.resolve(opts.root || process.cwd());
@@ -344,6 +325,11 @@ function runDriftCheck(options) {
344
325
  if (!fs.existsSync(path.join(root, map))) throw new UsageError(`map not found: ${opts.map}`);
345
326
  } else {
346
327
  const rootFiles = ['CLAUDE.md', 'AGENTS.md'].map((n) => path.join(root, n)).filter((p) => fs.existsSync(p));
328
+ // A root CLAUDE.md that is a stub (`@AGENTS.md` first) hands the map role to the root AGENTS.md.
329
+ const rootAgents = path.join(root, 'AGENTS.md');
330
+ let stubbed = false;
331
+ try { stubbed = fs.existsSync(rootAgents) && isAgentsStub(fs.readFileSync(path.join(root, ROOT_DOC), 'utf8')); } catch { /* no root CLAUDE.md */ }
332
+ if (stubbed) rootFiles.sort((a, b) => (a === rootAgents ? -1 : b === rootAgents ? 1 : 0));
347
333
  const candidates = [...rootFiles];
348
334
  for (const p of rootFiles) {
349
335
  const info = docInfo(p, root);
@@ -354,6 +340,7 @@ function runDriftCheck(options) {
354
340
  try { t = fs.readFileSync(p, 'utf8'); } catch { continue; }
355
341
  if (/<!--\s*md-network-map/.test(t)) { map = toPosix(path.relative(root, p)); break; }
356
342
  }
343
+ if (map === null && stubbed) map = 'AGENTS.md';
357
344
  }
358
345
  const notes = [];
359
346
  if (map === null) notes.push('no md-network-map comment found; the 70-line map limit was not applied');
@@ -363,11 +350,13 @@ function runDriftCheck(options) {
363
350
  const findings = [];
364
351
  const missing = []; // { file, line, target, cands }
365
352
  const missingLinks = []; // same shape; broken-link candidates, dropped when gitignored
353
+ const dupDocs = []; // { path, text } of every checked doc, for the duplicates check
366
354
 
367
355
  for (const rel of docs) {
368
356
  const abs = path.join(root, rel);
369
357
  let text;
370
358
  try { text = fs.readFileSync(abs, 'utf8'); } catch { continue; }
359
+ if (checks.has('duplicates')) dupDocs.push({ path: rel, text });
371
360
  const docDir = path.dirname(abs);
372
361
  const needParse = checks.has('links') || checks.has('paths') || checks.has('contents');
373
362
  const parsed = needParse ? parseDoc(text) : null;
@@ -460,6 +449,8 @@ function runDriftCheck(options) {
460
449
  }
461
450
  }
462
451
 
452
+ if (checks.has('pairs')) findings.push(...pairFindings(root, docs));
453
+
463
454
  if (checks.has('orphans')) {
464
455
  if (!fs.existsSync(path.join(root, ROOT_DOC))) {
465
456
  notes.push(`no root ${ROOT_DOC}; the orphans check was skipped`);
@@ -469,6 +460,20 @@ function runDriftCheck(options) {
469
460
  }
470
461
  }
471
462
 
463
+ if (checks.has('duplicates')) {
464
+ for (const d of findDuplicates(dupDocs)) {
465
+ const what = d.copy ? 'is a full copy of' : `shares ${d.sharedRuns} 8-word runs with`;
466
+ findings.push({
467
+ kind: 'duplicate',
468
+ type: 'duplicate',
469
+ file: d.a,
470
+ other: d.b,
471
+ sharedRuns: d.sharedRuns,
472
+ detail: `${d.a} ${what} ${d.b}; keep the text in one and link to it from the other.`,
473
+ });
474
+ }
475
+ }
476
+
472
477
  findings.sort((x, y) => (x.file < y.file ? -1 : x.file > y.file ? 1 : (x.line || 0) - (y.line || 0)));
473
478
  const counts = {};
474
479
  for (const f of findings) counts[f.kind] = (counts[f.kind] || 0) + 1;
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+ /**
3
+ * mdDuplicates.cjs — dependency-free primitive that finds the same text written in two docs,
4
+ * so a markdown-network scan can show where one fact lives more than once.
5
+ *
6
+ * const { findDuplicates } = require('./mdDuplicates.cjs');
7
+ * findDuplicates([{ path, text }, ...], { runWords, minRuns, maxDocsPerRun })
8
+ * → [{ a, b, sharedRuns, samples, copy? }] sorted by sharedRuns descending
9
+ *
10
+ * Method: each doc's text is normalized (fenced code blocks dropped, link/image targets dropped
11
+ * with their visible text kept, markdown punctuation removed, lower-cased) into words. A "run"
12
+ * is `runWords` consecutive words (default 8). A Map from run → doc indexes gives, per pair of
13
+ * docs, the number of distinct runs they share. A pair is reported when sharedRuns >= `minRuns`
14
+ * (default 10). Runs found in more than `maxDocsPerRun` docs (default 6) are boilerplate and
15
+ * ignored. A pair whose shared runs cover >= 90% of the larger doc's runs is a full copy and
16
+ * carries `copy: true`. `samples` holds up to 3 merged shared passages (the longest, in doc-a
17
+ * order, from doc a's normalized words), each at most 200 chars.
18
+ *
19
+ * Bounds: at most LIMITS.maxDocs (2000) docs are read — extra docs are ignored; each doc's text
20
+ * is truncated to LIMITS.maxDocBytes (256 KB, counted as 262144 UTF-16 chars) before
21
+ * normalizing. Pure: no I/O, no globals mutated.
22
+ */
23
+
24
+ const LIMITS = Object.freeze({ maxDocs: 2000, maxDocBytes: 256 * 1024 });
25
+ const DEFAULTS = Object.freeze({ runWords: 8, minRuns: 10, maxDocsPerRun: 6 });
26
+ const COPY_RATIO = 0.9;
27
+ const MAX_SAMPLES = 3;
28
+ const MAX_SAMPLE_CHARS = 200;
29
+
30
+ /**
31
+ * @typedef {{ path: string, text: string }} Doc
32
+ * @typedef {{ runWords?: number, minRuns?: number, maxDocsPerRun?: number }} DupOptions
33
+ * @typedef {{ a: string, b: string, sharedRuns: number, samples: string[], copy?: true }} DupPair
34
+ */
35
+
36
+ /**
37
+ * Normalize markdown into lower-case words.
38
+ * @param {string} text
39
+ * @returns {string[]}
40
+ */
41
+ function normalize(text) {
42
+ const src = String(text == null ? '' : text).slice(0, LIMITS.maxDocBytes);
43
+ const kept = [];
44
+ /** @type {string|null} */
45
+ let fence = null;
46
+ for (const line of src.split(/\r?\n/)) {
47
+ const m = /^\s*(`{3,}|~{3,})/.exec(line);
48
+ if (fence) {
49
+ if (m && m[1][0] === fence[0] && m[1].length >= fence.length) fence = null;
50
+ continue;
51
+ }
52
+ if (m) { fence = m[1]; continue; }
53
+ kept.push(line);
54
+ }
55
+ const body = kept
56
+ .join('\n')
57
+ .replace(/<!--[\s\S]*?-->/g, ' ')
58
+ // Inline links and images: keep the visible text, drop the target.
59
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
60
+ // Reference links: [text][ref] → text.
61
+ .replace(/!?\[([^\]]*)\]\[[^\]]*\]/g, '$1')
62
+ // Reference definitions: [ref]: target
63
+ .replace(/^\s*\[[^\]]+\]:\s*\S.*$/gm, ' ')
64
+ // Autolinks / bare URLs.
65
+ .replace(/<[a-z][a-z0-9+.-]*:[^>\s]*>/gi, ' ')
66
+ .replace(/\bhttps?:\/\/\S+/gi, ' ')
67
+ .toLowerCase()
68
+ .replace(/[^\p{L}\p{N}]+/gu, ' ');
69
+ return body.split(' ').filter(Boolean);
70
+ }
71
+
72
+ /**
73
+ * @param {unknown} v
74
+ * @param {number} dflt
75
+ * @param {string} name
76
+ * @returns {number}
77
+ */
78
+ function intOpt(v, dflt, name) {
79
+ if (v === undefined || v === null) return dflt;
80
+ if (!Number.isInteger(v) || /** @type {number} */ (v) < 1) {
81
+ throw new TypeError(`findDuplicates: opts.${name} must be a positive integer`);
82
+ }
83
+ return /** @type {number} */ (v);
84
+ }
85
+
86
+ /**
87
+ * Merge shared-run start positions into passages and render the longest few.
88
+ * @param {string[]} words
89
+ * @param {number[]} starts
90
+ * @param {number} runWords
91
+ * @returns {string[]}
92
+ */
93
+ function samplesOf(words, starts, runWords) {
94
+ const sorted = starts.slice().sort((x, y) => x - y);
95
+ /** @type {Array<[number, number]>} */
96
+ const spans = [];
97
+ for (const s of sorted) {
98
+ const last = spans[spans.length - 1];
99
+ if (last && s <= last[1]) last[1] = Math.max(last[1], s + runWords);
100
+ else spans.push([s, s + runWords]);
101
+ }
102
+ return spans
103
+ .map((sp, i) => ({ sp, i }))
104
+ .sort((x, y) => (y.sp[1] - y.sp[0]) - (x.sp[1] - x.sp[0]) || x.i - y.i)
105
+ .slice(0, MAX_SAMPLES)
106
+ .sort((x, y) => x.i - y.i)
107
+ .map(({ sp }) => {
108
+ const s = words.slice(sp[0], sp[1]).join(' ');
109
+ return s.length <= MAX_SAMPLE_CHARS ? s : s.slice(0, MAX_SAMPLE_CHARS);
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Find pairs of docs that share the same text.
115
+ * @param {Doc[]} docs
116
+ * @param {DupOptions} [opts]
117
+ * @returns {DupPair[]}
118
+ */
119
+ function findDuplicates(docs, opts = {}) {
120
+ const runWords = intOpt(opts.runWords, DEFAULTS.runWords, 'runWords');
121
+ const minRuns = intOpt(opts.minRuns, DEFAULTS.minRuns, 'minRuns');
122
+ const maxDocsPerRun = intOpt(opts.maxDocsPerRun, DEFAULTS.maxDocsPerRun, 'maxDocsPerRun');
123
+ const list = Array.isArray(docs) ? docs.slice(0, LIMITS.maxDocs) : [];
124
+
125
+ /** @type {string[][]} */
126
+ const wordsOf = [];
127
+ /** @type {number[]} distinct run count per doc */
128
+ const runCount = [];
129
+ /** @type {Map<string, Array<[number, number]>>} run → [docIndex, firstStart] */
130
+ const runs = new Map();
131
+
132
+ list.forEach((doc, di) => {
133
+ const words = normalize(doc && doc.text);
134
+ wordsOf.push(words);
135
+ const seen = new Set();
136
+ for (let i = 0; i + runWords <= words.length; i++) {
137
+ const key = words.slice(i, i + runWords).join(' ');
138
+ if (seen.has(key)) continue;
139
+ seen.add(key);
140
+ let hits = runs.get(key);
141
+ if (!hits) runs.set(key, (hits = []));
142
+ hits.push([di, i]);
143
+ }
144
+ runCount.push(seen.size);
145
+ });
146
+
147
+ /** @type {Map<string, { ai: number, bi: number, starts: number[] }>} */
148
+ const pairs = new Map();
149
+ for (const hits of runs.values()) {
150
+ if (hits.length < 2 || hits.length > maxDocsPerRun) continue;
151
+ for (let x = 0; x < hits.length; x++) {
152
+ for (let y = x + 1; y < hits.length; y++) {
153
+ const [ai, aStart] = hits[x];
154
+ const [bi] = hits[y];
155
+ const key = `${ai}:${bi}`;
156
+ let p = pairs.get(key);
157
+ if (!p) pairs.set(key, (p = { ai, bi, starts: [] }));
158
+ p.starts.push(aStart);
159
+ }
160
+ }
161
+ }
162
+
163
+ /** @type {DupPair[]} */
164
+ const out = [];
165
+ for (const { ai, bi, starts } of pairs.values()) {
166
+ const sharedRuns = starts.length;
167
+ if (sharedRuns < minRuns) continue;
168
+ /** @type {DupPair} */
169
+ const pair = {
170
+ a: String(list[ai].path),
171
+ b: String(list[bi].path),
172
+ sharedRuns,
173
+ samples: samplesOf(wordsOf[ai], starts, runWords),
174
+ };
175
+ if (sharedRuns >= COPY_RATIO * Math.max(runCount[ai], runCount[bi])) pair.copy = true;
176
+ out.push(pair);
177
+ }
178
+ out.sort((x, y) => y.sharedRuns - x.sharedRuns || x.a.localeCompare(y.a) || x.b.localeCompare(y.b));
179
+ return out;
180
+ }
181
+
182
+ module.exports = { findDuplicates, normalize, LIMITS, DEFAULTS };