@tokenroll/llmdoc 3.5.3 → 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.
Files changed (48) hide show
  1. package/assets/viewer-app.js +11 -11
  2. package/assets/viewer-detail.js +4 -4
  3. package/assets/viewer-graph.js +3 -3
  4. package/assets/viewer.html +19 -19
  5. package/dist/cli.js +147 -71
  6. package/dist/commands/adopt.js +10 -6
  7. package/dist/commands/commit.js +232 -80
  8. package/dist/commands/context.js +85 -45
  9. package/dist/commands/dream.js +608 -0
  10. package/dist/commands/eval.js +379 -0
  11. package/dist/commands/fingerprint.js +9 -3
  12. package/dist/commands/hook.js +135 -28
  13. package/dist/commands/index.js +52 -7
  14. package/dist/commands/init-state.js +5 -5
  15. package/dist/commands/mv.js +33 -12
  16. package/dist/commands/new.js +12 -5
  17. package/dist/commands/prune.js +14 -3
  18. package/dist/commands/search.js +67 -4
  19. package/dist/commands/serve.js +1 -1
  20. package/dist/commands/show.js +40 -6
  21. package/dist/commands/status.js +46 -18
  22. package/dist/commands/tree.js +94 -6
  23. package/dist/commands/upgrade.js +15 -15
  24. package/dist/lib/config.js +502 -0
  25. package/dist/lib/constants.js +23 -0
  26. package/dist/lib/doc-shape.js +5 -5
  27. package/dist/lib/frontmatter.js +47 -0
  28. package/dist/lib/fs.js +8 -8
  29. package/dist/lib/git.js +147 -42
  30. package/dist/lib/markdown.js +8 -7
  31. package/dist/lib/output-schema.js +3 -3
  32. package/dist/lib/package-root.js +1 -1
  33. package/dist/lib/pagination.js +2 -2
  34. package/dist/lib/rewrite.js +9 -3
  35. package/dist/lib/routing.js +152 -0
  36. package/dist/lib/schema.js +16 -0
  37. package/dist/lib/search.js +35 -16
  38. package/dist/lib/source-id.js +49 -0
  39. package/dist/lib/sources.js +760 -0
  40. package/dist/lib/state.js +74 -25
  41. package/dist/lib/telemetry.js +726 -0
  42. package/dist/lib/viewer-http.js +2 -2
  43. package/dist/lib/workspace.js +187 -43
  44. package/package.json +1 -1
  45. package/schemas/config.schema.json +116 -0
  46. package/schemas/meta.schema.json +5 -1
  47. package/schemas/output.schema.json +442 -0
  48. package/schemas/probes.schema.json +90 -0
package/dist/lib/git.js CHANGED
@@ -2,13 +2,14 @@ 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,
8
9
  encoding: "utf8"
9
10
  });
10
11
  if (result.status !== 0) {
11
- throw new CliError((result.stderr || result.stdout || "git 命令失败").trim());
12
+ throw new CliError((result.stderr || result.stdout || "Git command failed").trim());
12
13
  }
13
14
  return result.stdout.trim();
14
15
  }
@@ -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;
@@ -48,27 +141,27 @@ export function readGitState(rootDir, baselineRevision) {
48
141
  stagedPaths: [],
49
142
  unstagedPaths: [],
50
143
  untrackedPaths: [],
51
- degradedReason: "当前目录不是 git 仓库,状态面降级为不可用。"
144
+ degradedReason: "The current directory is not a Git repository; state diagnostics are unavailable."
52
145
  };
