@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
@@ -1,14 +1,51 @@
1
- import { paginate } from "../lib/pagination.js";
1
+ import { paginate, paginationMetadata } from "../lib/pagination.js";
2
2
  import { assertDocumentKind } from "../lib/doc-shape.js";
3
+ import { CliError } from "../lib/errors.js";
3
4
  import { loadWorkspace } from "../lib/workspace.js";
4
5
  import { formatPaginationSummary } from "../lib/format.js";
5
- import { paginationMetadata } from "../lib/pagination.js";
6
6
  import { estimateTokens } from "../lib/markdown.js";
7
+ import { formatDocumentPath, isSourceRef, matchesDocumentTopic, parseSourceTopicFilter } from "../lib/source-id.js";
8
+ import { ensureSourcesForRead } from "../lib/sources.js";
7
9
  export function runIndex(options) {
8
10
  const workspace = loadWorkspace(options.cwd);
9
11
  const kind = options.kind ? assertDocumentKind(options.kind) : undefined;
10
- const filtered = workspace.documents.filter((document) => {
11
- if (options.topic && document.topic !== options.topic) {
12
+ const warnings = [];
13
+ const warnedAliases = new Set();
14
+ if (options.topic && isSourceRef(options.topic)) {
15
+ const parsedTopic = parseSourceTopicFilter(options.topic);
16
+ if (!workspace.sourcesByName.has(parsedTopic.alias)) {
17
+ throw new CliError(`Unknown source: @${parsedTopic.alias}`);
18
+ }
19
+ const cold = ensureSourcesForRead(workspace, [parsedTopic.alias]);
20
+ warnings.push(...cold.warnings);
21
+ if (cold.warnings.length > 0) {
22
+ warnedAliases.add(parsedTopic.alias);
23
+ }
24
+ const source = workspace.sourcesByName.get(parsedTopic.alias);
25
+ if (source && source.status !== "ready" && !warnedAliases.has(source.name)) {
26
+ warnedAliases.add(source.name);
27
+ warnings.push(`Source @${source.name} is unavailable: ${source.error ?? "no local snapshot"}.${source.remedy ? ` ${source.remedy}` : ""}`);
28
+ }
29
+ }
30
+ else if (!options.topic && workspace.sources.length > 0) {
31
+ const cold = ensureSourcesForRead(workspace);
32
+ warnings.push(...cold.warnings);
33
+ for (const fetchedAlias of cold.fetched) {
34
+ const source = workspace.sourcesByName.get(fetchedAlias);
35
+ if (source && source.status !== "ready") {
36
+ warnedAliases.add(fetchedAlias);
37
+ }
38
+ }
39
+ for (const source of workspace.sources) {
40
+ if (source.status !== "ready" && !warnedAliases.has(source.name)) {
41
+ warnedAliases.add(source.name);
42
+ warnings.push(`Source @${source.name} is unavailable: ${source.error ?? "no local snapshot"}.${source.remedy ? ` ${source.remedy}` : ""}`);
43
+ }
44
+ }
45
+ }
46
+ const allDocuments = [...workspace.documents, ...workspace.sourceDocuments];
47
+ const filtered = allDocuments.filter((document) => {
48
+ if (options.topic && !matchesDocumentTopic(document, options.topic)) {
12
49
  return false;
13
50
  }
14
51
  if (kind && document.frontmatter.kind !== kind) {
@@ -24,12 +61,19 @@ export function runIndex(options) {
24
61
  if (options.json) {
25
62
  return {
26
63
  documents: result.items.map(toPayload),
64
+ ...(warnings.length > 0 ? { warnings } : {}),
27
65
  pagination: paginationMetadata(result)
28
66
  };
29
67
  }
30
68
  const lines = [];
69
+ for (const warning of warnings) {
70
+ lines.push(`warning: ${warning}`);
71
+ }
72
+ if (warnings.length > 0 && result.items.length > 0) {
73
+ lines.push("");
74
+ }
31
75
  for (const document of result.items) {
32
- lines.push(`llmdoc/${document.llmdocPath} [${document.frontmatter.kind}]`);
76
+ lines.push(`${formatDocumentPath(document)} [${document.frontmatter.kind}]`);
33
77
  lines.push(` ${document.frontmatter.description}`);
34
78
  if (document.frontmatter.relations?.requires?.length) {
35
79
  lines.push(` requires: ${document.frontmatter.relations.requires.join(", ")}`);
@@ -44,10 +88,11 @@ export function runIndex(options) {
44
88
  }
45
89
  function toPayload(document) {
46
90
  return {
47
- path: `llmdoc/${document.llmdocPath}`,
91
+ path: formatDocumentPath(document),
48
92
  kind: document.frontmatter.kind,
49
93
  description: document.frontmatter.description,
50
94
  relations: document.frontmatter.relations ?? {},
51
- code: document.frontmatter.code ?? {}
95
+ code: document.frontmatter.code ?? {},
96
+ ...(document.sourceName ? { source: document.sourceName } : {})
52
97
  };
53
98
  }
@@ -11,17 +11,17 @@ export function runInitState(options) {
11
11
  const rootDir = findProjectRoot(options.cwd);
12
12
  const workspace = loadWorkspace(rootDir);
13
13
  if (workspace.meta) {
14
- throw new CliError("llmdoc/meta.json 已存在;init-state 只用于首次建立台账,不覆盖现有状态。");
14
+ throw new CliError("llmdoc/meta.json already exists; init-state creates only the initial ledger and never overwrites it.");
15
15
  }
16
16
  const git = readWorkspaceGitState(workspace);
17
17
  if (!git.available) {
18
- throw new CliError("init-state 需要 Git 仓库;请先运行 `git init` 并创建一次真实的初始提交。");
18
+ throw new CliError("init-state requires a Git repository. Run `git init` and create a real initial commit first.");
19
19
  }
20
20
  if (!git.headRevision) {
21
21
  if (isUnbornHead(rootDir)) {
22
- throw new CliError("HEAD 尚无 commit(当前分支尚未创建首次提交)。请先创建一次真实的初始提交;空仓库可运行 `git commit --allow-empty -m \"chore: initial commit\"`。");
22
+ throw new CliError("HEAD has no commit (the current branch is unborn). Create a real initial commit first; an empty repository can run `git commit --allow-empty -m \"chore: initial commit\"`.");
23
23
  }
24
- throw new CliError(`${git.degradedReason ?? "无法解析 HEAD commit。"}请先修复 Git HEAD,再运行 init-state。`);
24
+ throw new CliError(`${git.degradedReason ?? "Unable to resolve the HEAD commit."} Repair Git HEAD before running init-state.`);
25
25
  }
26
26
  const now = new Date().toISOString().replace(/\.\d+Z$/, "Z");
27
27
  const meta = {
@@ -47,5 +47,5 @@ export function runInitState(options) {
47
47
  next: "npx -y @tokenroll/llmdoc validate && npx -y @tokenroll/llmdoc commit --all -m \"docs: bootstrap llmdoc\""
48
48
  };
49
49
  }
50
- return `initialized llmdoc/meta.json: ${workspace.documents.length} documents (validatedRevision: null), baseline ${git.headRevision.slice(0, 7)}\nnext: 先运行 \`npx -y @tokenroll/llmdoc validate\`;全部通过后运行 \`npx -y @tokenroll/llmdoc commit --all -m "docs: bootstrap llmdoc"\` 收尾`;
50
+ return `initialized llmdoc/meta.json: ${workspace.documents.length} documents (validatedRevision: null), baseline ${git.headRevision.slice(0, 7)}\nnext: Run \`npx -y @tokenroll/llmdoc validate\` first. After it passes, finish with \`npx -y @tokenroll/llmdoc commit --all -m "docs: bootstrap llmdoc"\`.`;
51
51
  }
@@ -6,40 +6,54 @@ import { findProjectRoot, normalizeRepoRelativePath, repoPath, resolveInsideRoot
6
6
  import { gitMove, gitRestorePaths } from "../lib/git.js";
7
7
  import { updateDocumentForMove, writeFileIfChanged } from "../lib/rewrite.js";
8
8
  import { loadWorkspace } from "../lib/workspace.js";
9
+ import { LLMDOC_CONFIG_FILENAME, rewriteStartupPreloadForMove } from "../lib/config.js";
10
+ import { isSourceRef } from "../lib/source-id.js";
9
11
  export function runMove(options) {
12
+ if (isSourceRef(options.from) || isSourceRef(options.to)) {
13
+ throw new CliError("External source documents (@...) are read-only and cannot be moved with mv.");
14
+ }
10
15
  const rootDir = findProjectRoot(options.cwd);
11
16
  const fromRepoPath = normalizeRepoRelativePath(options.from.startsWith("llmdoc/") ? options.from : `llmdoc/${options.from}`);
12
17
  const toRepoPath = normalizeRepoRelativePath(options.to.startsWith("llmdoc/") ? options.to : `llmdoc/${options.to}`);
18
+ const toFirstSegment = toRepoPath.startsWith("llmdoc/") ? toRepoPath.slice("llmdoc/".length).split("/")[0] : "";
19
+ if (toFirstSegment?.startsWith("@")) {
20
+ throw new CliError(`Local topic names cannot start with "@", which is reserved for external sources: ${toFirstSegment}`);
21
+ }
13
22
  const fromAbsolutePath = resolveInsideRoot(rootDir, fromRepoPath);
14
23
  if (!fromRepoPath.startsWith("llmdoc/") || !toRepoPath.startsWith("llmdoc/")) {
15
- throw new CliError("mv 仅支持 llmdoc/ 内部移动。");
24
+ throw new CliError("mv supports moves only within llmdoc/.");
16
25
  }
17
26
  if (fromRepoPath === "llmdoc/meta.json" || toRepoPath === "llmdoc/meta.json") {
18
- throw new CliError("mv 不允许移动 meta.json。");
27
+ throw new CliError("mv cannot move meta.json.");
19
28
  }
20
29
  const fromStats = fs.statSync(fromAbsolutePath);
21
30
  const beforeWorkspace = loadWorkspace(rootDir);
22
31
  if (fromStats.isDirectory()) {
23
32
  if (!isDirectTopicDirectory(fromRepoPath) || !isDirectTopicDirectory(toRepoPath)) {
24
- throw new CliError("topic 目录重命名仅允许 llmdoc/<topic> -> llmdoc/<topic>。");
33
+ throw new CliError("Topic renames must use llmdoc/<topic> -> llmdoc/<topic>.");
25
34
  }
26
35
  }
27
36
  else {
28
37
  if (!fromRepoPath.endsWith(".mdx") || !toRepoPath.endsWith(".mdx")) {
29
- throw new CliError("mv 仅允许移动 .mdx 文档。");
38
+ throw new CliError("mv can move only .mdx documents.");
30
39
  }
31
40
  const fromDocument = beforeWorkspace.documents.find((document) => document.repoPath === fromRepoPath);
32
41
  if (!fromDocument) {
33
- throw new CliError("mv 仅允许移动已索引的 llmdoc 文档。");
42
+ throw new CliError("mv can move only indexed llmdoc documents.");
34
43
  }
35
44
  const targetShape = parseDocTargetShape(toRepoPath);
36
45
  validateMoveTargetShape(targetShape);
37
46
  }
38
47
  const toAbsolutePath = resolveInsideRoot(rootDir, toRepoPath, { allowMissing: true });
39
48
  if (fs.existsSync(toAbsolutePath)) {
40
- throw new CliError(`目标已存在: ${toRepoPath}`);
49
+ throw new CliError(`Target already exists: ${toRepoPath}`);
41
50
  }
42
51
  const mapping = buildMoveMapping(beforeWorkspace.documents, beforeWorkspace.llmdocDir, fromAbsolutePath, toAbsolutePath);
52
+ const configRewrite = beforeWorkspace.llmdocConfig.config
53
+ ? rewriteStartupPreloadForMove(beforeWorkspace.llmdocConfig.config, mapping)
54
+ : { config: null, changed: false };
55
+ const configPath = path.join(rootDir, LLMDOC_CONFIG_FILENAME);
56
+ const originalConfig = configRewrite.changed ? fs.readFileSync(configPath, "utf8") : null;
43
57
  // 目标 topic 目录不存在时自动创建(topic 即纯目录,没有入口节点前置要求)。
44
58
  fs.mkdirSync(path.dirname(toAbsolutePath), { recursive: true });
45
59
  gitMove(rootDir, fromRepoPath, toRepoPath);
@@ -70,13 +84,16 @@ export function runMove(options) {
70
84
  const nextMeta = rewriteMeta(refreshedWorkspace.meta, mapping);
71
85
  fs.writeFileSync(refreshedWorkspace.metaPath, `${JSON.stringify(nextMeta, null, 2)}\n`);
72
86
  }
87
+ if (configRewrite.changed && configRewrite.config) {
88
+ fs.writeFileSync(configPath, `${JSON.stringify(configRewrite.config, null, 2)}\n`);
89
+ }
73
90
  }
74
91
  catch (error) {
75
- const rolledBack = rollbackMove(rootDir, toAbsolutePath);
92
+ const rolledBack = rollbackMove(rootDir, toAbsolutePath, configPath, originalConfig);
76
93
  const reason = error instanceof Error ? error.message : String(error);
77
94
  throw new CliError(rolledBack
78
- ? `mv 引用重写阶段失败,llmdoc/ 已回滚到移动前状态: ${reason}`
79
- : `mv 引用重写阶段失败,且自动回滚未完成,请检查 git status -- llmdoc/ 后手动恢复: ${reason}`);
95
+ ? `Reference rewriting failed during mv; llmdoc/ was rolled back to its previous state: ${reason}`
96
+ : `Reference rewriting failed during mv and automatic rollback did not complete. Inspect git status -- llmdoc/ llmdoc.config.json and recover manually: ${reason}`);
80
97
  }
81
98
  if (options.json) {
82
99
  return {
@@ -84,10 +101,11 @@ export function runMove(options) {
84
101
  from: fromRepoPath,
85
102
  to: toRepoPath
86
103
  },
104
+ rewrittenConfig: configRewrite.changed,
87
105
  rewrittenDocuments: [...documentTargets].map((absolutePath) => repoPath(rootDir, absolutePath)).sort()
88
106
  };
89
107
  }
90
- return `moved: ${fromRepoPath} -> ${toRepoPath}`;
108
+ return `moved: ${fromRepoPath} -> ${toRepoPath}${configRewrite.changed ? "; updated llmdoc.config.json startup preload" : ""}`;
91
109
  }
92
110
  function buildMoveMapping(documents, llmdocDir, fromAbsolutePath, toAbsolutePath) {
93
111
  const mapping = [];
@@ -101,7 +119,7 @@ function buildMoveMapping(documents, llmdocDir, fromAbsolutePath, toAbsolutePath
101
119
  return relative.replaceAll(path.sep, "/");
102
120
  }
103
121
  }
104
- throw new CliError(`无法从路径推导 llmdoc 相对路径: ${absolutePath}`);
122
+ throw new CliError(`Unable to derive an llmdoc-relative path from: ${absolutePath}`);
105
123
  };
106
124
  const fromPathIsDirectory = fs.statSync(fromAbsolutePath).isDirectory();
107
125
  if (fromPathIsDirectory) {
@@ -125,10 +143,13 @@ function buildMoveMapping(documents, llmdocDir, fromAbsolutePath, toAbsolutePath
125
143
  }
126
144
  return mapping.sort((left, right) => right.oldLlmdocPath.length - left.oldLlmdocPath.length);
127
145
  }
128
- function rollbackMove(rootDir, toAbsolutePath) {
146
+ function rollbackMove(rootDir, toAbsolutePath, configPath, originalConfig) {
129
147
  try {
130
148
  fs.rmSync(toAbsolutePath, { recursive: true, force: true });
131
149
  gitRestorePaths(rootDir, ["llmdoc"]);
150
+ if (originalConfig !== null) {
151
+ fs.writeFileSync(configPath, originalConfig);
152
+ }
132
153
  return true;
133
154
  }
134
155
  catch {
@@ -4,16 +4,23 @@ import { parseDocTargetShape, assertDocKindMatchesShape, assertDocumentKind } fr
4
4
  import { CliError } from "../lib/errors.js";
5
5
  import { ensureDirectory, findProjectRootForNew, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
6
6
  import { packageRootFromImport } from "../lib/package-root.js";
7
+ import { isSourceRef } from "../lib/source-id.js";
7
8
  import { loadWorkspace } from "../lib/workspace.js";
8
9
  export function runNew(options) {
10
+ if (isSourceRef(options.path)) {
11
+ throw new CliError(`External source documents (@...) are read-only and cannot be created with new: ${options.path}`);
12
+ }
9
13
  const rootDir = findProjectRootForNew(options.cwd);
10
14
  const repoRelativePath = normalizeDocDestination(options.path);
11
15
  const kind = assertDocumentKind(options.kind);
12
16
  const shape = parseDocTargetShape(repoRelativePath);
17
+ if (shape.topic?.startsWith("@")) {
18
+ throw new CliError(`Local topic names cannot start with "@", which is reserved for external sources: ${shape.topic}`);
19
+ }
13
20
  assertDocKindMatchesShape(shape);
14
21
  const absolutePath = resolveInsideRoot(rootDir, repoRelativePath, { allowMissing: true });
15
22
  if (fs.existsSync(absolutePath)) {
16
- throw new CliError(`目标已存在: ${repoRelativePath}`);
23
+ throw new CliError(`Target already exists: ${repoRelativePath}`);
17
24
  }
18
25
  ensureDirectory(absolutePath);
19
26
  const template = readTemplate();
@@ -21,7 +28,7 @@ export function runNew(options) {
21
28
  // description 经 JSON.stringify 得到合法的 YAML double-quoted scalar,防止引号/冒号/换行破坏 front matter;
22
29
  // replace 一律用函数形式,避免 $& 等替换模式展开。
23
30
  const content = template
24
- .replace("__DESCRIPTION__", () => JSON.stringify(options.description ?? "TODO: 补充文档描述。"))
31
+ .replace("__DESCRIPTION__", () => JSON.stringify(options.description ?? "TODO: Add a document description."))
25
32
  .replace("__KIND__", () => kind)
26
33
  .replace("__TITLE__", () => title);
27
34
  const metaExists = fs.existsSync(path.join(rootDir, "llmdoc", "meta.json"));
@@ -32,17 +39,17 @@ export function runNew(options) {
32
39
  created: repoRelativePath,
33
40
  next: metaExists
34
41
  ? null
35
- : "若 HEAD 尚无 commit,请先创建首次 Git 提交;然后运行 `npx -y @tokenroll/llmdoc init-state`。"
42
+ : "If HEAD has no commit, create the initial Git commit, then run `npx -y @tokenroll/llmdoc init-state`."
36
43
  };
37
44
  }
38
45
  return metaExists
39
46
  ? `created: ${repoRelativePath}`
40
- : `created: ${repoRelativePath}\nnext: 若仓库尚无提交,请先创建首次 Git 提交;然后运行 \`npx -y @tokenroll/llmdoc init-state\` 建立台账。`;
47
+ : `created: ${repoRelativePath}\nnext: If the repository has no commit, create the initial Git commit, then run \`npx -y @tokenroll/llmdoc init-state\` to create the ledger.`;
41
48
  }
42
49
  function normalizeDocDestination(input) {
43
50
  const repoRelativePath = normalizeRepoRelativePath(input.startsWith("llmdoc/") ? input : `llmdoc/${input}`);
44
51
  if (!repoRelativePath.startsWith("llmdoc/") || !repoRelativePath.endsWith(".mdx")) {
45
- throw new CliError("new 只能创建 llmdoc/ 下的 .mdx 文档。");
52
+ throw new CliError("new can create only .mdx documents under llmdoc/.");
46
53
  }
47
54
  return repoRelativePath;
48
55
  }
@@ -1,21 +1,24 @@
1
1
  import { FRAGMENT_TOKEN_THRESHOLD } from "../lib/constants.js";
2
+ import { isSourceRef } from "../lib/source-id.js";
2
3
  import { computeGrowthState } from "../lib/state.js";
3
4
  import { loadWorkspace } from "../lib/workspace.js";
4
5
  export function runPrune(options) {
5
6
  if (!options.report) {
6
7
  return options.json
7
- ? { status: "dry_run", message: "prune 当前仅支持 --report。", writable: false }
8
- : "prune 当前仅支持 --report。";
8
+ ? { status: "dry_run", message: "prune currently supports only --report.", writable: false }
9
+ : "prune currently supports only --report.";
9
10
  }
10
11
  const workspace = loadWorkspace(options.cwd);
11
12
  const growth = computeGrowthState(workspace);
12
13
  const duplicateCandidates = findDuplicateCandidates(workspace.documents);
13
14
  const mergeCandidates = findMergeCandidates(workspace.documents);
15
+ const startupPreloads = workspace.llmdocConfig.preloadPaths.map((preloadPath) => isSourceRef(preloadPath) ? preloadPath : `llmdoc/${preloadPath}`);
14
16
  if (options.json) {
15
17
  return {
16
18
  status: "dry_run",
17
19
  writable: false,
18
20
  growth,
21
+ startupPreloads,
19
22
  duplicateCandidates: duplicateCandidates.map((candidate) => ({
20
23
  paths: [`llmdoc/${candidate.left.llmdocPath}`, `llmdoc/${candidate.right.llmdocPath}`],
21
24
  score: candidate.score,
@@ -32,7 +35,15 @@ export function runPrune(options) {
32
35
  const growthLine = growth.baselineDocumentCount === null
33
36
  ? `growth: ${growth.currentDocumentCount} docs, ~${growth.currentTotalEstimatedTokens} tokens (no convergence baseline)`
34
37
  : `growth: ${growth.currentDocumentCount} docs, ~${growth.currentTotalEstimatedTokens} tokens; baseline ${growth.baselineDocumentCount} docs, ~${growth.baselineTotalEstimatedTokens} tokens; delta ${growth.documentDelta}, ~${growth.tokenDelta} tokens; ${growth.exceedsGate ? "above gate" : "below gate"}`;
35
- const lines = [growthLine, ""];
38
+ const lines = [growthLine, "", "startup preload references:"];
39
+ if (startupPreloads.length === 0) {
40
+ lines.push(" none");
41
+ }
42
+ else {
43
+ lines.push(...startupPreloads.map((preloadPath) => ` ${preloadPath}`));
44
+ lines.push(" Keep llmdoc.config.json synchronized when merging or deleting these documents.");
45
+ }
46
+ lines.push("");
36
47
  lines.push("duplicate candidates:");
37
48
  if (duplicateCandidates.length === 0) {
38
49
  lines.push(" none");
@@ -1,12 +1,50 @@
1
1
  import { paginate, paginationMetadata } from "../lib/pagination.js";
2
2
  import { assertDocumentKind } from "../lib/doc-shape.js";
3
+ import { CliError } from "../lib/errors.js";
3
4
  import { loadWorkspace } from "../lib/workspace.js";
4
5
  import { formatPaginationSummary } from "../lib/format.js";
5
6
  import { searchDocuments } from "../lib/search.js";
6
7
  import { estimateTokens } from "../lib/markdown.js";
8
+ import { formatDocumentPath, isSourceRef, parseSourceTopicFilter } from "../lib/source-id.js";
9
+ import { ensureSourcesForRead } from "../lib/sources.js";
10
+ import { recordTelemetryEvent } from "../lib/telemetry.js";
7
11
  export function runSearch(options) {
8
12
  const workspace = loadWorkspace(options.cwd);
9
13
  const kind = options.kind ? assertDocumentKind(options.kind) : undefined;
14
+ const warnings = [];
15
+ const warnedAliases = new Set();
16
+ if (options.topic && isSourceRef(options.topic)) {
17
+ const parsedTopic = parseSourceTopicFilter(options.topic);
18
+ if (!workspace.sourcesByName.has(parsedTopic.alias)) {
19
+ throw new CliError(`Unknown source: @${parsedTopic.alias}`);
20
+ }
21
+ const cold = ensureSourcesForRead(workspace, [parsedTopic.alias]);
22
+ warnings.push(...cold.warnings);
23
+ if (cold.warnings.length > 0) {
24
+ warnedAliases.add(parsedTopic.alias);
25
+ }
26
+ const source = workspace.sourcesByName.get(parsedTopic.alias);
27
+ if (source && source.status !== "ready" && !warnedAliases.has(source.name)) {
28
+ warnedAliases.add(source.name);
29
+ warnings.push(`Source @${source.name} is unavailable: ${source.error ?? "no local snapshot"}.${source.remedy ? ` ${source.remedy}` : ""}`);
30
+ }
31
+ }
32
+ else if (!options.topic && workspace.sources.length > 0) {
33
+ const cold = ensureSourcesForRead(workspace);
34
+ warnings.push(...cold.warnings);
35
+ for (const fetchedAlias of cold.fetched) {
36
+ const source = workspace.sourcesByName.get(fetchedAlias);
37
+ if (source && source.status !== "ready") {
38
+ warnedAliases.add(fetchedAlias);
39
+ }
40
+ }
41
+ for (const source of workspace.sources) {
42
+ if (source.status !== "ready" && !warnedAliases.has(source.name)) {
43
+ warnedAliases.add(source.name);
44
+ warnings.push(`Source @${source.name} is unavailable: ${source.error ?? "no local snapshot"}.${source.remedy ? ` ${source.remedy}` : ""}`);
45
+ }
46
+ }
47
+ }
10
48
  const search = searchDocuments(workspace, options.query, {
11
49
  topic: options.topic,
12
50
  kind
@@ -16,20 +54,44 @@ export function runSearch(options) {
16
54
  estimate: (entry) => estimateTokens(JSON.stringify(toPayload(entry))),
17
55
  options
18
56
  });
57
+ const isExternalScopedSearch = Boolean(options.topic && isSourceRef(options.topic));
58
+ if (!isExternalScopedSearch) {
59
+ const localSearch = workspace.sourceDocuments.length > 0 && !options.topic
60
+ ? searchDocuments(workspace, options.query, {
61
+ kind,
62
+ includeSources: false,
63
+ useCache: false
64
+ })
65
+ : search;
66
+ recordTelemetryEvent(workspace.rootDir, {
67
+ type: "search",
68
+ query: options.query,
69
+ mode: localSearch.mode,
70
+ hitCount: localSearch.results.length,
71
+ docs: localSearch.results.slice(0, 10).map((entry) => entry.document.llmdocPath)
72
+ });
73
+ }
19
74
  if (options.json) {
20
75
  return {
21
76
  query: options.query,
22
77
  searchMode: search.mode,
23
78
  results: paginated.items.map(toPayload),
79
+ ...(warnings.length > 0 ? { warnings } : {}),
24
80
  pagination: paginationMetadata(paginated)
25
81
  };
26
82
  }
27
83
  const lines = [];
84
+ for (const warning of warnings) {
85
+ lines.push(`warning: ${warning}`);
86
+ }
87
+ if (warnings.length > 0) {
88
+ lines.push("");
89
+ }
28
90
  if (search.mode === "cjk-bigram-fallback") {
29
- lines.push("note: 中文分词未命中,已使用 CJK bigram 降级检索。", "");
91
+ lines.push("note: Chinese segmentation returned no matches; CJK bigram fallback was used.", "");
30
92
  }
31
93
  for (const entry of paginated.items) {
32
- lines.push(`llmdoc/${entry.document.llmdocPath} [${entry.document.frontmatter.kind}]`);
94
+ lines.push(`${formatDocumentPath(entry.document)} [${entry.document.frontmatter.kind}]`);
33
95
  lines.push(` ${entry.document.frontmatter.description}`);
34
96
  lines.push(` ${entry.snippet}`);
35
97
  lines.push("");
@@ -39,10 +101,11 @@ export function runSearch(options) {
39
101
  }
40
102
  function toPayload(entry) {
41
103
  return {
42
- path: `llmdoc/${entry.document.llmdocPath}`,
104
+ path: formatDocumentPath(entry.document),
43
105
  kind: entry.document.frontmatter.kind,
44
106
  description: entry.document.frontmatter.description,
45
107
  snippet: entry.snippet,
46
- score: entry.score
108
+ score: entry.score,
109
+ ...(entry.document.sourceName ? { source: entry.document.sourceName } : {})
47
110
  };
48
111
  }
@@ -3,7 +3,7 @@ import { createViewerRequestHandler } from "../lib/viewer-http.js";
3
3
  // 长驻前台进程:启动本地 Viewer,Ctrl-C 退出。仅绑定 127.0.0.1,不对外暴露。
4
4
  export async function runServe(options) {
5
5
  const server = await startViewerServer(options.cwd, options.port ?? 4973);
6
- process.stdout.write(`llmdoc viewer: ${server.url} (Ctrl-C 退出)\n`);
6
+ process.stdout.write(`llmdoc viewer: ${server.url} (press Ctrl-C to stop)\n`);
7
7
  await new Promise((resolve, reject) => {
8
8
  const shutdown = () => {
9
9
  process.off("SIGINT", shutdown);
@@ -4,13 +4,42 @@ import { CliError } from "../lib/errors.js";
4
4
  import { DEFAULT_SHOW_BUDGET } from "../lib/constants.js";
5
5
  import { formatPaginationSummary } from "../lib/format.js";
6
6
  import { estimateTokens } from "../lib/markdown.js";
7
+ import { formatDocumentPath, isSourceRef, parseSourceDocId } from "../lib/source-id.js";
8
+ import { ensureSourcesForRead } from "../lib/sources.js";
9
+ import { recordTelemetryEvent } from "../lib/telemetry.js";
7
10
  export function runShow(options) {
8
11
  const workspace = loadWorkspace(options.cwd);
9
- const documents = options.paths.map((rawPath) => {
10
- const normalized = rawPath.startsWith("llmdoc/") ? rawPath.slice("llmdoc/".length) : rawPath;
12
+ const requestedSourceAliases = new Set();
13
+ const parsedRequests = options.paths.map((rawPath) => {
14
+ if (isSourceRef(rawPath)) {
15
+ const parsed = parseSourceDocId(rawPath);
16
+ if (!workspace.sourcesByName.has(parsed.alias)) {
17
+ throw new CliError(`Unknown source: @${parsed.alias}`);
18
+ }
19
+ requestedSourceAliases.add(parsed.alias);
20
+ return { kind: "source", rawPath, parsed };
21
+ }
22
+ return { kind: "local", rawPath };
23
+ });
24
+ if (requestedSourceAliases.size > 0) {
25
+ ensureSourcesForRead(workspace, [...requestedSourceAliases]);
26
+ }
27
+ const documents = parsedRequests.map((request) => {
28
+ if (request.kind === "source") {
29
+ const source = workspace.sourcesByName.get(request.parsed.alias);
30
+ if (!source || source.status !== "ready") {
31
+ throw new CliError(`Source @${request.parsed.alias} is unavailable: ${source?.error ?? "no local snapshot"}.${source?.remedy ? ` ${source.remedy}` : ""}`);
32
+ }
33
+ const document = workspace.sourceDocumentsById.get(request.parsed.canonicalId);
34
+ if (!document) {
35
+ throw new CliError(`Document does not exist in @${request.parsed.alias}: ${request.parsed.canonicalId}`);
36
+ }
37
+ return document;
38
+ }
39
+ const normalized = request.rawPath.startsWith("llmdoc/") ? request.rawPath.slice("llmdoc/".length) : request.rawPath;
11
40
  const document = workspace.documentsByLlmdocPath.get(normalized);
12
41
  if (!document) {
13
- throw new CliError(`文档不存在: ${rawPath}`);
42
+ throw new CliError(`Document does not exist: ${request.rawPath}`);
14
43
  }
15
44
  return document;
16
45
  });
@@ -22,6 +51,10 @@ export function runShow(options) {
22
51
  budget: options.budget ?? DEFAULT_SHOW_BUDGET
23
52
  }
24
53
  });
54
+ recordTelemetryEvent(workspace.rootDir, {
55
+ type: "show",
56
+ docs: result.items.filter((document) => !document.sourceName).map((document) => document.llmdocPath)
57
+ });
25
58
  if (options.json) {
26
59
  return {
27
60
  documents: result.items.map(toDocumentPayload),
@@ -30,7 +63,7 @@ export function runShow(options) {
30
63
  }
31
64
  const lines = [];
32
65
  for (const document of result.items) {
33
- lines.push(`=== llmdoc/${document.llmdocPath} [${document.frontmatter.kind}] ===`);
66
+ lines.push(`=== ${formatDocumentPath(document)} [${document.frontmatter.kind}] ===`);
34
67
  lines.push(document.body);
35
68
  lines.push("");
36
69
  }
@@ -39,9 +72,10 @@ export function runShow(options) {
39
72
  }
40
73
  function toDocumentPayload(document) {
41
74
  return {
42
- path: `llmdoc/${document.llmdocPath}`,
75
+ path: formatDocumentPath(document),
43
76
  kind: document.frontmatter.kind,
44
77
  description: document.frontmatter.description,
45
- body: document.body
78
+ body: document.body,
79
+ ...(document.sourceName ? { source: document.sourceName } : {})
46
80
  };
47
81
  }
@@ -1,29 +1,44 @@
1
1
  import { readRepositoryRevisionHealth } from "../lib/repository-health.js";
2
2
  import { computeGrowthState, analyzeDelta } from "../lib/state.js";
3
+ import { refreshGitSources, toSourceSummary, triggerBackgroundRefreshIfNeeded } from "../lib/sources.js";
3
4
  import { loadWorkspace } from "../lib/workspace.js";
5
+ import { formatSourcesSection } from "./tree.js";
4
6
  export function runStatus(options) {
5
7
  const workspace = loadWorkspace(options.cwd);
8
+ let refreshFailed = [];
9
+ if (options.refresh && workspace.sources.length > 0) {
10
+ refreshFailed = refreshGitSources(workspace, { force: true }).failed;
11
+ }
12
+ else if (workspace.sources.length > 0) {
13
+ triggerBackgroundRefreshIfNeeded(workspace);
14
+ }
6
15
  const delta = analyzeDelta(workspace);
7
16
  const growth = computeGrowthState(workspace);
8
17
  const relevantCommitsBehindHead = readRepositoryRevisionHealth(workspace.rootDir, workspace.meta?.baseline.revision ?? null, delta.git).relevantCommitsBehindHead;
18
+ const sourceSummaries = workspace.sources.map(toSourceSummary);
19
+ const exitCode = options.refresh && refreshFailed.length > 0 ? 1 : 0;
9
20
  if (options.json) {
10
21
  return {
11
- baseline: workspace.meta?.baseline.revision ?? null,
12
- head: delta.git.headRevision,
13
- commitsBehindHead: delta.git.baselineBehindHead,
14
- relevantCommitsBehindHead,
15
- degradedReason: delta.git.degradedReason,
16
- documents: {
17
- total: workspace.documents.length,
18
- impacted: delta.impacts.length,
19
- needsReview: delta.needsReview.length,
20
- dirty: delta.dirtyDocuments.length
21
- },
22
- unmapped: {
23
- committed: delta.unmappedCommittedPaths,
24
- dirty: delta.unmappedDirtyPaths
25
- },
26
- growth
22
+ exitCode,
23
+ output: {
24
+ baseline: workspace.meta?.baseline.revision ?? null,
25
+ head: delta.git.headRevision,
26
+ commitsBehindHead: delta.git.baselineBehindHead,
27
+ relevantCommitsBehindHead,
28
+ degradedReason: delta.git.degradedReason,
29
+ documents: {
30
+ total: workspace.documents.length,
31
+ impacted: delta.impacts.length,
32
+ needsReview: delta.needsReview.length,
33
+ dirty: delta.dirtyDocuments.length
34
+ },
35
+ unmapped: {
36
+ committed: delta.unmappedCommittedPaths,
37
+ dirty: delta.unmappedDirtyPaths
38
+ },
39
+ growth,
40
+ ...(sourceSummaries.length > 0 ? { sources: sourceSummaries } : {})
41
+ }
27
42
  };
28
43
  }
29
44
  const baseline = workspace.meta?.baseline.revision ?? "missing";
@@ -36,16 +51,29 @@ export function runStatus(options) {
36
51
  `baseline: ${baseline} (${behind})`,
37
52
  `documents: ${workspace.documents.length} total / ${delta.impacts.length} impacted / ${delta.needsReview.length} needs-review / ${delta.dirtyDocuments.length} dirty`
38
53
  ];
54
+ const unparsedCount = workspace.unparsedDocPaths?.size ?? 0;
55
+ if (unparsedCount > 0) {
56
+ lines.push(`warning: ${unparsedCount} local document(s) failed to parse and were omitted; run \`npx -y @tokenroll/llmdoc validate\` for details`);
57
+ }
39
58
  if (unmapped.length > 0) {
40
59
  const shown = unmapped.slice(0, 5);
41
60
  const rest = unmapped.length - shown.length;
42
- lines.push(`unmapped changes (${unmapped.length}): ${shown.join(", ")}${rest > 0 ? ` … +${rest} more (--json 查看全部)` : ""}`);
61
+ lines.push(`unmapped changes (${unmapped.length}): ${shown.join(", ")}${rest > 0 ? ` … +${rest} more (use --json for all)` : ""}`);
43
62
  }
44
63
  lines.push(growthLabel);
64
+ if (workspace.sources.length > 0) {
65
+ lines.push("", ...formatSourcesSection(workspace.sources));
66
+ }
67
+ if (refreshFailed.length > 0) {
68
+ lines.push("", `refresh failed (${refreshFailed.length}): ${refreshFailed.map((entry) => `@${entry.name} (${entry.error})`).join("; ")}`);
69
+ }
45
70
  if (delta.git.degradedReason) {
46
71
  lines.push(`degraded: ${delta.git.degradedReason}`);
47
72
  }
48
- return lines.join("\n");
73
+ return {
74
+ exitCode,
75
+ output: lines.join("\n")
76
+ };
49
77
  }
50
78
  function formatBehindLabel(commitsBehindHead, relevantCommitsBehindHead) {
51
79
  if (commitsBehindHead === null) {