@tokenroll/llmdoc 3.6.0 → 3.9.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.
package/dist/lib/git.js CHANGED
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { CliError } from "./errors.js";
5
+ const COMMIT_OID_PATTERN = /^[0-9a-f]{40,64}$/i;
5
6
  function runGit(rootDir, args) {
6
7
  const result = spawnSync("git", ["-c", "core.quotePath=false", ...args], {
7
8
  cwd: rootDir,
@@ -19,13 +20,105 @@ export function gitRestorePaths(rootDir, repoRelativePaths) {
19
20
  runGit(rootDir, ["reset", "--quiet", "--", ...repoRelativePaths]);
20
21
  runGit(rootDir, ["checkout", "--quiet", "--", ...repoRelativePaths]);
21
22
  }
23
+ export function resolveCommitObjectId(rootDir, revision) {
24
+ if (!revision || revision.startsWith("-") || /[\s\0]/.test(revision)) {
25
+ return null;
26
+ }
27
+ const resolved = runGitSafe(rootDir, ["rev-parse", "--verify", "--end-of-options", `${revision}^{commit}`]);
28
+ if (!resolved || !COMMIT_OID_PATTERN.test(resolved)) {
29
+ return null;
30
+ }
31
+ return resolved.toLowerCase();
32
+ }
22
33
  export function gitCommitExists(rootDir, revision) {
23
- const result = spawnSync("git", ["cat-file", "-e", `${revision}^{commit}`], {
34
+ return resolveCommitObjectId(rootDir, revision) !== null;
35
+ }
36
+ export function readCommitTimestampMs(rootDir, revision) {
37
+ const oid = resolveCommitObjectId(rootDir, revision);
38
+ if (!oid) {
39
+ return null;
40
+ }
41
+ const output = runGitSafe(rootDir, ["show", "-s", "--format=%ct", oid, "--"]);
42
+ if (!output) {
43
+ return null;
44
+ }
45
+ const seconds = Number.parseInt(output, 10);
46
+ return Number.isFinite(seconds) ? seconds * 1000 : null;
47
+ }
48
+ export function isGitRepository(rootDir) {
49
+ const result = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], {
24
50
  cwd: rootDir,
25
51
  encoding: "utf8"
26
52
  });
53
+ return result.status === 0 && result.stdout.trim() === "true";
54
+ }
55
+ export function isGitFileTracked(rootDir, repoRelativePath) {
56
+ const result = spawnSync("git", ["ls-files", "--error-unmatch", "--", repoRelativePath], {
57
+ cwd: rootDir,
58
+ encoding: "utf8",
59
+ stdio: ["ignore", "pipe", "ignore"]
60
+ });
27
61
  return result.status === 0;
28
62
  }
63
+ export function isGitPathIgnored(rootDir, repoRelativePath) {
64
+ const result = spawnSync("git", ["check-ignore", "-q", "--", repoRelativePath], {
65
+ cwd: rootDir,
66
+ encoding: "utf8",
67
+ stdio: ["ignore", "ignore", "ignore"]
68
+ });
69
+ return result.status === 0;
70
+ }
71
+ export function listGitTrackedFiles(rootDir) {
72
+ if (!isGitRepository(rootDir)) {
73
+ return null;
74
+ }
75
+ const raw = runGitSafeRaw(rootDir, ["ls-files", "-z"]);
76
+ if (raw === null) {
77
+ return null;
78
+ }
79
+ return raw.split("\0").filter(Boolean).sort();
80
+ }
81
+ export function parseGitPorcelainZ(raw) {
82
+ const entries = [];
83
+ const tokens = raw.split("\0");
84
+ for (let index = 0; index < tokens.length; index += 1) {
85
+ const token = tokens[index];
86
+ if (!token || token.length < 4 || token[2] !== " ") {
87
+ continue;
88
+ }
89
+ const indexStatus = token[0];
90
+ const worktreeStatus = token[1];
91
+ const entryPath = token.slice(3);
92
+ entries.push({
93
+ indexStatus,
94
+ worktreeStatus,
95
+ path: entryPath
96
+ });
97
+ // In porcelain v1 -z, R/C entries emit a second NUL-terminated source path; skip it safely if present.
98
+ if (indexStatus === "R" || indexStatus === "C" || worktreeStatus === "R" || worktreeStatus === "C") {
99
+ index += 1;
100
+ }
101
+ }
102
+ return entries;
103
+ }
104
+ export function listGitDeletedLlmdocPaths(rootDir) {
105
+ if (!isGitRepository(rootDir)) {
106
+ return new Set();
107
+ }
108
+ const raw = runGitSafeRaw(rootDir, ["status", "--porcelain=v1", "-z", "--no-renames", "--", "llmdoc"]);
109
+ if (!raw) {
110
+ return new Set();
111
+ }
112
+ const deleted = new Set();
113
+ for (const entry of parseGitPorcelainZ(raw)) {
114
+ if ((entry.indexStatus === "D" || entry.worktreeStatus === "D") &&
115
+ entry.path.startsWith("llmdoc/") &&
116
+ entry.path.endsWith(".mdx")) {
117
+ deleted.add(entry.path.slice("llmdoc/".length));
118
+ }
119
+ }
120
+ return deleted;
121
+ }
29
122
  export function isUnbornHead(rootDir) {
30
123
  if (!isGitRepository(rootDir) || runGitSafe(rootDir, ["rev-parse", "--verify", "HEAD"]) !== null) {
31
124
  return false;
@@ -54,20 +147,20 @@ export function readGitState(rootDir, baselineRevision) {
54
147
  const headRevision = runGitSafe(rootDir, ["rev-parse", "--verify", "HEAD"]);
55
148
  const detached = runGitSafe(rootDir, ["symbolic-ref", "--quiet", "--short", "HEAD"]) === null;
56
149
  const inProgressOperation = detectInProgressOperation(rootDir);
57
- const stagedPaths = readPathList(rootDir, ["diff", "--name-only", "--no-renames", "--cached"]);
58
- const unstagedPaths = readPathList(rootDir, ["diff", "--name-only", "--no-renames"]);
59
- const untrackedPaths = readPathList(rootDir, ["ls-files", "--others", "--exclude-standard"]);
60
- const committedChangedPaths = baselineRevision && headRevision && gitCommitExists(rootDir, baselineRevision)
61
- ? readPathList(rootDir, ["diff", "--name-only", "--no-renames", `${baselineRevision}..${headRevision}`])
150
+ const stagedPaths = readNulPathList(rootDir, ["diff", "-z", "--name-only", "--no-renames", "--cached"]);
151
+ const unstagedPaths = readNulPathList(rootDir, ["diff", "-z", "--name-only", "--no-renames"]);
152
+ const untrackedPaths = readNulPathList(rootDir, ["ls-files", "-z", "--others", "--exclude-standard"]);
153
+ const baselineOid = baselineRevision ? resolveCommitObjectId(rootDir, baselineRevision) : null;
154
+ const headOid = headRevision ? resolveCommitObjectId(rootDir, headRevision) : null;
155
+ const committedChangedPaths = baselineOid && headOid
156
+ ? readNulPathList(rootDir, ["diff", "-z", "--name-only", "--no-renames", `${baselineOid}..${headOid}`, "--"])
62
157
  : [];
63
- const baselineBehindHead = baselineRevision && headRevision && gitCommitExists(rootDir, baselineRevision)
64
- ? readBehindCount(rootDir, baselineRevision, headRevision)
65
- : null;
158
+ const baselineBehindHead = baselineOid && headOid ? readBehindCount(rootDir, baselineOid, headOid) : null;
66
159
  let degradedReason = null;
67
160
  if (!headRevision) {
68
161
  degradedReason = isUnbornHead(rootDir) ? "HEAD has no commit (the current branch is unborn)." : "Unable to resolve the HEAD commit.";
69
162
  }
70
- else if (baselineRevision && !gitCommitExists(rootDir, baselineRevision)) {
163
+ else if (baselineRevision && !baselineOid) {
71
164
  degradedReason = `baseline.revision does not exist in current Git history: ${baselineRevision}`;
72
165
  }
73
166
  return {
@@ -84,32 +177,50 @@ export function readGitState(rootDir, baselineRevision) {
84
177
  };
85
178
  }
86
179
  export function readChangedPathsSince(rootDir, revision, headRevision) {
87
- if (!gitCommitExists(rootDir, revision)) {
180
+ const revOid = resolveCommitObjectId(rootDir, revision);
181
+ const headOid = resolveCommitObjectId(rootDir, headRevision);
182
+ if (!revOid || !headOid) {
88
183
  return [];
89
184
  }
90
- return readPathList(rootDir, ["diff", "--name-only", "--no-renames", `${revision}..${headRevision}`]);
185
+ return readNulPathList(rootDir, ["diff", "-z", "--name-only", "--no-renames", `${revOid}..${headOid}`, "--"]);
91
186
  }
92
187
  // 逐 commit 列出 baseline..HEAD 中每个提交触碰的路径,供"有效源码落后"计数:
93
188
  // \x01 前缀作 commit 分隔哨兵,避免 40 位 hex 路径名的歧义;merge commit 默认不列文件,视为无自身变更。
94
189
  export function readCommitsWithChangedPathsSince(rootDir, revision, headRevision) {
95
- if (!gitCommitExists(rootDir, revision)) {
190
+ const revOid = resolveCommitObjectId(rootDir, revision);
191
+ const headOid = resolveCommitObjectId(rootDir, headRevision);
192
+ if (!revOid || !headOid) {
96
193
  return null;
97
194
  }
98
- const output = runGitSafe(rootDir, ["log", "--format=%x01%H", "--name-only", "--no-renames", `${revision}..${headRevision}`]);
195
+ const output = runGitSafeRaw(rootDir, [
196
+ "log",
197
+ "-z",
198
+ "--format=%x01%H",
199
+ "--name-only",
200
+ "--no-renames",
201
+ `${revOid}..${headOid}`,
202
+ "--"
203
+ ]);
99
204
  if (output === null) {
100
205
  return null;
101
206
  }
102
207
  const commits = [];
103
- for (const line of output.split(/\r?\n/)) {
104
- const trimmed = line.trim();
105
- if (!trimmed) {
208
+ let awaitingFirstPath = false;
209
+ for (const segment of output.split("\0")) {
210
+ if (!segment) {
106
211
  continue;
107
212
  }
108
- if (trimmed.startsWith("\u0001")) {
109
- commits.push({ revision: trimmed.slice(1), paths: [] });
213
+ if (segment.startsWith("\u0001")) {
214
+ commits.push({ revision: segment.slice(1).trim(), paths: [] });
215
+ awaitingFirstPath = true;
110
216
  }
111
217
  else if (commits.length > 0) {
112
- commits[commits.length - 1].paths.push(trimmed);
218
+ // git log -z places a single newline separator between the commit format chunk and the first --name-only path.
219
+ const filePath = awaitingFirstPath && segment.startsWith("\n") ? segment.slice(1) : segment;
220
+ awaitingFirstPath = false;
221
+ if (filePath) {
222
+ commits[commits.length - 1].paths.push(filePath);
223
+ }
113
224
  }
114
225
  }
115
226
  return commits;
@@ -123,14 +234,11 @@ export function canAdvanceRevisions(gitState) {
123
234
  }
124
235
  return { ok: true };
125
236
  }
126
- function isGitRepository(rootDir) {
127
- const result = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], {
128
- cwd: rootDir,
129
- encoding: "utf8"
130
- });
131
- return result.status === 0 && result.stdout.trim() === "true";
132
- }
133
237
  function runGitSafe(rootDir, args) {
238
+ const raw = runGitSafeRaw(rootDir, args);
239
+ return raw === null ? null : raw.trim();
240
+ }
241
+ function runGitSafeRaw(rootDir, args) {
134
242
  const result = spawnSync("git", ["-c", "core.quotePath=false", ...args], {
135
243
  cwd: rootDir,
136
244
  encoding: "utf8"
@@ -138,20 +246,17 @@ function runGitSafe(rootDir, args) {
138
246
  if (result.status !== 0) {
139
247
  return null;
140
248
  }
141
- return result.stdout.trim();
249
+ return result.stdout;
142
250
  }
143
- function readPathList(rootDir, args) {
144
- const output = runGitSafe(rootDir, args);
251
+ function readNulPathList(rootDir, args) {
252
+ const output = runGitSafeRaw(rootDir, args);
145
253
  if (!output) {
146
254
  return [];
147
255
  }
148
- return output
149
- .split(/\r?\n/)
150
- .map((line) => line.trim())
151
- .filter(Boolean);
256
+ return output.split("\0").filter(Boolean);
152
257
  }
153
- function readBehindCount(rootDir, baselineRevision, headRevision) {
154
- const output = runGitSafe(rootDir, ["rev-list", "--count", `${baselineRevision}..${headRevision}`]);
258
+ function readBehindCount(rootDir, baselineOid, headOid) {
259
+ const output = runGitSafe(rootDir, ["rev-list", "--count", `${baselineOid}..${headOid}`, "--"]);
155
260
  if (!output) {
156
261
  return null;
157
262
  }
@@ -3,8 +3,9 @@ const LINK_PATTERN = /(?<!!)\[[^\]]*]\(([^)]+)\)/g;
3
3
  const CODE_REF_PATTERN = /<CodeRef\b([\s\S]*?)\/>/g;
4
4
  const INLINE_CODE_PATTERN = /`[^`\n]*`/g;
5
5
  export function extractTitle(body) {
6
- const match = body.match(/^#\s+(.+)$/m);
7
- return match ? match[1].trim() : null;
6
+ const match = body.match(/^#[ \t]+(.+)$/m);
7
+ const title = match?.[1]?.trim();
8
+ return title ? title : null;
8
9
  }
9
10
  export function estimateTokens(text) {
10
11
  return Math.max(1, Math.ceil(text.length / 4));
@@ -1,10 +1,16 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import matter from "gray-matter";
3
+ import { stringifyYamlFrontmatter } from "./frontmatter.js";
4
4
  import { resolveDocLink } from "./markdown.js";
5
5
  export function updateDocumentForMove(document, mapping) {
6
6
  const frontmatter = structuredClone(document.frontmatter);
7
- frontmatter.relations = updateRelations(frontmatter.relations, mapping);
7
+ const nextRelations = updateRelations(frontmatter.relations, mapping);
8
+ if (nextRelations) {
9
+ frontmatter.relations = nextRelations;
10
+ }
11
+ else {
12
+ delete frontmatter.relations;
13
+ }
8
14
  let body = document.body;
9
15
  body = rewriteMarkdownLinks({
10
16
  sourceLlmdocPathBefore: document.llmdocPath,
@@ -12,7 +18,7 @@ export function updateDocumentForMove(document, mapping) {
12
18
  body,
13
19
  mapping
14
20
  });
15
- return matter.stringify(body, frontmatter);
21
+ return stringifyYamlFrontmatter(frontmatter, body);
16
22
  }
17
23
  function updateRelations(relations, mapping) {
18
24
  if (!relations) {
@@ -0,0 +1,152 @@
1
+ import { normalizeRepoRelativePath, resolveInsideRoot } from "./fs.js";
2
+ import { matchesCodePathPattern } from "./search.js";
3
+ import { formatDocumentPath, isSourceRef, parseSourceDocId } from "./source-id.js";
4
+ import { sourceDocumentMatchesPath } from "./sources.js";
5
+ export function getDocumentCodePaths(document) {
6
+ const raw = document.frontmatter?.code?.paths;
7
+ if (!Array.isArray(raw)) {
8
+ return [];
9
+ }
10
+ return raw.filter((item) => typeof item === "string" && item.trim().length > 0);
11
+ }
12
+ export function getDocumentRequires(document) {
13
+ const raw = document.frontmatter?.relations?.requires;
14
+ if (!Array.isArray(raw)) {
15
+ return [];
16
+ }
17
+ return raw.filter((item) => typeof item === "string" && item.trim().length > 0);
18
+ }
19
+ export function resolveContextFileInput(rootDir, rawFile) {
20
+ const normalized = normalizeRepoRelativePath(rawFile);
21
+ // Allow not-yet-created repo-relative paths while still blocking traversal and symlink escapes.
22
+ const absolutePath = resolveInsideRoot(rootDir, normalized, { allowMissing: true });
23
+ return { normalized, absolutePath };
24
+ }
25
+ export function matchLocalContextFiles(workspace, files) {
26
+ const localDocumentsByFile = files.map((file) => ({
27
+ file,
28
+ documents: workspace.documents.filter((document) => getDocumentCodePaths(document).some((pattern) => matchesCodePathPattern(pattern, file.normalized)))
29
+ }));
30
+ const localImpactedPaths = new Set(localDocumentsByFile.flatMap(({ documents }) => documents.map((document) => document.llmdocPath)));
31
+ const localImpacted = workspace.documents.filter((document) => localImpactedPaths.has(document.llmdocPath));
32
+ // Unmapped files are strictly determined by local owners so external references never hide missing local ownership.
33
+ const unmappedFiles = localDocumentsByFile
34
+ .filter(({ documents }) => documents.length === 0)
35
+ .map(({ file }) => file.normalized);
36
+ return { localDocumentsByFile, localImpacted, unmappedFiles };
37
+ }
38
+ export function resolveContextFiles(workspace, files, options) {
39
+ const { localDocumentsByFile, localImpacted, unmappedFiles } = options?.prematchedLocal ?? matchLocalContextFiles(workspace, files);
40
+ const includeSources = options?.includeSources ?? true;
41
+ const sourceImpactedIds = includeSources
42
+ ? new Set(files.flatMap((file) => workspace.sourceDocuments
43
+ .filter((document) => sourceDocumentMatchesPath(document, file.normalized))
44
+ .map((document) => document.llmdocPath)))
45
+ : new Set();
46
+ const sourceImpacted = includeSources
47
+ ? workspace.sourceDocuments.filter((document) => sourceImpactedIds.has(document.llmdocPath))
48
+ : [];
49
+ const impacted = [...localImpacted, ...sourceImpacted].sort((left, right) => formatDocumentPath(left).localeCompare(formatDocumentPath(right)));
50
+ const { prerequisites, missingPrerequisites, missingLocalPrerequisites } = collectRequiresClosure(workspace, impacted, {
51
+ includeSources
52
+ });
53
+ return {
54
+ localDocumentsByFile,
55
+ localImpacted,
56
+ sourceImpacted,
57
+ impacted,
58
+ unmappedFiles,
59
+ prerequisites,
60
+ missingPrerequisites,
61
+ missingLocalPrerequisites
62
+ };
63
+ }
64
+ export function collectRequiresClosure(workspace, impacted, options) {
65
+ const includeSources = options?.includeSources ?? true;
66
+ const seen = new Set(impacted.map((document) => formatDocumentPath(document)));
67
+ const queue = [...impacted];
68
+ const results = [];
69
+ const missingByPath = new Map();
70
+ const missingLocalByPath = new Map();
71
+ while (queue.length > 0) {
72
+ const current = queue.shift();
73
+ for (const requirement of getDocumentRequires(current)) {
74
+ if (isSourceRef(requirement)) {
75
+ if (!includeSources) {
76
+ continue;
77
+ }
78
+ let parsed;
79
+ try {
80
+ parsed = parseSourceDocId(requirement);
81
+ }
82
+ catch (error) {
83
+ if (!missingByPath.has(requirement)) {
84
+ missingByPath.set(requirement, { path: requirement, reason: error.message });
85
+ }
86
+ continue;
87
+ }
88
+ // Source documents may only traverse prerequisites within the same source.
89
+ if (current.sourceName && current.sourceName !== parsed.alias) {
90
+ continue;
91
+ }
92
+ if (seen.has(parsed.canonicalId)) {
93
+ continue;
94
+ }
95
+ const source = workspace.sourcesByName.get(parsed.alias);
96
+ if (!source) {
97
+ missingByPath.set(parsed.canonicalId, {
98
+ path: parsed.canonicalId,
99
+ reason: `source @${parsed.alias} is not configured`
100
+ });
101
+ continue;
102
+ }
103
+ if (source.status !== "ready") {
104
+ missingByPath.set(parsed.canonicalId, {
105
+ path: parsed.canonicalId,
106
+ reason: `source @${parsed.alias} is unavailable: ${source.error ?? "no local snapshot"}${source.remedy ? ` (${source.remedy})` : ""}`
107
+ });
108
+ continue;
109
+ }
110
+ const next = workspace.sourceDocumentsById.get(parsed.canonicalId);
111
+ if (!next) {
112
+ missingByPath.set(parsed.canonicalId, {
113
+ path: parsed.canonicalId,
114
+ reason: `not found in @${parsed.alias}${source.revision ? ` (${source.revision.slice(0, 7)})` : ""}`
115
+ });
116
+ continue;
117
+ }
118
+ seen.add(parsed.canonicalId);
119
+ results.push(next);
120
+ queue.push(next);
121
+ continue;
122
+ }
123
+ // External source documents cannot require consumer local documents.
124
+ if (current.sourceName) {
125
+ continue;
126
+ }
127
+ const normalizedLocal = requirement.startsWith("llmdoc/") ? requirement.slice("llmdoc/".length) : requirement;
128
+ const localKey = `llmdoc/${normalizedLocal}`;
129
+ if (seen.has(localKey)) {
130
+ continue;
131
+ }
132
+ const next = workspace.documentsByLlmdocPath.get(normalizedLocal);
133
+ if (!next) {
134
+ if (!missingLocalByPath.has(localKey)) {
135
+ missingLocalByPath.set(localKey, {
136
+ path: localKey,
137
+ reason: `local prerequisite document does not exist: ${localKey}`
138
+ });
139
+ }
140
+ continue;
141
+ }
142
+ seen.add(localKey);
143
+ results.push(next);
144
+ queue.push(next);
145
+ }
146
+ }
147
+ return {
148
+ prerequisites: results.sort((left, right) => formatDocumentPath(left).localeCompare(formatDocumentPath(right))),
149
+ missingPrerequisites: [...missingByPath.values()].sort((left, right) => left.path.localeCompare(right.path)),
150
+ missingLocalPrerequisites: [...missingLocalByPath.values()].sort((left, right) => left.path.localeCompare(right.path))
151
+ };
152
+ }
@@ -12,6 +12,7 @@ function readSchema(fileName) {
12
12
  const docValidator = ajv.compile(readSchema("doc-frontmatter.schema.json"));
13
13
  const metaValidator = ajv.compile(readSchema("meta.schema.json"));
14
14
  const configValidator = ajv.compile(readSchema("config.schema.json"));
15
+ const probesValidator = ajv.compile(readSchema("probes.schema.json"));
15
16
  export function validateDocFrontmatter(input) {
16
17
  const ok = docValidator(input);
17
18
  if (ok) {
@@ -41,6 +42,13 @@ export function validateLlmdocConfig(input) {
41
42
  }
42
43
  return (configValidator.errors ?? []).map(formatAjvError);
43
44
  }
45
+ export function validateProbesConfig(input) {
46
+ const ok = probesValidator(input);
47
+ if (ok) {
48
+ return [];
49
+ }
50
+ return (probesValidator.errors ?? []).map(formatAjvError);
51
+ }
44
52
  function formatAjvError(error) {
45
53
  return `${error.instancePath || "/"} ${error.message ?? "invalid"}`;
46
54
  }
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import { Minimatch } from "minimatch";
3
3
  import { CACHE_DIR, SEARCH_CACHE_FILE } from "./constants.js";
4
4
  import { ensureDirectory, resolveInsideRoot } from "./fs.js";
5
+ import { formatDocumentPath, matchesDocumentTopic } from "./source-id.js";
5
6
  const WORD_SEGMENTER = new Intl.Segmenter("zh-CN", { granularity: "word" });
6
7
  const CJK_CHARACTER = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]$/u;
7
8
  const CJK_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]{2,}/gu;
@@ -31,9 +32,14 @@ const QUERY_STOP_WORDS = new Set([
31
32
  export function searchDocuments(workspace, query, filters) {
32
33
  const normalizedQuery = query.trim().toLowerCase();
33
34
  const lexicalTokens = tokenizeQuery(query).map((value) => ({ value, weight: 1 }));
34
- const cache = loadSearchCache(workspace);
35
- const filteredDocs = workspace.documents.filter((document) => {
36
- if (filters?.topic && document.topic !== filters.topic) {
35
+ const includeSources = filters?.includeSources ?? true;
36
+ const useCache = filters?.useCache ?? true;
37
+ const allDocuments = includeSources ? [...workspace.documents, ...workspace.sourceDocuments] : [...workspace.documents];
38
+ // Persist only local workspace documents to the repository search cache so external private
39
+ // source bodies and ~/.llmdoc paths are never copied into the consumer repository.
40
+ const cache = useCache ? loadSearchCache(workspace, workspace.documents) : { version: 3, entries: {} };
41
+ const filteredDocs = allDocuments.filter((document) => {
42
+ if (filters?.topic && !matchesDocumentTopic(document, filters.topic)) {
37
43
  return false;
38
44
  }
39
45
  if (filters?.kind && document.frontmatter.kind !== filters.kind) {
@@ -72,7 +78,8 @@ function scoreDocuments(documents, cache, tokens, options) {
72
78
  for (const token of tokens) {
73
79
  let count = 0;
74
80
  for (const document of documents) {
75
- const searchableText = cache.entries[document.llmdocPath]?.searchableText ?? buildSearchableText(document);
81
+ const cacheKey = formatDocumentPath(document);
82
+ const searchableText = cache.entries[cacheKey]?.searchableText ?? buildSearchableText(document);
76
83
  if (searchableText.includes(token.value)) {
77
84
  count += 1;
78
85
  }
@@ -81,8 +88,9 @@ function scoreDocuments(documents, cache, tokens, options) {
81
88
  }
82
89
  return documents
83
90
  .map((document) => {
84
- const searchableText = cache.entries[document.llmdocPath]?.searchableText ?? buildSearchableText(document);
85
- const wordCount = cache.entries[document.llmdocPath]?.wordCount ?? countWords(searchableText);
91
+ const cacheKey = formatDocumentPath(document);
92
+ const searchableText = cache.entries[cacheKey]?.searchableText ?? buildSearchableText(document);
93
+ const wordCount = cache.entries[cacheKey]?.wordCount ?? countWords(searchableText);
86
94
  let score = 0;
87
95
  let matchedTokenCount = 0;
88
96
  for (const token of tokens) {
@@ -129,24 +137,35 @@ function normalizeCodePathPattern(pattern) {
129
137
  }
130
138
  return normalized.replace(/\/+$/, "");
131
139
  }
132
- function loadSearchCache(workspace) {
140
+ function loadSearchCache(workspace, documents) {
133
141
  const next = {
134
- version: 2,
142
+ version: 3,
135
143
  entries: {}
136
144
  };
137
145
  const cachePath = resolveCachePath(workspace);
138
146
  const existing = cachePath ? readCache(cachePath) : null;
139
- for (const document of workspace.documents) {
140
- const stats = fs.statSync(document.absolutePath);
141
- const cachedEntry = existing?.entries[document.llmdocPath];
142
- if (existing?.version === 2 && cachedEntry && cachedEntry.mtimeMs === stats.mtimeMs) {
143
- next.entries[document.llmdocPath] = cachedEntry;
147
+ for (const document of documents) {
148
+ let mtimeMs = 0;
149
+ try {
150
+ mtimeMs = fs.statSync(document.absolutePath).mtimeMs;
151
+ }
152
+ catch {
153
+ continue;
154
+ }
155
+ const cacheKey = formatDocumentPath(document);
156
+ const cachedEntry = existing?.entries[cacheKey];
157
+ if (existing?.version === 3 &&
158
+ cachedEntry &&
159
+ cachedEntry.mtimeMs === mtimeMs &&
160
+ cachedEntry.absolutePath === document.absolutePath) {
161
+ next.entries[cacheKey] = cachedEntry;
144
162
  continue;
145
163
  }
146
164
  const searchableText = buildSearchableText(document);
147
- next.entries[document.llmdocPath] = {
148
- llmdocPath: document.llmdocPath,
149
- mtimeMs: stats.mtimeMs,
165
+ next.entries[cacheKey] = {
166
+ llmdocPath: cacheKey,
167
+ absolutePath: document.absolutePath,
168
+ mtimeMs,
150
169
  searchableText,
151
170
  wordCount: countWords(searchableText)
152
171
  };
@@ -0,0 +1,49 @@
1
+ import { CliError } from "./errors.js";
2
+ import { normalizeRepoRelativePath } from "./fs.js";
3
+ export const SOURCE_ALIAS_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
4
+ export function isValidSourceAlias(alias) {
5
+ return SOURCE_ALIAS_PATTERN.test(alias);
6
+ }
7
+ export function isSourceRef(input) {
8
+ return input.trim().startsWith("@");
9
+ }
10
+ export function formatDocumentPath(doc) {
11
+ return doc.sourceName ? doc.llmdocPath : `llmdoc/${doc.llmdocPath}`;
12
+ }
13
+ function relativePath(input) {
14
+ const normalized = input.replaceAll("\\", "/");
15
+ if (/[\p{Cc}<>:"|?*]/u.test(normalized) || normalized.split("/").includes(".")) {
16
+ throw new CliError(`Invalid source path: ${input}`);
17
+ }
18
+ return normalizeRepoRelativePath(normalized);
19
+ }
20
+ export function normalizeSourceSubdir(input) {
21
+ return relativePath(input.replaceAll("\\", "/").replace(/\/$/u, ""));
22
+ }
23
+ function splitRef(input) {
24
+ const [prefix, ...rest] = input.trim().replaceAll("\\", "/").split("/");
25
+ const alias = prefix.slice(1);
26
+ if (!prefix.startsWith("@") || !isValidSourceAlias(alias)) {
27
+ throw new CliError(`Invalid source alias: ${prefix}`);
28
+ }
29
+ return { alias, rest };
30
+ }
31
+ export function parseSourceDocId(input) {
32
+ const { alias, rest } = splitRef(input);
33
+ const normalized = relativePath(rest.join("/"));
34
+ if (!/\.mdx?$/u.test(normalized)) {
35
+ throw new CliError("A source document ID must end in .md or .mdx.");
36
+ }
37
+ return { alias, relativePath: normalized, canonicalId: `@${alias}/${normalized}` };
38
+ }
39
+ export function parseSourceTopicFilter(input) {
40
+ const { alias, rest } = splitRef(input);
41
+ return { alias, subdir: rest.length === 0 ? null : normalizeSourceSubdir(rest.join("/")) };
42
+ }
43
+ export function matchesDocumentTopic(doc, topicFilter) {
44
+ if (!isSourceRef(topicFilter))
45
+ return !doc.sourceName && doc.topic === topicFilter;
46
+ const { alias, subdir } = parseSourceTopicFilter(topicFilter);
47
+ return doc.sourceName === alias && (subdir === null || doc.sourceRelativePath === subdir ||
48
+ doc.sourceRelativePath?.startsWith(`${subdir}/`) === true);
49
+ }