53
146
  }
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
- degradedReason = isUnbornHead(rootDir) ? "HEAD 尚无 commit(当前分支尚未创建首次提交)。" : "无法解析 HEAD commit。";
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)) {
71
- degradedReason = `baseline.revision 不存在于当前 git 历史: ${baselineRevision}`;
163
+ else if (baselineRevision && !baselineOid) {
164
+ degradedReason = `baseline.revision does not exist in current Git history: ${baselineRevision}`;
72
165
  }
73
166
  return {
74
167
  available: true,
@@ -84,53 +177,68 @@ 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;
116
227
  }
117
228
  export function canAdvanceRevisions(gitState) {
118
229
  if (!gitState.available || !gitState.headRevision) {
119
- return { ok: false, reason: gitState.degradedReason ?? "git 状态不可用。" };
230
+ return { ok: false, reason: gitState.degradedReason ?? "Git state is unavailable." };
120
231
  }
121
232
  if (gitState.inProgressOperation) {
122
- return { ok: false, reason: `${gitState.inProgressOperation} 进行中,不推进 revision。` };
233
+ return { ok: false, reason: `${gitState.inProgressOperation} is in progress; revisions cannot advance.` };
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));
@@ -64,27 +65,27 @@ export function validateCodeRefTags(body) {
64
65
  const raw = match[0] ?? "";
65
66
  const attributes = match[1] ?? "";
66
67
  if (!raw.endsWith("/>")) {
67
- issues.push("CodeRef 必须使用自闭合写法 <CodeRef ... />。");
68
+ issues.push("CodeRef must use the self-closing form <CodeRef ... />.");
68
69
  continue;
69
70
  }
70
71
  const attrMatches = [...attributes.matchAll(/([A-Za-z]+)="([^"]*)"/g)];
71
72
  const consumed = attrMatches.map((attr) => attr[0]).join(" ").trim();
72
73
  const normalized = attributes.replace(/\s+/g, " ").trim().replace(/\/$/, "").trim();
73
74
  if (normalized && consumed !== normalized) {
74
- issues.push("CodeRef 仅允许双引号属性 path 和可选 symbol。");
75
+ issues.push("CodeRef allows only the double-quoted path attribute and optional symbol attribute.");
75
76
  continue;
76
77
  }
77
78
  const names = attrMatches.map((attr) => attr[1]);
78
79
  const duplicates = names.filter((name, index) => names.indexOf(name) !== index);
79
80
  if (duplicates.length > 0) {
80
- issues.push(`CodeRef 存在重复属性: ${[...new Set(duplicates)].join(", ")}`);
81
+ issues.push(`CodeRef contains duplicate attributes: ${[...new Set(duplicates)].join(", ")}`);
81
82
  }
82
83
  if (!names.includes("path")) {
83
- issues.push("CodeRef 缺少必填属性 path。");
84
+ issues.push("CodeRef is missing the required path attribute.");
84
85
  }
85
86
  for (const name of names) {
86
87
  if (name !== "path" && name !== "symbol") {
87
- issues.push(`CodeRef 存在未知属性: ${name}`);
88
+ issues.push(`CodeRef contains an unknown attribute: ${name}`);
88
89
  }
89
90
  }
90
91
  }
@@ -13,7 +13,7 @@ export function assertOutputSchema(name, payload) {
13
13
  if (ok) {
14
14
  return;
15
15
  }
16
- throw new CliError(`内部输出契约错误(${name}): ${formatErrors(validator.errors ?? [])}`, 70);
16
+ throw new CliError(`Internal output contract error (${name}): ${formatErrors(validator.errors ?? [])}`, 70);
17
17
  }
18
18
  export function stringifyValidatedOutput(name, payload) {
19
19
  assertOutputSchema(name, payload);
@@ -25,7 +25,7 @@ export function parseAndValidateJsonString(name, input) {
25
25
  payload = JSON.parse(input);
26
26
  }
27
27
  catch (error) {
28
- throw new CliError(`内部输出契约错误(${name}): JSON 解析失败: ${error.message}`, 70);
28
+ throw new CliError(`Internal output contract error (${name}): JSON parse failed: ${error.message}`, 70);
29
29
  }
30
30
  return stringifyValidatedOutput(name, payload);
31
31
  }
@@ -36,7 +36,7 @@ function getValidator(name) {
36
36
  }
37
37
  const defs = schemaDocument.$defs;
38
38
  if (!defs?.[name]) {
39
- throw new CliError(`内部输出契约错误: 未找到 schema ${name}`, 70);
39
+ throw new CliError(`Internal output contract error: schema ${name} was not found`, 70);
40
40
  }
41
41
  const validator = ajv.compile({
42
42
  $schema: "https://json-schema.org/draft/2020-12/schema",
@@ -9,7 +9,7 @@ export function packageRootFromImport(metaUrl) {
9
9
  }
10
10
  const parent = path.dirname(current);
11
11
  if (parent === current) {
12
- throw new Error(`无法从 ${metaUrl} 向上定位 package root。`);
12
+ throw new Error(`Unable to locate the package root above ${metaUrl}.`);
13
13
  }
14
14
  current = parent;
15
15
  }
@@ -6,7 +6,7 @@ export function paginate({ items, estimate, options }) {
6
6
  const budget = options.budget ?? DEFAULT_BUDGET;
7
7
  const offset = decodeCursor(options.cursor);
8
8
  if (offset < 0 || offset > items.length) {
9
- throw new CliError("cursor 非法或已失效。");
9
+ throw new CliError("The cursor is invalid or expired.");
10
10
  }
11
11
  const selected = [];
12
12
  let usedBudget = 0;
@@ -60,6 +60,6 @@ function decodeCursor(cursor) {
60
60
  return payload.offset;
61
61
  }
62
62
  catch {
63
- throw new CliError("cursor 非法或已损坏。");
63
+ throw new CliError("The cursor is invalid or corrupted.");
64
64
  }
65
65
  }
@@ -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
+ }
@@ -11,6 +11,8 @@ function readSchema(fileName) {
11
11
  }
12
12
  const docValidator = ajv.compile(readSchema("doc-frontmatter.schema.json"));
13
13
  const metaValidator = ajv.compile(readSchema("meta.schema.json"));
14
+ const configValidator = ajv.compile(readSchema("config.schema.json"));
15
+ const probesValidator = ajv.compile(readSchema("probes.schema.json"));
14
16
  export function validateDocFrontmatter(input) {
15
17
  const ok = docValidator(input);
16
18
  if (ok) {
@@ -33,6 +35,20 @@ export function validateMeta(input) {
33
35
  }
34
36
  return errors;
35
37
  }
38
+ export function validateLlmdocConfig(input) {
39
+ const ok = configValidator(input);
40
+ if (ok) {
41
+ return [];
42
+ }
43
+ return (configValidator.errors ?? []).map(formatAjvError);
44
+ }
45
+ export function validateProbesConfig(input) {
46
+ const ok = probesValidator(input);
47
+ if (ok) {
48
+ return [];
49
+ }
50
+ return (probesValidator.errors ?? []).map(formatAjvError);
51
+ }
36
52
  function formatAjvError(error) {
37
53
  return `${error.instancePath || "/"} ${error.message ?? "invalid"}`;
38
54
  }