@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
@@ -0,0 +1,760 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { DEFAULT_SOURCE_COOLDOWN_MS, DEFAULT_SOURCE_COLD_WALL_TIMEOUT_MS, DEFAULT_SOURCE_GIT_TIMEOUT_MS, DEFAULT_SOURCE_LOCK_STALE_MS, DEFAULT_SOURCE_MAX_RETRIES, DEFAULT_SOURCE_REFRESH_MS, MAX_SOURCE_DOCUMENT_BYTES, MAX_SOURCE_DOCUMENTS } from "./constants.js";
7
+ import { CliError } from "./errors.js";
8
+ import { isWithinRoot, normalizeRepoRelativePath, resolveInsideRoot, toPosixRelative } from "./fs.js";
9
+ import { parseYamlFrontmatter } from "./frontmatter.js";
10
+ import { estimateTokens, extractCodeRefs, extractLinks, extractTitle } from "./markdown.js";
11
+ import { packageRootFromImport } from "./package-root.js";
12
+ import { matchesCodePathPattern } from "./search.js";
13
+ import { isValidSourceAlias, normalizeSourceSubdir, parseSourceDocId } from "./source-id.js";
14
+ export function getLlmdocHomeDir() {
15
+ return path.resolve(process.env.LLMDOC_HOME || path.join(os.homedir(), ".llmdoc"));
16
+ }
17
+ export function parseRefreshDurationMs(input) {
18
+ if (input === undefined)
19
+ return DEFAULT_SOURCE_REFRESH_MS;
20
+ const match = /^([1-9][0-9]*)([mhd])$/u.exec(input);
21
+ const units = { m: 60_000, h: 3_600_000, d: 86_400_000 };
22
+ const duration = match ? Number(match[1]) * units[match[2]] : NaN;
23
+ if (!Number.isSafeInteger(duration))
24
+ throw new CliError("Invalid refresh duration. Use a positive integer followed by m, h, or d.");
25
+ return duration;
26
+ }
27
+ function hasControlChar(input) {
28
+ for (let index = 0; index < input.length; index += 1) {
29
+ const code = input.charCodeAt(index);
30
+ if (code <= 0x1f || code === 0x7f) {
31
+ return true;
32
+ }
33
+ }
34
+ return false;
35
+ }
36
+ export function validateGitRef(rawRef) {
37
+ const ref = rawRef.trim();
38
+ if (!ref ||
39
+ ref.startsWith("-") ||
40
+ ref.startsWith("/") ||
41
+ ref.endsWith("/") ||
42
+ ref.endsWith(".") ||
43
+ hasControlChar(ref) ||
44
+ /[\s:~^?*[\\]/u.test(ref) ||
45
+ ref.includes("..") ||
46
+ ref.includes("@{") ||
47
+ ref.includes("//")) {
48
+ return { ok: false, message: `Invalid Git source ref: ${rawRef}` };
49
+ }
50
+ return { ok: true, normalized: ref };
51
+ }
52
+ export function validateGitSourceUrl(rawUrl) {
53
+ const invalid = { ok: false, message: "Invalid Git URL. Use HTTP(S), SSH, file, or user@host:path without embedded credentials." };
54
+ if (hasControlChar(rawUrl) || /[\s\\]/u.test(rawUrl) || rawUrl.startsWith("-"))
55
+ return invalid;
56
+ if (/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:[^\s?#]+$/u.test(rawUrl))
57
+ return { ok: true, normalized: rawUrl };
58
+ if (!/^(?:https?|ssh|file):\/\//u.test(rawUrl))
59
+ return invalid;
60
+ try {
61
+ const url = new URL(rawUrl);
62
+ if (url.password || (url.username && url.protocol !== "ssh:") || url.search || url.hash)
63
+ return invalid;
64
+ if (url.protocol !== "file:" && !url.hostname)
65
+ return invalid;
66
+ // Keep the SSH alias and transport spelling used by Git in the cache identity.
67
+ return { ok: true, normalized: rawUrl };
68
+ }
69
+ catch {
70
+ return invalid;
71
+ }
72
+ }
73
+ export function isCommitSha(ref) {
74
+ return ref !== undefined && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref);
75
+ }
76
+ function sanitizeErrorMessage(error) {
77
+ const raw = String(error instanceof Error ? error.message : error)
78
+ .replace(/([a-z][a-z0-9+.-]*:\/\/)[^/\s'"]+@/giu, "$1[redacted]@")
79
+ .replace(/([a-z][a-z0-9+.-]*:\/\/[^\s'"?#]+)[?#][^\s'"]*/giu, "$1?[redacted]");
80
+ const lines = raw
81
+ .split(/\r?\n/u)
82
+ .map((line) => line.trim())
83
+ .filter(Boolean);
84
+ const primary = lines.find((line) => /^(?:fatal|error):/iu.test(line)) ??
85
+ lines[0] ??
86
+ "Unknown error";
87
+ return primary.replace(/\.+$/u, "").slice(0, 240);
88
+ }
89
+ function envMs(key, fallback) {
90
+ const raw = process.env[key];
91
+ const n = Number(raw);
92
+ return raw && Number.isSafeInteger(n) && n > 0 && n <= 2_147_483_647 ? n : fallback;
93
+ }
94
+ function git(args, cwd, deadline) {
95
+ const timeout = Math.min(envMs("LLMDOC_GIT_TIMEOUT_MS", DEFAULT_SOURCE_GIT_TIMEOUT_MS), deadline - Date.now());
96
+ if (timeout <= 0)
97
+ throw new Error("Git operation timed out");
98
+ const env = {
99
+ ...process.env,
100
+ GIT_TERMINAL_PROMPT: "0",
101
+ GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? "ssh -o BatchMode=yes -o ConnectTimeout=10"
102
+ };
103
+ // A caller running inside a Git hook may point these at the consumer's worktree.
104
+ for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"]) {
105
+ delete env[key];
106
+ }
107
+ const result = spawnSync("git", [
108
+ "-c", "protocol.ext.allow=never", "-c", "core.hooksPath=/dev/null", "-c", "submodule.recurse=false", ...args
109
+ ], {
110
+ cwd, encoding: "utf8", timeout, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "pipe"], env
111
+ });
112
+ if (result.error)
113
+ throw result.error;
114
+ if (result.status !== 0)
115
+ throw new Error(sanitizeErrorMessage(result.stderr || `Git exited with status ${result.status}`));
116
+ return result.stdout.trim();
117
+ }
118
+ function hash(input) {
119
+ return createHash("sha256").update(input).digest("hex").slice(0, 24);
120
+ }
121
+ function normalizedConfigDir(config) {
122
+ return config.dir !== undefined ? normalizeSourceSubdir(config.dir) : null;
123
+ }
124
+ function cachePaths(config) {
125
+ const dir = normalizedConfigDir(config);
126
+ const key = hash(JSON.stringify([config.git, config.ref ?? null, dir]));
127
+ const home = getLlmdocHomeDir();
128
+ const cache = path.join(home, "sources", "v1", key);
129
+ const mirror = path.join(home, "mirrors", "v1", hash(config.git) + ".git");
130
+ return { cache, mirror, dir, statePath: path.join(cache, "state.json"), snapshots: path.join(cache, "snapshots") };
131
+ }
132
+ function readState(config) {
133
+ const dir = normalizedConfigDir(config);
134
+ const empty = {
135
+ url: config.git, ref: config.ref ?? null, dir, pinned: isCommitSha(config.ref), currentSnapshot: null, revision: null,
136
+ lastSyncedAt: null, lastAttemptAt: null, lastError: null, cooldownUntil: null
137
+ };
138
+ const { statePath } = cachePaths(config);
139
+ try {
140
+ const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
141
+ if (state.url !== empty.url ||
142
+ state.ref !== empty.ref ||
143
+ (state.dir ?? null) !== empty.dir ||
144
+ !(state.currentSnapshot === null || (typeof state.currentSnapshot === "string" && /^[a-zA-Z0-9_-]+$/u.test(state.currentSnapshot))) ||
145
+ !(state.revision === null || isCommitSha(state.revision))) {
146
+ throw new Error("Invalid snapshot state");
147
+ }
148
+ for (const key of ["lastSyncedAt", "lastAttemptAt", "lastError", "cooldownUntil"]) {
149
+ if (state[key] !== null && typeof state[key] !== "string")
150
+ throw new Error("Invalid snapshot metadata");
151
+ }
152
+ return { ...state, dir: empty.dir, pinned: empty.pinned };
153
+ }
154
+ catch (error) {
155
+ if (error.code !== "ENOENT") {
156
+ empty.lastError = "Invalid snapshot metadata; refresh this source to rebuild its cache";
157
+ }
158
+ return empty;
159
+ }
160
+ }
161
+ function privateDir(dir) {
162
+ fs.mkdirSync(dir, { mode: 0o700, recursive: true });
163
+ }
164
+ function writeState(target, state) {
165
+ const tmp = target + "." + randomUUID();
166
+ try {
167
+ fs.writeFileSync(tmp, JSON.stringify(state), { mode: 0o600, flag: "wx" });
168
+ fs.renameSync(tmp, target);
169
+ }
170
+ finally {
171
+ fs.rmSync(tmp, { force: true });
172
+ }
173
+ }
174
+ function inCooldown(state) {
175
+ return state.cooldownUntil !== null && Date.parse(state.cooldownUntil) > Date.now();
176
+ }
177
+ function warning(source, message, id) {
178
+ source.issues.push({ severity: "warning", code: "source.document", message, path: id ?? `@${source.name}` });
179
+ }
180
+ function readList(source, data, group, field, id, normalize) {
181
+ const obj = data[group];
182
+ if (obj === undefined)
183
+ return [];
184
+ const values = obj && typeof obj === "object" ? obj[field] : null;
185
+ if (values === undefined)
186
+ return [];
187
+ if (!Array.isArray(values)) {
188
+ warning(source, `Expected a list for ${group}.${field}.`, id);
189
+ return [];
190
+ }
191
+ const result = new Set();
192
+ for (const value of values) {
193
+ try {
194
+ if (typeof value !== "string")
195
+ throw new Error("Expected a string");
196
+ result.add(normalize(value));
197
+ }
198
+ catch (error) {
199
+ warning(source, `Invalid ${group}.${field} entry: ${sanitizeErrorMessage(error)}`, id);
200
+ }
201
+ }
202
+ return [...result];
203
+ }
204
+ function scanDocument(source, absolutePath, sourceRelativePath, mountRepoPath) {
205
+ const id = parseSourceDocId(`@${source.name}/${sourceRelativePath}`).canonicalId;
206
+ if (fs.statSync(absolutePath).size > MAX_SOURCE_DOCUMENT_BYTES) {
207
+ warning(source, `Document exceeds the ${MAX_SOURCE_DOCUMENT_BYTES}-byte limit.`, id);
208
+ return null;
209
+ }
210
+ const raw = fs.readFileSync(absolutePath, "utf8");
211
+ const { hasFrontmatter, data, content } = parseYamlFrontmatter(raw);
212
+ if (!hasFrontmatter || typeof data.description !== "string" || !data.description.trim())
213
+ return null;
214
+ const kind = data.kind;
215
+ const frontmatter = { description: data.description.trim(), kind: "reference" };
216
+ if (kind === "architecture" || kind === "guide" || kind === "reference")
217
+ frontmatter.kind = kind;
218
+ else if (kind !== undefined)
219
+ warning(source, "Unknown document kind; using reference.", id);
220
+ const paths = readList(source, data, "code", "paths", id, normalizeRepoRelativePath);
221
+ if (paths.length)
222
+ frontmatter.code = { paths };
223
+ const requires = readList(source, data, "relations", "requires", id, (value) => {
224
+ const target = parseSourceDocId(value.trim().startsWith("@") ? value : `@${source.name}/${value}`);
225
+ if (target.alias !== source.name)
226
+ throw new Error("Cross-source requirements are ignored");
227
+ return target.canonicalId;
228
+ });
229
+ if (requires.length)
230
+ frontmatter.relations = { requires };
231
+ return {
232
+ absolutePath, repoPath: id, llmdocPath: id, topic: `@${source.name}`, basename: path.basename(absolutePath),
233
+ frontmatter, raw, body: content.trim(), title: extractTitle(content), links: extractLinks(content),
234
+ codeRefs: extractCodeRefs(content), estimatedTokens: estimateTokens(content), lineCount: raw.split(/\r?\n/u).length,
235
+ sourceName: source.name, sourceRelativePath, sourceMountPath: mountRepoPath
236
+ };
237
+ }
238
+ // Follow neither a symlink selected by dir nor a symlink named llmdoc.
239
+ function documentRoot(mount, subdir) {
240
+ let effective = mount;
241
+ if (subdir) {
242
+ effective = resolveInsideRoot(mount, subdir);
243
+ if (effective !== path.join(fs.realpathSync(mount), subdir))
244
+ throw new Error("Source dir traverses a symbolic link");
245
+ }
246
+ if (!fs.statSync(effective).isDirectory())
247
+ throw new Error("Source dir is not a directory");
248
+ const nested = path.join(effective, "llmdoc");
249
+ return fs.lstatSync(nested, { throwIfNoEntry: false })?.isDirectory() ? nested : effective;
250
+ }
251
+ function scan(source, mount, mountRepoPath) {
252
+ source.mountDir = mount;
253
+ const root = documentRoot(mount, source.dir);
254
+ source.docRootDir = root;
255
+ const skipped = new Set([".git", ".llmdoc-tmp", "node_modules"]);
256
+ const seenIds = new Set();
257
+ function visit(dir) {
258
+ const entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
259
+ for (const entry of entries) {
260
+ if (skipped.has(entry.name) || entry.isSymbolicLink())
261
+ continue;
262
+ const file = path.join(dir, entry.name);
263
+ if (entry.isDirectory()) {
264
+ if (!visit(file))
265
+ return false;
266
+ }
267
+ else if (entry.isFile() && /\.mdx?$/u.test(entry.name)) {
268
+ try {
269
+ const doc = scanDocument(source, file, toPosixRelative(root, file), mountRepoPath);
270
+ if (!doc)
271
+ continue;
272
+ if (seenIds.has(doc.llmdocPath)) {
273
+ warning(source, `Duplicate normalized source document ID skipped: ${doc.llmdocPath}`, doc.llmdocPath);
274
+ continue;
275
+ }
276
+ if (source.documents.length === MAX_SOURCE_DOCUMENTS) {
277
+ warning(source, `Source exceeds the ${MAX_SOURCE_DOCUMENTS}-document limit. Remaining documents were skipped.`);
278
+ return false;
279
+ }
280
+ seenIds.add(doc.llmdocPath);
281
+ source.documents.push(doc);
282
+ }
283
+ catch (error) {
284
+ warning(source, sanitizeErrorMessage(error), `@${source.name}/${toPosixRelative(root, file)}`);
285
+ }
286
+ }
287
+ }
288
+ return true;
289
+ }
290
+ visit(root);
291
+ source.status = "ready";
292
+ }
293
+ function loadSource(root, name, config) {
294
+ const source = {
295
+ name, kind: "git" in config ? "git" : "path", target: "git" in config ? "[invalid Git URL]" : config.path,
296
+ ref: "git" in config ? config.ref ?? null : null, dir: null, status: "missing", revision: null, pinned: false,
297
+ mountDir: null, docRootDir: null, isSubmodule: false, lastSyncedAt: null, lastAttemptAt: null,
298
+ stale: false, error: null, remedy: null, documents: [], issues: []
299
+ };
300
+ try {
301
+ if (!isValidSourceAlias(name))
302
+ throw new Error("Invalid source alias");
303
+ if (config.dir !== undefined)
304
+ source.dir = normalizeSourceSubdir(config.dir);
305
+ if ("path" in config) {
306
+ let mount;
307
+ let mountRepoPath;
308
+ if (config.allowOutsideRoot) {
309
+ source.configuredPath = config.path;
310
+ mount = path.resolve(root, config.path);
311
+ const rootReal = fs.realpathSync(root);
312
+ if (fs.existsSync(mount)) {
313
+ const mountReal = fs.realpathSync(mount);
314
+ mountRepoPath = isWithinRoot(rootReal, mountReal) ? toPosixRelative(rootReal, mountReal) : null;
315
+ }
316
+ else {
317
+ mountRepoPath = null;
318
+ }
319
+ }
320
+ else {
321
+ source.configuredPath = normalizeRepoRelativePath(config.path);
322
+ mount = resolveInsideRoot(root, source.configuredPath, { allowMissing: true });
323
+ mountRepoPath = source.configuredPath;
324
+ }
325
+ if (!fs.existsSync(mount) || (fs.statSync(mount).isDirectory() && !fs.readdirSync(mount).length)) {
326
+ if (!config.allowOutsideRoot) {
327
+ const modules = path.join(root, ".gitmodules");
328
+ if (fs.lstatSync(modules, { throwIfNoEntry: false })?.isFile()) {
329
+ try {
330
+ const listing = git(["config", "--null", "--no-includes", "--file", modules, "--list"], root, Infinity);
331
+ source.isSubmodule = listing.split("\0").some(entry => /^submodule\..+\.path\n/u.test(entry) && entry.slice(entry.indexOf("\n") + 1) === source.configuredPath);
332
+ }
333
+ catch {
334
+ source.isSubmodule = false;
335
+ }
336
+ }
337
+ source.remedy = "Run `git submodule update --init` or verify the configured path.";
338
+ }
339
+ else {
340
+ source.remedy = `Verify the local path in llmdoc.config.local.json: ${config.path}`;
341
+ }
342
+ return source;
343
+ }
344
+ if (!fs.statSync(mount).isDirectory()) {
345
+ throw new Error(`Configured path is not a directory: ${config.path}`);
346
+ }
347
+ source.isSubmodule = !config.allowOutsideRoot && fs.existsSync(path.join(mount, ".git"));
348
+ if (fs.existsSync(path.join(mount, ".git"))) {
349
+ try {
350
+ source.revision = git(["-C", mount, "rev-parse", "--verify", "HEAD"], mount, Infinity);
351
+ }
352
+ catch { /* A repository with an unborn branch still has a readable tree. */ }
353
+ }
354
+ scan(source, mount, mountRepoPath);
355
+ }
356
+ else {
357
+ const url = validateGitSourceUrl(config.git);
358
+ if (!url.ok)
359
+ throw new Error(url.message);
360
+ source.target = source.gitUrl = url.normalized;
361
+ source.refreshIntervalMs = parseRefreshDurationMs(config.refresh);
362
+ const state = readState(config);
363
+ source.pinned = state.pinned;
364
+ source.error = state.lastError;
365
+ source.lastSyncedAt = state.lastSyncedAt;
366
+ source.lastAttemptAt = state.lastAttemptAt;
367
+ const snapshot = state.currentSnapshot && path.join(cachePaths(config).snapshots, state.currentSnapshot);
368
+ if (!snapshot || !fs.lstatSync(snapshot, { throwIfNoEntry: false })?.isDirectory()) {
369
+ if (state.lastError) {
370
+ source.status = "error";
371
+ source.remedy = "Verify the git URL, ref, credentials, and network access, then retry `npx -y @tokenroll/llmdoc status --refresh`.";
372
+ }
373
+ else {
374
+ source.status = "missing";
375
+ source.remedy = "read this source or run `npx -y @tokenroll/llmdoc status --refresh` to fetch its snapshot.";
376
+ }
377
+ return source;
378
+ }
379
+ source.revision = state.revision;
380
+ source.stale = !state.pinned && (!state.lastSyncedAt || Date.now() - Date.parse(state.lastSyncedAt) >= source.refreshIntervalMs);
381
+ scan(source, snapshot, null);
382
+ if (source.error)
383
+ source.remedy = "Verify Git access and retry `npx -y @tokenroll/llmdoc status --refresh`.";
384
+ }
385
+ }
386
+ catch (error) {
387
+ source.status = "error";
388
+ source.documents = [];
389
+ source.error = sanitizeErrorMessage(error);
390
+ source.remedy = "Verify the source configuration and that its directory is readable.";
391
+ }
392
+ return source;
393
+ }
394
+ function indexSources(sources) {
395
+ const sourceDocuments = sources.flatMap(source => source.documents);
396
+ return {
397
+ sources,
398
+ sourcesByName: new Map(sources.map(s => [s.name, s])),
399
+ sourceDocuments,
400
+ sourceDocumentsById: new Map(sourceDocuments.map(doc => [doc.llmdocPath, doc]))
401
+ };
402
+ }
403
+ export function loadSourcesReadOnly(rootDir, sourcesConfig) {
404
+ return indexSources(Object.entries(sourcesConfig).map(([name, config]) => loadSource(rootDir, name, config)));
405
+ }
406
+ export function toSourceSummary(source) {
407
+ const { name, kind, target, ref, dir, status, revision, pinned, isSubmodule, lastSyncedAt, stale, error, remedy } = source;
408
+ return {
409
+ name, kind, target, ref, dir, status, documentCount: source.documents.length, revision, pinned,
410
+ isSubmodule, lastSyncedAt, stale, error, remedy
411
+ };
412
+ }
413
+ export function sourceDocumentMatchesPath(document, repoRelativePath) {
414
+ if (!document.sourceName)
415
+ return false;
416
+ let candidate = repoRelativePath;
417
+ if (document.sourceMountPath) {
418
+ const prefix = document.sourceMountPath + "/";
419
+ if (!candidate.startsWith(prefix))
420
+ return false;
421
+ candidate = candidate.slice(prefix.length);
422
+ }
423
+ return (document.frontmatter.code?.paths ?? []).some(pattern => matchesCodePathPattern(pattern, candidate));
424
+ }
425
+ function sleepMs(duration) {
426
+ if (duration > 0) {
427
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, duration);
428
+ }
429
+ }
430
+ function lockFile(file, waitUntilMs = 0) {
431
+ for (;;) {
432
+ let fd;
433
+ try {
434
+ fd = fs.openSync(file, "wx", 0o600);
435
+ }
436
+ catch (error) {
437
+ if (error.code !== "EEXIST")
438
+ throw error;
439
+ const stat = fs.statSync(file, { throwIfNoEntry: false });
440
+ if (!stat)
441
+ continue;
442
+ let stale = Date.now() - stat.mtimeMs > DEFAULT_SOURCE_LOCK_STALE_MS;
443
+ try {
444
+ const owner = JSON.parse(fs.readFileSync(file, "utf8"));
445
+ if (Number.isInteger(owner.pid) && owner.pid > 0) {
446
+ try {
447
+ process.kill(owner.pid, 0);
448
+ }
449
+ catch (err) {
450
+ if (err.code === "ESRCH")
451
+ stale = true;
452
+ }
453
+ }
454
+ if (Date.now() - Date.parse(owner.createdAt) > DEFAULT_SOURCE_LOCK_STALE_MS)
455
+ stale = true;
456
+ }
457
+ catch { /* An owner may still be writing its metadata. */ }
458
+ if (stale) {
459
+ if (fs.statSync(file, { throwIfNoEntry: false })?.ino === stat.ino)
460
+ fs.rmSync(file, { force: true });
461
+ continue;
462
+ }
463
+ const remaining = waitUntilMs - Date.now();
464
+ if (remaining > 0) {
465
+ sleepMs(Math.min(100, remaining));
466
+ continue;
467
+ }
468
+ return null;
469
+ }
470
+ const own = fs.fstatSync(fd);
471
+ const release = () => {
472
+ if (fs.statSync(file, { throwIfNoEntry: false })?.ino === own.ino)
473
+ fs.rmSync(file, { force: true });
474
+ fs.closeSync(fd);
475
+ };
476
+ try {
477
+ fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }));
478
+ return release;
479
+ }
480
+ catch (error) {
481
+ release();
482
+ throw error;
483
+ }
484
+ }
485
+ }
486
+ function fetchRevision(config, mirror, deadline) {
487
+ const refCheck = validateGitRef(config.ref ?? "HEAD");
488
+ if (!refCheck.ok) {
489
+ throw new Error(refCheck.message);
490
+ }
491
+ const ref = refCheck.normalized;
492
+ for (let attempt = 0;; attempt++) {
493
+ try {
494
+ git(["fetch", "--quiet", "--no-recurse-submodules", "--no-tags", "--", config.git, ref], mirror, deadline);
495
+ break;
496
+ }
497
+ catch (error) {
498
+ const message = sanitizeErrorMessage(error);
499
+ const permanent = /permission denied|authentication failed|host key verification failed|could not read username|not found|not a git repository|repository .* does not exist|returned error: (401|403|404)|couldn't find remote ref/iu;
500
+ const transient = /ETIMEDOUT|timed out|could not resolve host|connection reset|failed to connect|unable to access/iu;
501
+ const delay = 100 * 2 ** attempt;
502
+ if (attempt >= DEFAULT_SOURCE_MAX_RETRIES || permanent.test(message) || !transient.test(message) ||
503
+ Date.now() + delay >= deadline)
504
+ throw error;
505
+ sleepMs(delay);
506
+ }
507
+ }
508
+ const revision = git(["rev-parse", "--verify", "FETCH_HEAD^{commit}"], mirror, deadline);
509
+ if (!isCommitSha(revision))
510
+ throw new Error("Git returned an invalid commit ID");
511
+ return revision;
512
+ }
513
+ function protectFiles(dir) {
514
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
515
+ const file = path.join(dir, entry.name);
516
+ if (entry.isDirectory())
517
+ protectFiles(file);
518
+ if (entry.isFile())
519
+ fs.chmodSync(file, fs.statSync(file).mode & 0o555);
520
+ }
521
+ }
522
+ function hasGitTree(mirror, revision, treePath, deadline) {
523
+ const output = git(["ls-tree", "-d", "--name-only", revision, "--", treePath], mirror, deadline);
524
+ return output.split(/\r?\n/u).some((line) => line.trim() === treePath);
525
+ }
526
+ function exportSnapshot(mirror, snapshots, revision, dir, deadline) {
527
+ privateDir(snapshots);
528
+ const tmp = fs.mkdtempSync(path.join(snapshots, ".tmp-"));
529
+ try {
530
+ // Export only the minimal documentation subtree when `dir` or `llmdoc/` exists,
531
+ // avoiding checking out tens of thousands of unrelated source files from large repos.
532
+ let checkoutPath = null;
533
+ if (dir) {
534
+ const nestedLlmdoc = `${dir}/llmdoc`;
535
+ if (hasGitTree(mirror, revision, nestedLlmdoc, deadline)) {
536
+ checkoutPath = nestedLlmdoc;
537
+ }
538
+ else if (hasGitTree(mirror, revision, dir, deadline)) {
539
+ checkoutPath = dir;
540
+ }
541
+ else {
542
+ throw new Error(`Configured dir "${dir}" does not exist in revision ${revision.slice(0, 7)}`);
543
+ }
544
+ }
545
+ else if (hasGitTree(mirror, revision, "llmdoc", deadline)) {
546
+ checkoutPath = "llmdoc";
547
+ }
548
+ else {
549
+ const tree = git(["ls-tree", "--name-only", revision], mirror, deadline);
550
+ checkoutPath = tree ? "." : null;
551
+ }
552
+ if (checkoutPath) {
553
+ git([`--git-dir=${mirror}`, `--work-tree=${tmp}`, "checkout", "--force", "--no-overlay", revision, "--", checkoutPath], tmp, deadline);
554
+ }
555
+ documentRoot(tmp, dir);
556
+ protectFiles(tmp);
557
+ const generation = randomUUID();
558
+ fs.renameSync(tmp, path.join(snapshots, generation));
559
+ return generation;
560
+ }
561
+ finally {
562
+ fs.rmSync(tmp, { force: true, recursive: true });
563
+ }
564
+ }
565
+ function syncSource(config, mode, deadline) {
566
+ const { cache, mirror, dir, statePath, snapshots } = cachePaths(config);
567
+ privateDir(cache);
568
+ privateDir(path.dirname(mirror));
569
+ const waitUntil = mode === "due" ? 0 : Math.min(deadline, Date.now() + 2_500);
570
+ const release = lockFile(path.join(cache, ".lock"), waitUntil);
571
+ if (!release) {
572
+ return mode === "force"
573
+ ? { error: "Another process is currently syncing this source cache; retry shortly" }
574
+ : "skipped";
575
+ }
576
+ try {
577
+ const state = readState(config);
578
+ const previous = state.currentSnapshot;
579
+ const ready = !!previous && !!fs.lstatSync(path.join(snapshots, previous), { throwIfNoEntry: false })?.isDirectory();
580
+ if (mode !== "force" && inCooldown(state))
581
+ return "skipped";
582
+ if (mode === "cold" && ready)
583
+ return "skipped";
584
+ if (mode === "due" && (!ready || state.pinned || (state.lastSyncedAt &&
585
+ Date.now() - Date.parse(state.lastSyncedAt) < parseRefreshDurationMs(config.refresh))))
586
+ return "skipped";
587
+ // FETCH_HEAD and the checkout index are shared by every ref of this URL.
588
+ const releaseMirror = lockFile(mirror + ".lock", waitUntil);
589
+ if (!releaseMirror) {
590
+ return mode === "force"
591
+ ? { error: "Another process is currently updating this Git mirror; retry shortly" }
592
+ : "skipped";
593
+ }
594
+ let generation = null;
595
+ try {
596
+ state.lastAttemptAt = new Date().toISOString();
597
+ if (!fs.existsSync(path.join(mirror, "HEAD"))) {
598
+ privateDir(mirror);
599
+ git(["init", "--bare", "--quiet", mirror], cache, deadline);
600
+ }
601
+ const revision = fetchRevision(config, mirror, deadline);
602
+ if (state.revision && state.revision !== revision) {
603
+ try {
604
+ git(["merge-base", "--is-ancestor", state.revision, revision], mirror, deadline);
605
+ }
606
+ catch (error) {
607
+ throw new Error(`Cannot verify a fast-forward update; keeping the previous snapshot (${sanitizeErrorMessage(error)})`);
608
+ }
609
+ }
610
+ if (!ready || revision !== state.revision) {
611
+ generation = exportSnapshot(mirror, snapshots, revision, dir, deadline);
612
+ }
613
+ // Keep each published revision reachable even after fetching another ref.
614
+ git(["update-ref", "refs/llmdoc/" + path.basename(cache), revision], mirror, deadline);
615
+ writeState(statePath, {
616
+ ...state,
617
+ currentSnapshot: generation ?? previous,
618
+ revision,
619
+ lastSyncedAt: new Date().toISOString(),
620
+ lastError: null,
621
+ cooldownUntil: null
622
+ });
623
+ }
624
+ catch (error) {
625
+ if (generation)
626
+ fs.rmSync(path.join(snapshots, generation), { force: true, recursive: true });
627
+ const message = sanitizeErrorMessage(error);
628
+ writeState(statePath, {
629
+ ...state,
630
+ lastError: message,
631
+ cooldownUntil: new Date(Date.now() + envMs("LLMDOC_COOLDOWN_MS", DEFAULT_SOURCE_COOLDOWN_MS)).toISOString()
632
+ });
633
+ return { error: message };
634
+ }
635
+ finally {
636
+ releaseMirror();
637
+ }
638
+ if (generation) {
639
+ for (const entry of fs.readdirSync(snapshots, { withFileTypes: true })) {
640
+ if (entry.isDirectory() && entry.name !== generation && entry.name !== previous) {
641
+ fs.rmSync(path.join(snapshots, entry.name), { recursive: true, force: true });
642
+ }
643
+ }
644
+ }
645
+ return generation ? "refreshed" : "unchanged";
646
+ }
647
+ finally {
648
+ release();
649
+ }
650
+ }
651
+ function runSync(workspace, mode, aliases) {
652
+ const results = new Map();
653
+ const outcomes = new Map();
654
+ const configs = workspace.llmdocConfig.sources;
655
+ const deadline = Date.now() + envMs("LLMDOC_COLD_WALL_TIMEOUT_MS", DEFAULT_SOURCE_COLD_WALL_TIMEOUT_MS);
656
+ for (const source of workspace.sources) {
657
+ if (source.kind !== "git" || !source.gitUrl || (aliases && !aliases.includes(source.name)))
658
+ continue;
659
+ if (mode === "cold" && source.status === "ready")
660
+ continue;
661
+ if (mode === "due" && (source.status !== "ready" || !source.stale))
662
+ continue;
663
+ const config = configs[source.name];
664
+ if (!config || !("git" in config))
665
+ continue;
666
+ const key = cachePaths(config).cache;
667
+ let outcome = outcomes.get(key);
668
+ if (outcome === undefined) {
669
+ if (Date.now() >= deadline) {
670
+ outcome = { error: "Source sync exceeded the command time limit" };
671
+ }
672
+ else {
673
+ try {
674
+ outcome = syncSource(config, mode, deadline);
675
+ }
676
+ catch (error) {
677
+ outcome = { error: sanitizeErrorMessage(error) };
678
+ }
679
+ }
680
+ outcomes.set(key, outcome);
681
+ }
682
+ results.set(source.name, outcome);
683
+ }
684
+ if (outcomes.size) {
685
+ const updated = workspace.sources.map(source => {
686
+ const config = configs[source.name];
687
+ if (!config || !("git" in config))
688
+ return source;
689
+ const key = cachePaths(config).cache;
690
+ if (!outcomes.has(key))
691
+ return source;
692
+ const reloaded = loadSource(workspace.rootDir, source.name, config);
693
+ const outcome = outcomes.get(key);
694
+ if (outcome && typeof outcome === "object" && !reloaded.error) {
695
+ reloaded.error = outcome.error;
696
+ }
697
+ return reloaded;
698
+ });
699
+ Object.assign(workspace, indexSources(updated));
700
+ }
701
+ return results;
702
+ }
703
+ export function ensureSourcesForRead(workspace, targetAliases) {
704
+ const fetched = [];
705
+ const warnings = [];
706
+ const results = runSync(workspace, "cold", targetAliases);
707
+ for (const [name, outcome] of results) {
708
+ if (outcome === "skipped")
709
+ continue;
710
+ fetched.push(name);
711
+ if (typeof outcome === "object")
712
+ warnings.push(`@${name}: ${outcome.error}`);
713
+ for (const issue of workspace.sourcesByName.get(name)?.issues ?? [])
714
+ warnings.push(`${issue.path}: ${issue.message}`);
715
+ }
716
+ return { fetched, warnings };
717
+ }
718
+ export function refreshGitSources(workspace, options) {
719
+ const refreshed = [];
720
+ const unchanged = [];
721
+ const failed = [];
722
+ for (const [name, outcome] of runSync(workspace, options?.force ? "force" : "due", options?.aliases)) {
723
+ if (outcome === "refreshed")
724
+ refreshed.push(name);
725
+ if (outcome === "unchanged")
726
+ unchanged.push(name);
727
+ if (typeof outcome === "object")
728
+ failed.push({ name, error: outcome.error });
729
+ }
730
+ return { refreshed, unchanged, failed };
731
+ }
732
+ export function triggerBackgroundRefreshIfNeeded(workspace) {
733
+ if (process.env.LLMDOC_DISABLE_BG_REFRESH === "1")
734
+ return false;
735
+ const due = workspace.sources.some(source => {
736
+ if (source.kind !== "git" || source.status !== "ready" || !source.stale)
737
+ return false;
738
+ const config = workspace.llmdocConfig.sources[source.name];
739
+ if (!config || !("git" in config))
740
+ return false;
741
+ const { cache } = cachePaths(config);
742
+ return !inCooldown(readState(config)) && !fs.existsSync(path.join(cache, ".lock"));
743
+ });
744
+ if (!due)
745
+ return false;
746
+ const entry = path.join(packageRootFromImport(import.meta.url), "dist", "bin", "llmdoc.js");
747
+ if (!fs.existsSync(entry))
748
+ return false;
749
+ try {
750
+ const child = spawn(process.execPath, [entry, "_refresh-sources", "--cwd", workspace.rootDir], {
751
+ detached: true, stdio: "ignore"
752
+ });
753
+ child.on("error", () => { });
754
+ child.unref();
755
+ return child.pid !== undefined;
756
+ }
757
+ catch {
758
+ return false;
759
+ }
760
+ }