@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
@@ -58,7 +58,7 @@ async function loadState() {
58
58
  const response = await fetch("/api/state", { headers: { accept: "application/json" } });
59
59
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
60
60
  const nextState = await response.json();
61
- if (!Array.isArray(nextState.nodes) || !Array.isArray(nextState.edges)) throw new Error("服务返回了无效状态");
61
+ if (!Array.isArray(nextState.nodes) || !Array.isArray(nextState.edges)) throw new Error("The server returned invalid state");
62
62
  state = nextState;
63
63
  topicColors = createTopicColors(state.nodes);
64
64
  if (selectedDocument && !state.nodes.some((node) => node.path === selectedDocument)) selectedDocument = null;
@@ -83,15 +83,15 @@ function renderHeader() {
83
83
  const baseline = state.baseline;
84
84
  const shortRevision = baseline.revision?.slice(0, 7);
85
85
  if (!baseline.revision) {
86
- setChip(elements.statBaseline, "baseline 缺失", "bad");
86
+ setChip(elements.statBaseline, "baseline missing", "bad");
87
87
  } else if (baseline.degradedReason || baseline.relevantBehindHead === null) {
88
- setChip(elements.statBaseline, `baseline ${shortRevision} · 状态未知`, "warn");
88
+ setChip(elements.statBaseline, `baseline ${shortRevision} · status unknown`, "warn");
89
89
  } else if (baseline.relevantBehindHead > 0) {
90
- setChip(elements.statBaseline, `baseline ${shortRevision} · ${baseline.relevantBehindHead} 个源码提交待复核`, "warn");
90
+ setChip(elements.statBaseline, `baseline ${shortRevision} · ${baseline.relevantBehindHead} source commit(s) need review`, "warn");
91
91
  } else if (baseline.metadataOnlyBehind) {
92
- setChip(elements.statBaseline, `baseline ${shortRevision} · metadata-only,知识干净`, "ok");
92
+ setChip(elements.statBaseline, `baseline ${shortRevision} · metadata-only, knowledge clean`, "ok");
93
93
  } else {
94
- setChip(elements.statBaseline, `baseline ${shortRevision} · 最新`, "ok");
94
+ setChip(elements.statBaseline, `baseline ${shortRevision} · current`, "ok");
95
95
  }
96
96
 
97
97
  const validation = state.validate;
@@ -103,9 +103,9 @@ function renderHeader() {
103
103
 
104
104
  const stale = state.nodes.filter((node) => node.status !== "fresh").length;
105
105
  const unmapped = state.delta.unmappedCommittedPaths.length + state.delta.unmappedDirtyPaths.length;
106
- if (stale) setChip(elements.statDelta, `${stale} 份待同步 · 建议 ${state.delta.suggestedMode}`, "warn");
107
- else if (unmapped) setChip(elements.statDelta, `${unmapped} 个未映射变化 · 建议 ${state.delta.suggestedMode}`, "warn");
108
- else setChip(elements.statDelta, "知识面新鲜", "ok");
106
+ if (stale) setChip(elements.statDelta, `${stale} document(s) pending · ${state.delta.suggestedMode} recommended`, "warn");
107
+ else if (unmapped) setChip(elements.statDelta, `${unmapped} unmapped change(s) · ${state.delta.suggestedMode} recommended`, "warn");
108
+ else setChip(elements.statDelta, "knowledge is current", "ok");
109
109
  }
110
110
 
111
111
  function setChip(chip, text, stateClass) {
@@ -154,7 +154,7 @@ function renderSidebar() {
154
154
  fragment.append(item);
155
155
  }
156
156
  }
157
- if (!fragment.childNodes.length) fragment.append(element("div", "empty-list", "没有匹配的文档"));
157
+ if (!fragment.childNodes.length) fragment.append(element("div", "empty-list", "No matching documents"));
158
158
  elements.documentList.replaceChildren(fragment);
159
159
  }
160
160
 
@@ -195,7 +195,7 @@ async function selectDocument(path) {
195
195
  }
196
196
 
197
197
  function showError(message) {
198
- elements.error.textContent = `Viewer 加载失败:${message}`;
198
+ elements.error.textContent = `Viewer load failed: ${message}`;
199
199
  elements.error.hidden = false;
200
200
  }
201
201
 
@@ -9,7 +9,7 @@ const DROP_TAGS = new Set(["EMBED", "FORM", "IFRAME", "INPUT", "LINK", "META", "
9
9
  export function createDetailRenderer({ panel, container, onSelectDocument, getState }) {
10
10
  let activeRequest = null;
11
11
 
12
- function showPlaceholder(message = "选择一个 topic 或文档查看详情") {
12
+ function showPlaceholder(message = "Select a topic or document to view details") {
13
13
  activeRequest?.abort();
14
14
  const placeholder = element("div", "placeholder", message);
15
15
  container.replaceChildren(placeholder);
@@ -31,7 +31,7 @@ export function createDetailRenderer({ panel, container, onSelectDocument, getSt
31
31
  const description = element(
32
32
  "div",
33
33
  "desc",
34
- `${documents.length} docs · ~${tokenCount} tokens · 状态最差 ${worstStatus(documents)}`
34
+ `${documents.length} docs · ~${tokenCount} tokens · worst status ${worstStatus(documents)}`
35
35
  );
36
36
  const cards = documents.map((node) => {
37
37
  const card = element("button", "topic-doc-card");
@@ -52,7 +52,7 @@ export function createDetailRenderer({ panel, container, onSelectDocument, getSt
52
52
  activeRequest?.abort();
53
53
  activeRequest = new AbortController();
54
54
  const request = activeRequest;
55
- container.replaceChildren(element("div", "placeholder", "正在加载文档…"));
55
+ container.replaceChildren(element("div", "placeholder", "Loading document…"));
56
56
  openPanel();
57
57
 
58
58
  try {
@@ -64,7 +64,7 @@ export function createDetailRenderer({ panel, container, onSelectDocument, getSt
64
64
  } catch (error) {
65
65
  if (error instanceof DOMException && error.name === "AbortError") return;
66
66
  const message = error instanceof Error ? error.message : String(error);
67
- container.replaceChildren(element("div", "placeholder", `加载失败:${message}`));
67
+ container.replaceChildren(element("div", "placeholder", `Load failed: ${message}`));
68
68
  }
69
69
  }
70
70
 
@@ -332,11 +332,11 @@ export function createGraphController(options) {
332
332
 
333
333
  function setGraphChrome(mode) {
334
334
  hint.textContent = mode === "topics"
335
- ? "Topic 拓扑 · 边粗细表示跨域引用数 · 点击下钻"
336
- : "文档全图 · 点击查看详情 · 拖动画布 / 滚轮缩放";
335
+ ? "Topic topology · edge width shows cross-domain references · click to drill down"
336
+ : "Document graph · click for details · drag to pan / scroll to zoom";
337
337
  legend.replaceChildren();
338
338
  const edgeItems = mode === "topics"
339
- ? [["", "跨域引用"]]
339
+ ? [["", "Cross-domain references"]]
340
340
  : [["", "requires"], ["related", "related"], ["link", "link"]];
341
341
  for (const [className, label] of edgeItems) {
342
342
  const item = document.createElement("span");
@@ -12,46 +12,46 @@
12
12
  <body>
13
13
  <header class="app-header">
14
14
  <h1>llmdoc <span class="repo" id="repo"></span></h1>
15
- <div class="health-strip" aria-label="知识面状态">
15
+ <div class="health-strip" aria-label="Knowledge status">
16
16
  <span class="chip" id="stat-docs"></span>
17
17
  <span class="chip" id="stat-baseline"></span>
18
18
  <span class="chip" id="stat-validate"></span>
19
19
  <span class="chip" id="stat-delta"></span>
20
20
  </div>
21
- <button class="chip button" id="refresh" type="button" aria-label="刷新知识面">↻ 刷新</button>
22
- <div class="toggle" role="group" aria-label="图谱显示模式">
23
- <button id="mode-topics" type="button">Topics 拓扑</button>
24
- <button id="mode-docs" type="button">Documents 全图</button>
21
+ <button class="chip button" id="refresh" type="button" aria-label="Refresh knowledge">↻ Refresh</button>
22
+ <div class="toggle" role="group" aria-label="Graph display mode">
23
+ <button id="mode-topics" type="button">Topic topology</button>
24
+ <button id="mode-docs" type="button">All documents</button>
25
25
  </div>
26
26
  </header>
27
27
 
28
28
  <div id="load-error" class="load-error" role="alert" hidden></div>
29
29
 
30
30
  <main>
31
- <nav id="sidebar" aria-label="llmdoc 文档列表">
31
+ <nav id="sidebar" aria-label="llmdoc document list">
32
32
  <label class="search-box">
33
- <span class="sr-only">过滤文档</span>
34
- <input id="search" type="search" placeholder="过滤路径、标题或描述" autocomplete="off" />
33
+ <span class="sr-only">Filter documents</span>
34
+ <input id="search" type="search" placeholder="Filter by path, title, or description" autocomplete="off" />
35
35
  <kbd>/</kbd>
36
36
  </label>
37
37
  <div id="doc-list"></div>
38
38
  </nav>
39
39
 
40
- <section id="graph-wrap" aria-label="知识关系图">
41
- <svg id="graph" role="application" tabindex="0" aria-label="知识关系图;可拖动画布、滚轮缩放,按 0 重置视图"></svg>
40
+ <section id="graph-wrap" aria-label="Knowledge relationship graph">
41
+ <svg id="graph" role="application" tabindex="0" aria-label="Knowledge graph; drag to pan, scroll to zoom, press 0 to reset"></svg>
42
42
  <div id="graph-hint" aria-live="polite"></div>
43
- <div id="graph-toolbar" role="group" aria-label="图谱缩放控制">
44
- <button id="zoom-out" type="button" title="缩小">−</button>
45
- <button id="zoom-reset" type="button" title="重置视图">适应</button>
46
- <button id="zoom-in" type="button" title="放大">+</button>
43
+ <div id="graph-toolbar" role="group" aria-label="Graph zoom controls">
44
+ <button id="zoom-out" type="button" title="Zoom out">−</button>
45
+ <button id="zoom-reset" type="button" title="Reset view">Fit</button>
46
+ <button id="zoom-in" type="button" title="Zoom in">+</button>
47
47
  </div>
48
- <div id="legend" aria-label="图例"></div>
49
- <div id="graph-empty" hidden>没有可显示的文档</div>
48
+ <div id="legend" aria-label="Legend"></div>
49
+ <div id="graph-empty" hidden>No documents to display</div>
50
50
  </section>
51
51
 
52
- <aside id="detail" aria-label="文档详情">
53
- <button id="detail-close" type="button" aria-label="关闭详情">×</button>
54
- <div class="inner"><div class="placeholder">选择一个 topic 或文档查看详情</div></div>
52
+ <aside id="detail" aria-label="Document details">
53
+ <button id="detail-close" type="button" aria-label="Close details">×</button>
54
+ <div class="inner"><div class="placeholder">Select a topic or document to view details</div></div>
55
55
  </aside>
56
56
  </main>
57
57
  </body>
package/dist/cli.js CHANGED
@@ -16,8 +16,12 @@ import { runDelta } from "./commands/delta.js";
16
16
  import { runFingerprint } from "./commands/fingerprint.js";
17
17
  import { runHook } from "./commands/hook.js";
18
18
  import { runPrune } from "./commands/prune.js";
19
+ import { runDream } from "./commands/dream.js";
20
+ import { runEval } from "./commands/eval.js";
19
21
  import { parseAndValidateJsonString, stringifyValidatedOutput } from "./lib/output-schema.js";
20
22
  import { packageRootFromImport } from "./lib/package-root.js";
23
+ import { refreshGitSources } from "./lib/sources.js";
24
+ import { loadWorkspace } from "./lib/workspace.js";
21
25
  export async function runCli(argv, cwd = process.cwd(), stdin = "") {
22
26
  if (argv.includes("--version") || argv.includes("-V")) {
23
27
  return {
@@ -43,38 +47,38 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
43
47
  }
44
48
  program
45
49
  .name("llmdoc")
46
- .description("面向 LLM 的项目知识库 CLI:渐进检索 llmdoc/ 文档,维护 revision 台账")
47
- .version(readPackageVersion(), "--version", "输出 CLI 版本")
48
- .helpOption("-h, --help", "显示帮助")
49
- .helpCommand("help [command]", "显示指定命令的帮助")
50
- .showHelpAfterError("(用 --help 查看用法)");
50
+ .description("Project knowledge CLI for LLMs: progressively retrieve llmdoc/ documents and maintain the revision ledger")
51
+ .version(readPackageVersion(), "--version", "output the CLI version")
52
+ .helpOption("-h, --help", "display help")
53
+ .helpCommand("help [command]", "display help for a command")
54
+ .showHelpAfterError("(use --help to view usage)");
51
55
  program
52
- .option("--json", "以 JSON 输出(经 schema 校验)")
53
- .option("--cursor <cursor>", "上次输出截断处的游标,从该处继续")
54
- .option("--budget <tokens>", "输出 token 预算,超出即截断并返回 cursor", parseInteger)
55
- .option("--limit <n>", "最多返回条数", parseInteger);
56
+ .option("--json", "emit schema-validated JSON")
57
+ .option("--cursor <cursor>", "continue from a cursor returned by a truncated response")
58
+ .option("--budget <tokens>", "truncate output at this token budget and return a cursor", parseInteger)
59
+ .option("--limit <n>", "maximum number of items to return", parseInteger);
56
60
  program.addHelpText("after", [
57
61
  "",
58
- "按用途速查:",
59
- " 检索(只读) tree → index / search / context → show",
60
- " 状态诊断 status · delta · validate",
61
- " 结构改写 new · adopt · mv · fingerprint · init-state · commit",
62
- " 维护诊断 prune · upgrade",
63
- " 集成 hook · serve",
62
+ "Quick reference by purpose:",
63
+ " Retrieval (read-only) tree → index / search / context → show",
64
+ " State diagnostics status · delta · validate · eval",
65
+ " Structural mutation new · adopt · mv · fingerprint · init-state · commit",
66
+ " Maintenance dream · prune · upgrade",
67
+ " Integration hook · serve",
64
68
  "",
65
- "常用示例:",
66
- " llmdoc tree --docs 全局地图,展开到文档级",
67
- " llmdoc search \"重试策略\" --limit 5 词法检索文档",
68
- " llmdoc context --files src/api/retry.ts 按源码反查应读文档",
69
- " llmdoc show api-client/retry-policy.mdx 读取正文",
70
- " llmdoc commit -m \"docs: ...\" 校验并提交 llmdoc 写集",
69
+ "Common examples:",
70
+ " llmdoc tree --docs expand the global map to documents",
71
+ " llmdoc search \"retry policy\" --limit 5 search documents lexically",
72
+ " llmdoc context --files src/api/retry.ts map source files to documents to read",
73
+ " llmdoc show api-client/retry-policy.mdx read selected bodies",
74
+ " llmdoc commit -m \"docs: ...\" validate and commit the llmdoc write set",
71
75
  "",
72
- "所有检索命令支持 --json / --budget / --limit;输出被截断时带 --cursor 继续。"
76
+ "All retrieval commands support --json / --budget / --limit; use --cursor to continue truncated output."
73
77
  ].join("\n"));
74
78
  program
75
79
  .command("tree")
76
- .description("输出 llmdoc 全局地图(默认停在 topic 层)")
77
- .option("--docs", "展开到文档级")
80
+ .description("output the global llmdoc map (topics by default)")
81
+ .option("--docs", "expand to document level")
78
82
  .action((commandOptions) => {
79
83
  const rootDir = findProjectRoot(cwd);
80
84
  const result = runTree({ ...globalOptions, ...commandOptions, cwd: rootDir });
@@ -82,35 +86,35 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
82
86
  });
83
87
  program
84
88
  .command("index")
85
- .description("列出文档元数据索引(不读正文即可判断相关性)")
86
- .option("--topic <topic>", "只列指定 topic 下的文档")
87
- .option("--kind <kind>", "只列指定类型: architecture | guide | reference")
89
+ .description("list document metadata without reading bodies")
90
+ .option("--topic <topic>", "list documents only under a local topic or @source[/subdir]")
91
+ .option("--kind <kind>", "filter by kind: architecture | guide | reference")
88
92
  .action((commandOptions) => {
89
93
  const rootDir = findProjectRoot(cwd);
90
94
  output.push(writeOutput("index", runIndex({ ...globalOptions, ...commandOptions, cwd: rootDir }), globalOptions.json));
91
95
  });
92
96
  program
93
97
  .command("show")
94
- .description("读取一个或多个文档正文")
95
- .argument("<path...>", "llmdoc/ 下的相对路径,如 api-client/retry-policy.mdx")
98
+ .description("read one or more document bodies")
99
+ .argument("<path...>", "local paths under llmdoc/ (e.g. api-client/retry.mdx) or external @source/<path> IDs")
96
100
  .action((paths) => {
97
101
  const rootDir = findProjectRoot(cwd);
98
102
  output.push(writeOutput("show", runShow({ ...globalOptions, cwd: rootDir, paths }), globalOptions.json));
99
103
  });
100
104
  program
101
105
  .command("search")
102
- .description("按词法检索 llmdoc 文档(自动中文分词,必要时使用 CJK bigram 降级)")
103
- .argument("<query>", "检索词")
104
- .option("--topic <topic>", "限定 topic")
105
- .option("--kind <kind>", "限定类型: architecture | guide | reference")
106
+ .description("search llmdoc documents lexically (Chinese segmentation with CJK bigram fallback)")
107
+ .argument("<query>", "search query")
108
+ .option("--topic <topic>", "limit to a local topic or @source[/subdir]")
109
+ .option("--kind <kind>", "filter by kind: architecture | guide | reference")
106
110
  .action((query, commandOptions) => {
107
111
  const rootDir = findProjectRoot(cwd);
108
112
  output.push(writeOutput("search", runSearch({ ...globalOptions, ...commandOptions, cwd: rootDir, query }), globalOptions.json));
109
113
  });
110
114
  program
111
115
  .command("context")
112
- .description("按源码文件反查应读文档(含 requires 前置闭包)")
113
- .requiredOption("--files <files...>", "源码文件路径,可多个")
116
+ .description("map source files to documents to read, including the requires closure")
117
+ .requiredOption("--files <files...>", "one or more source file paths")
114
118
  .action((commandOptions) => {
115
119
  const rootDir = findProjectRoot(cwd);
116
120
  output.push(writeOutput("context", runContext({
@@ -121,7 +125,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
121
125
  });
122
126
  program
123
127
  .command("validate")
124
- .description("校验 llmdoc 结构与引用")
128
+ .description("validate llmdoc structure and references")
125
129
  .action((commandOptions) => {
126
130
  const rootDir = findProjectRoot(cwd);
127
131
  const result = runValidate({ ...globalOptions, ...commandOptions, cwd: rootDir });
@@ -130,24 +134,27 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
130
134
  });
131
135
  program
132
136
  .command("status")
133
- .description("查看 baseline、dirty 与增长状态")
137
+ .description("inspect baseline, dirty, growth, and external source state")
138
+ .option("--refresh", "refresh configured git sources in the foreground")
134
139
  .action((commandOptions) => {
135
140
  const rootDir = findProjectRoot(cwd);
136
- output.push(writeOutput("status", runStatus({ ...globalOptions, ...commandOptions, cwd: rootDir }), globalOptions.json));
141
+ const result = runStatus({ ...globalOptions, ...commandOptions, cwd: rootDir });
142
+ exitCode = result.exitCode;
143
+ output.push(writeOutput("status", result.output, globalOptions.json));
137
144
  });
138
145
  program
139
146
  .command("delta")
140
- .description("查看代码变化对应的文档影响面(决定 update 走 light 还是 deep)")
141
- .option("--scope <scope...>", "限定参与比对的代码路径")
147
+ .description("inspect document impacts from code changes and choose light or deep update mode")
148
+ .option("--scope <scope...>", "limit comparison to selected topics or documents")
142
149
  .action((commandOptions) => {
143
150
  const rootDir = findProjectRoot(cwd);
144
151
  output.push(writeOutput("delta", runDelta({ ...globalOptions, ...commandOptions, cwd: rootDir }), globalOptions.json));
145
152
  });
146
153
  program
147
154
  .command("fingerprint")
148
- .description("把文档 validatedRevision 刷新到当前 HEAD")
149
- .option("--update <path...>", "只刷新指定文档")
150
- .option("--all", "刷新全部文档并推进 baseline")
155
+ .description("refresh document validatedRevision values to the current HEAD")
156
+ .option("--update <path...>", "refresh only selected documents")
157
+ .option("--all", "refresh every document and advance the baseline")
151
158
  .action((commandOptions) => {
152
159
  const rootDir = findProjectRoot(cwd);
153
160
  output.push(writeOutput("fingerprint", runFingerprint({
@@ -159,8 +166,8 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
159
166
  });
160
167
  program
161
168
  .command("init-state")
162
- .description("首次生成 llmdoc/meta.json 台账骨架(validatedRevision 全部为 null)")
163
- .addHelpText("after", "\n前置: Git HEAD 必须已有真实 commit。生成后先 validate,再用 commit --all 完成 bootstrap。")
169
+ .description("create the initial llmdoc/meta.json ledger with null validatedRevision values")
170
+ .addHelpText("after", "\nPrerequisite: Git HEAD must reference a real commit. Then run validate and finish bootstrap with commit --all.")
164
171
  .action(async () => {
165
172
  const { runInitState } = await import("./commands/init-state.js");
166
173
  const rootDir = findProjectRoot(cwd);
@@ -168,11 +175,13 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
168
175
  });
169
176
  program
170
177
  .command("commit")
171
- .description("一体化收尾:validate 门控 → 可选提交正文 → 刷新 changed/verified revision → meta 小 commit")
178
+ .description("finalize atomically: validate, optionally commit prose, refresh revisions, and commit metadata")
172
179
  .option("-m, --message <message>", "docs commit message")
173
- .option("--all", "fingerprint 全部文档并推进 baseline")
174
- .option("--verified <paths...>", "正文复核后无需改写,刷新指定文档的 validatedRevision")
175
- .option("--no-verify", "透传 git commit --no-verify(husky 等重钩子仓库)")
180
+ .option("--all", "fingerprint every document and advance the baseline")
181
+ .option("--verified <paths...>", "refresh validatedRevision for reviewed documents whose bodies did not change")
182
+ .option("--refresh-convergence", "refresh the convergence snapshot in meta.json after validated prune or dream")
183
+ .option("--convergence-source <source>", "convergence refresh source: prune | dream (default: prune)")
184
+ .option("--no-verify", "pass --no-verify through to git commit")
176
185
  .action(async (commandOptions) => {
177
186
  const { runCommit } = await import("./commands/commit.js");
178
187
  const rootDir = findProjectRoot(cwd);
@@ -182,16 +191,18 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
182
191
  message: commandOptions.message,
183
192
  all: commandOptions.all,
184
193
  verified: commandOptions.verified,
194
+ refreshConvergence: Boolean(commandOptions.refreshConvergence),
195
+ convergenceSource: commandOptions.convergenceSource,
185
196
  noVerify: commandOptions.verify === false
186
197
  }), globalOptions.json));
187
198
  });
188
199
  program
189
200
  .command("new")
190
- .description("在 llmdoc/ 下生成文档脚手架")
191
- .argument("<path>", "目标相对路径,如 api-client/retry-policy.mdx")
192
- .requiredOption("--kind <kind>", "文档类型: architecture | guide | reference")
193
- .option("--description <description>", "front matter 一句话描述")
194
- .addHelpText("after", "\n首次创建时会自动建立 llmdoc/;完成初始文档后运行 init-state → validate → commit --all。")
201
+ .description("scaffold a document under llmdoc/")
202
+ .argument("<path>", "target path, such as api-client/retry-policy.mdx")
203
+ .requiredOption("--kind <kind>", "document kind: architecture | guide | reference")
204
+ .option("--description <description>", "one-line front matter description")
205
+ .addHelpText("after", "\nThe first document creates llmdoc/ automatically. Finish bootstrap with init-state → validate → commit --all.")
195
206
  .action((targetPath, commandOptions) => {
196
207
  output.push(writeOutput("new", runNew({
197
208
  ...globalOptions,
@@ -203,8 +214,8 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
203
214
  });
204
215
  program
205
216
  .command("adopt")
206
- .description("无损登记已存在的 .mdx 到 meta.json(validatedRevision: null,不改正文,幂等)")
207
- .argument("<path...>", "已存在的 llmdoc/ 下相对路径,可多个")
217
+ .description("register existing .mdx documents in meta.json without rewriting them")
218
+ .argument("<path...>", "one or more existing paths under llmdoc/")
208
219
  .action(async (paths) => {
209
220
  const { runAdopt } = await import("./commands/adopt.js");
210
221
  const rootDir = findProjectRoot(cwd);
@@ -212,60 +223,121 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
212
223
  });
213
224
  program
214
225
  .command("mv")
215
- .description("移动/重命名文档或整个 topic,并重写内部引用")
216
- .argument("<from>", "源路径")
217
- .argument("<to>", "目标路径")
226
+ .description("move or rename a document or topic and rewrite internal references")
227
+ .argument("<from>", "source path")
228
+ .argument("<to>", "target path")
218
229
  .action((from, to) => {
219
230
  const rootDir = findProjectRoot(cwd);
220
231
  output.push(writeOutput("mv", runMove({ ...globalOptions, cwd: rootDir, from, to }), globalOptions.json));
221
232
  });
222
233
  program
223
234
  .command("prune")
224
- .description("输出只读收敛报告(增长趋势、重复候选、小文档合并候选)")
225
- .option("--report", "输出只读收敛报告")
235
+ .description("output a read-only convergence report")
236
+ .option("--report", "output the read-only report")
226
237
  .action((commandOptions) => {
227
238
  const rootDir = findProjectRoot(cwd);
228
239
  output.push(writeOutput("prune", runPrune({ ...globalOptions, cwd: rootDir, report: commandOptions.report }), globalOptions.json));
229
240
  });
241
+ program
242
+ .command("dream")
243
+ .description("output a read-only offline consolidation report (Harness cron friendly)")
244
+ .option("--report", "output the read-only consolidation report (default)")
245
+ .option("--check", "exit 0 when quiet and exit 2 when actionable consolidation signals exist")
246
+ .option("--quiet", "suppress text output in --check mode when quiet")
247
+ .option("--window-days <days>", "telemetry lookback window in days", parseInteger)
248
+ .option("--stale-days <days>", "days since last verification before hot docs need review", parseInteger)
249
+ .option("--hot-threshold <count>", "minimum reads/preloads within the window to classify as hot", parseInteger)
250
+ .action((commandOptions) => {
251
+ let rootDir;
252
+ try {
253
+ rootDir = findProjectRoot(cwd);
254
+ }
255
+ catch (error) {
256
+ if (error instanceof CliError) {
257
+ // Keep exit code 2 exclusive to actionable --check results so Harness cron distinguishes missing repos from work.
258
+ throw new CliError(error.message, 1);
259
+ }
260
+ throw error;
261
+ }
262
+ const result = runDream({
263
+ ...globalOptions,
264
+ cwd: rootDir,
265
+ report: commandOptions.report,
266
+ check: Boolean(commandOptions.check),
267
+ quiet: Boolean(commandOptions.quiet),
268
+ windowDays: commandOptions.windowDays,
269
+ staleDays: commandOptions.staleDays,
270
+ hotThreshold: commandOptions.hotThreshold
271
+ });
272
+ exitCode = result.exitCode;
273
+ if (typeof result.output !== "string" || result.output.length > 0 || globalOptions.json) {
274
+ output.push(writeOutput("dream", result.output, globalOptions.json));
275
+ }
276
+ });
277
+ program
278
+ .command("eval")
279
+ .description("run deterministic Context Floor routing probes from llmdoc.probes.json")
280
+ .option("--file <path>", "path to a probes JSON file relative to the repository root")
281
+ .action((commandOptions) => {
282
+ const rootDir = findProjectRoot(cwd);
283
+ const result = runEval({
284
+ ...globalOptions,
285
+ cwd: rootDir,
286
+ file: commandOptions.file
287
+ });
288
+ exitCode = result.exitCode;
289
+ output.push(writeOutput("eval", result.output, globalOptions.json));
290
+ });
230
291
  program
231
292
  .command("upgrade")
232
- .description("盘点 legacy/V2 到 V3 的迁移需求")
293
+ .description("inventory legacy/V2 to V3 migration needs")
233
294
  .action(async (commandOptions) => {
234
295
  const { runUpgrade } = await import("./commands/upgrade.js");
235
296
  const rootDir = findProjectRootOrNull(cwd) ?? cwd;
236
297
  output.push(writeOutput("upgrade", await runUpgrade({ ...globalOptions, ...commandOptions, cwd: rootDir }), globalOptions.json));
237
298
  });
238
- const hookCommand = program.command("hook").description("供编辑器/Agent hooks 调用的只读信号(异常时 fail-open)");
299
+ const hookCommand = program.command("hook").description("read-only, fail-open signals for editor and Agent hooks");
239
300
  hookCommand
240
301
  .command("session-start")
241
- .description("输出 SessionStart 短状态信号")
302
+ .description("output SessionStart state and apply optional llmdoc.config.json (reads optional JSON stdin such as {\"source\":\"compact\"})")
242
303
  .action(() => {
243
304
  const rootDir = findProjectRootOrNull(cwd) ?? cwd;
244
305
  output.push(runHook({ cwd: rootDir, mode: "session-start", stdin }));
245
306
  });
246
307
  hookCommand
247
308
  .command("stop")
248
- .description("输出 Stop hook JSON 提醒")
309
+ .description("output the Stop hook JSON reminder")
249
310
  .action(() => {
250
311
  const rootDir = findProjectRootOrNull(cwd) ?? cwd;
251
312
  output.push(parseAndValidateJsonString("hook", runHook({ cwd: rootDir, mode: "stop", stdin })));
252
313
  });
253
314
  hookCommand
254
315
  .command("compact")
255
- .description("输出 PreCompact hook JSON 指令")
316
+ .description("output the PreCompact hook JSON instruction")
256
317
  .action(() => {
257
318
  const rootDir = findProjectRootOrNull(cwd) ?? cwd;
258
319
  output.push(parseAndValidateJsonString("hook", runHook({ cwd: rootDir, mode: "compact", stdin })));
259
320
  });
260
321
  program
261
322
  .command("serve")
262
- .description("启动本地 Web Viewer(HTTP 服务,浏览文档结构与关联,Ctrl-C 退出)")
263
- .option("--port <port>", "监听端口", parseInteger)
323
+ .description("start the local Web Viewer; press Ctrl-C to stop")
324
+ .option("--port <port>", "listening port", parseInteger)
264
325
  .action(async (commandOptions) => {
265
326
  const { runServe } = await import("./commands/serve.js");
266
327
  const rootDir = findProjectRoot(cwd);
267
328
  output.push(await runServe({ cwd: rootDir, port: commandOptions.port }));
268
329
  });
330
+ program
331
+ .command("_refresh-sources", { hidden: true })
332
+ .option("--cwd <dir>", "repository root directory")
333
+ .action((commandOptions) => {
334
+ const rootDir = findProjectRootOrNull(commandOptions.cwd ?? cwd);
335
+ if (!rootDir) {
336
+ return;
337
+ }
338
+ const workspace = loadWorkspace(rootDir);
339
+ refreshGitSources(workspace, { force: false });
340
+ });
269
341
  try {
270
342
  await program.parseAsync(argv, { from: "user" });
271
343
  }
@@ -293,9 +365,13 @@ function writeOutput(schemaName, value, expectJson = false) {
293
365
  return stringifyOutput(value);
294
366
  }
295
367
  function parseInteger(input) {
296
- const value = Number.parseInt(input, 10);
297
- if (Number.isNaN(value) || value <= 0) {
298
- throw new CliError(`非法整数: ${input}`);
368
+ const trimmed = input.trim();
369
+ if (!/^\d+$/.test(trimmed)) {
370
+ throw new CliError(`Invalid integer: ${input}`);
371
+ }
372
+ const value = Number.parseInt(trimmed, 10);
373
+ if (!Number.isSafeInteger(value) || value <= 0) {
374
+ throw new CliError(`Invalid integer: ${input}`);
299
375
  }
300
376
  return value;
301
377
  }
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import { assertDocKindMatchesShape, parseDocTargetShape } from "../lib/doc-shape.js";
3
3
  import { CliError } from "../lib/errors.js";
4
4
  import { findProjectRoot, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
5
+ import { isSourceRef } from "../lib/source-id.js";
5
6
  import { writeMeta } from "../lib/state.js";
6
7
  import { loadWorkspace, validateWorkspace } from "../lib/workspace.js";
7
8
  // 无损登记已存在的合法 .mdx 到 meta.json:只新增 validatedRevision: null 条目,
@@ -10,21 +11,24 @@ export function runAdopt(options) {
10
11
  const rootDir = findProjectRoot(options.cwd);
11
12
  const workspace = loadWorkspace(rootDir);
12
13
  if (!workspace.meta) {
13
- throw new CliError("缺少 llmdoc/meta.json,先运行 llmdoc init-state。");
14
+ throw new CliError("llmdoc/meta.json is missing; run llmdoc init-state first.");
14
15
  }
15
16
  const llmdocPaths = options.paths.map((input) => {
17
+ if (isSourceRef(input)) {
18
+ throw new CliError(`External source documents (@...) are read-only and cannot be adopted: ${input}`);
19
+ }
16
20
  const repoRelativePath = normalizeRepoRelativePath(input.startsWith("llmdoc/") ? input : `llmdoc/${input}`);
17
21
  if (!repoRelativePath.startsWith("llmdoc/") || !repoRelativePath.endsWith(".mdx")) {
18
- throw new CliError(`adopt 只能登记 llmdoc/ 下的 .mdx 文档: ${input}`);
22
+ throw new CliError(`adopt can register only .mdx documents under llmdoc/: ${input}`);
19
23
  }
20
24
  const shape = parseDocTargetShape(repoRelativePath);
21
25
  assertDocKindMatchesShape(shape);
22
26
  const absolutePath = resolveInsideRoot(rootDir, repoRelativePath, { allowMissing: true });
23
27
  if (!fs.existsSync(absolutePath)) {
24
- throw new CliError(`目标不存在,adopt 只登记已有文档(新建请用 llmdoc new): ${repoRelativePath}`);
28
+ throw new CliError(`Target does not exist; adopt registers existing documents only (use llmdoc new to create one): ${repoRelativePath}`);
25
29
  }
26
30
  if (!workspace.documentsByLlmdocPath.has(shape.llmdocPath)) {
27
- throw new CliError(`文档未被 workspace 识别(front matter 可能不合法): ${repoRelativePath}`);
31
+ throw new CliError(`The workspace did not recognize the document (its front matter may be invalid): ${repoRelativePath}`);
28
32
  }
29
33
  return shape.llmdocPath;
30
34
  });
@@ -32,7 +36,7 @@ export function runAdopt(options) {
32
36
  const targetRepoPaths = new Set(llmdocPaths.map((llmdocPath) => `llmdoc/${llmdocPath}`));
33
37
  const blockingIssues = validateWorkspace(workspace).filter((issue) => issue.severity === "error" && issue.path !== undefined && targetRepoPaths.has(issue.path) && issue.code !== "meta.entry.missing");
34
38
  if (blockingIssues.length > 0) {
35
- throw new CliError(`目标文档未通过校验,拒绝登记:\n${blockingIssues.map((issue) => ` ${issue.code} (${issue.path}) ${issue.message}`).join("\n")}`);
39
+ throw new CliError(`Target documents failed validation; refusing to register them:\n${blockingIssues.map((issue) => ` ${issue.code} (${issue.path}) ${issue.message}`).join("\n")}`);
36
40
  }
37
41
  const adopted = [];
38
42
  const alreadyRegistered = [];
@@ -59,7 +63,7 @@ export function runAdopt(options) {
59
63
  lines.push(`already registered (no-op): ${alreadyRegistered.join(", ")}`);
60
64
  }
61
65
  if (adopted.length > 0) {
62
- lines.push("validatedRevision 登记为 null;经 validate 后用 fingerprint/commit 写入有效 revision。");
66
+ lines.push("validatedRevision was registered as null; after validation, use fingerprint/commit to write a valid revision.");
63
67
  }
64
68
  return lines.join("\n");
65
69
  }