@tokenroll/llmdoc 3.5.2 → 3.6.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.
@@ -2,6 +2,9 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { analyzeDelta } from "../lib/state.js";
4
4
  import { loadWorkspace } from "../lib/workspace.js";
5
+ import { formatCompactPreloadIndex, formatStartupPreloadDocuments, loadLlmdocConfig } from "../lib/config.js";
6
+ // Minimal SessionStart guidance; the complete protocol remains in the llmdoc skill.
7
+ const SESSION_START_GUIDANCE = "Operating guidance: Before broad exploration, planning, or documentation work, load the llmdoc skill and retrieve through the CLI instead of crawling the whole repository; align with the user before non-trivial plans or edits; proactively delegate to subagents (investigator for current-state and unfamiliar subsystems, recorder exclusively for stable llmdoc/ writes, reflector for workflow lessons); when a task produces durable knowledge, finish with /llmdoc:update.";
5
8
  export function runHook(options) {
6
9
  try {
7
10
  const hasLlmdoc = fs.existsSync(path.join(options.cwd, "llmdoc"));
@@ -39,30 +42,61 @@ function runSessionStart(cwd, stdin) {
39
42
  // fingerprint/commit 正常收尾会让 HEAD 前进到仅修改 llmdoc/meta.json 的 follow-up commit。
40
43
  // 没有可执行影响时不展示 raw baseline 落后数,避免把知识面自身更新误报成需要再次 update。
41
44
  if (!signal.shouldUpdate) {
42
- parts.push("文档无待处理影响");
45
+ parts.push("documents have no actionable impacts");
43
46
  if (pendingLessonCandidates > 0) {
44
- parts.push(`待处理反思候选 ${pendingLessonCandidates} 个`);
47
+ parts.push(`${pendingLessonCandidates} pending reflection candidate(s)`);
45
48
  }
46
- return parts.join("; ");
47
49
  }
48
- const baseline = workspace.meta?.baseline.revision ? workspace.meta.baseline.revision.slice(0, 7) : "缺失";
49
- const freshness = delta.git.baselineBehindHead === null ? "落后未知" : delta.git.baselineBehindHead === 0 ? "与 HEAD 同步" : `落后 HEAD ${delta.git.baselineBehindHead} commit`;
50
- parts.push(`baseline ${baseline}(${freshness})`);
51
- const summary = [
52
- signal.impactedCount > 0 ? `受影响 ${signal.impactedCount} 篇` : null,
53
- signal.needsReviewCount > 0 ? `待复核 ${signal.needsReviewCount} 篇` : null,
54
- signal.unmappedCount > 0 ? `未映射代码路径 ${signal.unmappedCount} 个` : null
55
- ]
56
- .filter(Boolean)
57
- .join(", ");
58
- parts.push(`${summary} → 建议先看 npx @tokenroll/llmdoc delta`);
59
- if (pendingLessonCandidates > 0) {
60
- parts.push(`待处理反思候选 ${pendingLessonCandidates} 个`);
50
+ else {
51
+ const baseline = workspace.meta?.baseline.revision ? workspace.meta.baseline.revision.slice(0, 7) : "missing";
52
+ const freshness = delta.git.baselineBehindHead === null ? "distance unknown" : delta.git.baselineBehindHead === 0 ? "at HEAD" : `${delta.git.baselineBehindHead} commit(s) behind HEAD`;
53
+ parts.push(`baseline ${baseline}(${freshness})`);
54
+ const summary = [
55
+ signal.impactedCount > 0 ? `${signal.impactedCount} impacted document(s)` : null,
56
+ signal.needsReviewCount > 0 ? `${signal.needsReviewCount} document(s) need review` : null,
57
+ signal.unmappedCount > 0 ? `${signal.unmappedCount} unmapped code path(s)` : null
58
+ ]
59
+ .filter(Boolean)
60
+ .join(", ");
61
+ parts.push(`${summary} → inspect npx @tokenroll/llmdoc delta first`);
62
+ if (pendingLessonCandidates > 0) {
63
+ parts.push(`${pendingLessonCandidates} pending reflection candidate(s)`);
64
+ }
61
65
  }
62
- return parts.join("; ");
66
+ const context = [parts.join("; ")];
67
+ const startupConfig = workspace.llmdocConfig;
68
+ if (startupConfig.config?.startup?.remindSkill ?? true) {
69
+ context.push(SESSION_START_GUIDANCE);
70
+ }
71
+ appendStartupConfigIssues(context, startupConfig);
72
+ const preloaded = source === "compact"
73
+ ? formatCompactPreloadIndex(startupConfig.preloadPaths)
74
+ : formatStartupPreloadDocuments(startupConfig.preloadPaths.map((preloadPath) => workspace.documentsByLlmdocPath.get(preloadPath)));
75
+ if (preloaded) {
76
+ context.push(preloaded);
77
+ }
78
+ return context.join("\n\n");
63
79
  }
64
80
  catch {
65
- return `llmdoc ${lifecycle}; 状态读取失败,检索不受影响`;
81
+ const context = [`llmdoc ${lifecycle}; status read failed, retrieval remains available`];
82
+ const startupConfig = loadLlmdocConfig(cwd);
83
+ if (startupConfig.config?.startup?.remindSkill ?? true) {
84
+ context.push(SESSION_START_GUIDANCE);
85
+ }
86
+ appendStartupConfigIssues(context, startupConfig);
87
+ return context.join("\n\n");
88
+ }
89
+ }
90
+ function appendStartupConfigIssues(context, startupConfig) {
91
+ const errors = startupConfig.issues.filter((issue) => issue.severity === "error");
92
+ const warnings = startupConfig.issues.filter((issue) => issue.severity === "warning");
93
+ if (errors.length > 0) {
94
+ context.push(startupConfig.config
95
+ ? "llmdoc.config.json has invalid startup.preload entries; preload was skipped while the valid remindSkill preference remained applied. Run npx @tokenroll/llmdoc validate for details."
96
+ : "llmdoc.config.json could not be applied; preload was skipped and the default skill reminder remains active. Run npx @tokenroll/llmdoc validate for details.");
97
+ }
98
+ if (warnings.length > 0) {
99
+ context.push("llmdoc.config.json has warnings; normalized duplicate startup.preload entries were ignored. Run npx @tokenroll/llmdoc validate for details.");
66
100
  }
67
101
  }
68
102
  function runStop(cwd) {
@@ -75,23 +109,23 @@ function runStop(cwd) {
75
109
  return { continue: true };
76
110
  }
77
111
  const summary = [
78
- signal.impactedCount > 0 ? `${signal.impactedCount} 篇文档受代码变更影响` : null,
79
- signal.needsReviewCount > 0 ? `${signal.needsReviewCount} 篇文档需要复核` : null,
80
- signal.unmappedCount > 0 ? `${signal.unmappedCount} 个代码路径未映射到任何文档` : null,
81
- pendingLessonCandidates > 0 ? `${pendingLessonCandidates} 个反思候选待处理` : null
112
+ signal.impactedCount > 0 ? `${signal.impactedCount} document(s) impacted by code changes` : null,
113
+ signal.needsReviewCount > 0 ? `${signal.needsReviewCount} document(s) need review` : null,
114
+ signal.unmappedCount > 0 ? `${signal.unmappedCount} code path(s) are not mapped to any document` : null,
115
+ pendingLessonCandidates > 0 ? `${pendingLessonCandidates} reflection candidate(s) pending` : null
82
116
  ]
83
117
  .filter(Boolean)
84
118
  .join(", ");
85
- const reasons = delta.reasons.length > 0 ? `信号: ${delta.reasons.join("; ")}` : "";
119
+ const reasons = delta.reasons.length > 0 ? `Signals: ${delta.reasons.join("; ")}` : "";
86
120
  const updateCommand = pendingLessonCandidates > 0 ? "/llmdoc:update --reflection" : "/llmdoc:update";
87
121
  const guidance = pendingLessonCandidates > 0
88
122
  ? signal.shouldUpdate
89
- ? "workflow 会读取 pending 候选;代码影响面可先用 npx @tokenroll/llmdoc delta 查看"
90
- : "workflow 会读取 pending 候选"
91
- : "先用 npx @tokenroll/llmdoc delta 查看影响面";
123
+ ? "the workflow will read pending candidates; inspect code impact with npx @tokenroll/llmdoc delta first"
124
+ : "the workflow will read pending candidates"
125
+ : "inspect impact with npx @tokenroll/llmdoc delta first";
92
126
  return {
93
127
  continue: true,
94
- systemMessage: `llmdoc: ${summary},建议运行 ${updateCommand}(${guidance})。${reasons}`
128
+ systemMessage: `llmdoc: ${summary}. Consider running ${updateCommand} (${guidance}). ${reasons}`.trim()
95
129
  };
96
130
  }
97
131
  catch (error) {
@@ -115,7 +149,7 @@ function summarizeHookDelta(delta) {
115
149
  function runCompact() {
116
150
  return {
117
151
  continue: true,
118
- systemMessage: "即将 compact:请在 summary 中写入 LLMDOC_STATE(active goal、已读 llmdoc 文档、关键结论与不变量、用户决策、lesson_candidates、next step、open risks)。恢复后若该状态仍充分,直接继续,不要重放 tree/show。"
152
+ systemMessage: "Compaction is imminent. Preserve LLMDOC_STATE in the summary (active goal, llmdoc documents already read, key conclusions and invariants, user decisions, lesson_candidates, next step, open risks). After resuming, continue directly when that state is sufficient; do not replay tree/show."
119
153
  };
120
154
  }
121
155
  function countPendingLessonCandidates(cwd) {
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import { CliError } from "../lib/errors.js";
3
3
  import { findProjectRoot } from "../lib/fs.js";
4
+ import { isUnbornHead } from "../lib/git.js";
4
5
  import { readWorkspaceGitState } from "../lib/state.js";
5
6
  import { loadWorkspace } from "../lib/workspace.js";
6
7
  // init/upgrade 场景的 meta.json 骨架生成:
@@ -10,11 +11,17 @@ export function runInitState(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 已存在;init-state 只用于首次建立台账,不覆盖现有状态。");
14
+ throw new CliError("llmdoc/meta.json already exists; init-state creates only the initial ledger and never overwrites it.");
14
15
  }
15
16
  const git = readWorkspaceGitState(workspace);
16
- if (!git.available || !git.headRevision) {
17
- throw new CliError(git.degradedReason ?? "无法解析 HEAD commit,init-state 需要 git 仓库。");
17
+ if (!git.available) {
18
+ throw new CliError("init-state requires a Git repository. Run `git init` and create a real initial commit first.");
19
+ }
20
+ if (!git.headRevision) {
21
+ if (isUnbornHead(rootDir)) {
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
+ }
24
+ throw new CliError(`${git.degradedReason ?? "Unable to resolve the HEAD commit."} Repair Git HEAD before running init-state.`);
18
25
  }
19
26
  const now = new Date().toISOString().replace(/\.\d+Z$/, "Z");
20
27
  const meta = {
@@ -37,8 +44,8 @@ export function runInitState(options) {
37
44
  status: "success",
38
45
  documents: workspace.documents.length,
39
46
  baselineRevision: git.headRevision,
40
- next: "npx @tokenroll/llmdoc fingerprint --all"
47
+ next: "npx -y @tokenroll/llmdoc validate && npx -y @tokenroll/llmdoc commit --all -m \"docs: bootstrap llmdoc\""
41
48
  };
42
49
  }
43
- return `initialized llmdoc/meta.json: ${workspace.documents.length} documents (validatedRevision: null), baseline ${git.headRevision.slice(0, 7)}\nnext: 验证文档内容后运行 \`npx @tokenroll/llmdoc fingerprint --all\` 烙印 revision`;
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"\`.`;
44
51
  }
@@ -6,40 +6,46 @@ 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";
9
10
  export function runMove(options) {
10
11
  const rootDir = findProjectRoot(options.cwd);
11
12
  const fromRepoPath = normalizeRepoRelativePath(options.from.startsWith("llmdoc/") ? options.from : `llmdoc/${options.from}`);
12
13
  const toRepoPath = normalizeRepoRelativePath(options.to.startsWith("llmdoc/") ? options.to : `llmdoc/${options.to}`);
13
14
  const fromAbsolutePath = resolveInsideRoot(rootDir, fromRepoPath);
14
15
  if (!fromRepoPath.startsWith("llmdoc/") || !toRepoPath.startsWith("llmdoc/")) {
15
- throw new CliError("mv 仅支持 llmdoc/ 内部移动。");
16
+ throw new CliError("mv supports moves only within llmdoc/.");
16
17
  }
17
18
  if (fromRepoPath === "llmdoc/meta.json" || toRepoPath === "llmdoc/meta.json") {
18
- throw new CliError("mv 不允许移动 meta.json。");
19
+ throw new CliError("mv cannot move meta.json.");
19
20
  }
20
21
  const fromStats = fs.statSync(fromAbsolutePath);
21
22
  const beforeWorkspace = loadWorkspace(rootDir);
22
23
  if (fromStats.isDirectory()) {
23
24
  if (!isDirectTopicDirectory(fromRepoPath) || !isDirectTopicDirectory(toRepoPath)) {
24
- throw new CliError("topic 目录重命名仅允许 llmdoc/<topic> -> llmdoc/<topic>。");
25
+ throw new CliError("Topic renames must use llmdoc/<topic> -> llmdoc/<topic>.");
25
26
  }
26
27
  }
27
28
  else {
28
29
  if (!fromRepoPath.endsWith(".mdx") || !toRepoPath.endsWith(".mdx")) {
29
- throw new CliError("mv 仅允许移动 .mdx 文档。");
30
+ throw new CliError("mv can move only .mdx documents.");
30
31
  }
31
32
  const fromDocument = beforeWorkspace.documents.find((document) => document.repoPath === fromRepoPath);
32
33
  if (!fromDocument) {
33
- throw new CliError("mv 仅允许移动已索引的 llmdoc 文档。");
34
+ throw new CliError("mv can move only indexed llmdoc documents.");
34
35
  }
35
36
  const targetShape = parseDocTargetShape(toRepoPath);
36
37
  validateMoveTargetShape(targetShape);
37
38
  }
38
39
  const toAbsolutePath = resolveInsideRoot(rootDir, toRepoPath, { allowMissing: true });
39
40
  if (fs.existsSync(toAbsolutePath)) {
40
- throw new CliError(`目标已存在: ${toRepoPath}`);
41
+ throw new CliError(`Target already exists: ${toRepoPath}`);
41
42
  }
42
43
  const mapping = buildMoveMapping(beforeWorkspace.documents, beforeWorkspace.llmdocDir, fromAbsolutePath, toAbsolutePath);
44
+ const configRewrite = beforeWorkspace.llmdocConfig.config
45
+ ? rewriteStartupPreloadForMove(beforeWorkspace.llmdocConfig.config, mapping)
46
+ : { config: null, changed: false };
47
+ const configPath = path.join(rootDir, LLMDOC_CONFIG_FILENAME);
48
+ const originalConfig = configRewrite.changed ? fs.readFileSync(configPath, "utf8") : null;
43
49
  // 目标 topic 目录不存在时自动创建(topic 即纯目录,没有入口节点前置要求)。
44
50
  fs.mkdirSync(path.dirname(toAbsolutePath), { recursive: true });
45
51
  gitMove(rootDir, fromRepoPath, toRepoPath);
@@ -70,13 +76,16 @@ export function runMove(options) {
70
76
  const nextMeta = rewriteMeta(refreshedWorkspace.meta, mapping);
71
77
  fs.writeFileSync(refreshedWorkspace.metaPath, `${JSON.stringify(nextMeta, null, 2)}\n`);
72
78
  }
79
+ if (configRewrite.changed && configRewrite.config) {
80
+ fs.writeFileSync(configPath, `${JSON.stringify(configRewrite.config, null, 2)}\n`);
81
+ }
73
82
  }
74
83
  catch (error) {
75
- const rolledBack = rollbackMove(rootDir, toAbsolutePath);
84
+ const rolledBack = rollbackMove(rootDir, toAbsolutePath, configPath, originalConfig);
76
85
  const reason = error instanceof Error ? error.message : String(error);
77
86
  throw new CliError(rolledBack
78
- ? `mv 引用重写阶段失败,llmdoc/ 已回滚到移动前状态: ${reason}`
79
- : `mv 引用重写阶段失败,且自动回滚未完成,请检查 git status -- llmdoc/ 后手动恢复: ${reason}`);
87
+ ? `Reference rewriting failed during mv; llmdoc/ was rolled back to its previous state: ${reason}`
88
+ : `Reference rewriting failed during mv and automatic rollback did not complete. Inspect git status -- llmdoc/ llmdoc.config.json and recover manually: ${reason}`);
80
89
  }
81
90
  if (options.json) {
82
91
  return {
@@ -84,10 +93,11 @@ export function runMove(options) {
84
93
  from: fromRepoPath,
85
94
  to: toRepoPath
86
95
  },
96
+ rewrittenConfig: configRewrite.changed,
87
97
  rewrittenDocuments: [...documentTargets].map((absolutePath) => repoPath(rootDir, absolutePath)).sort()
88
98
  };
89
99
  }
90
- return `moved: ${fromRepoPath} -> ${toRepoPath}`;
100
+ return `moved: ${fromRepoPath} -> ${toRepoPath}${configRewrite.changed ? "; updated llmdoc.config.json startup preload" : ""}`;
91
101
  }
92
102
  function buildMoveMapping(documents, llmdocDir, fromAbsolutePath, toAbsolutePath) {
93
103
  const mapping = [];
@@ -101,7 +111,7 @@ function buildMoveMapping(documents, llmdocDir, fromAbsolutePath, toAbsolutePath
101
111
  return relative.replaceAll(path.sep, "/");
102
112
  }
103
113
  }
104
- throw new CliError(`无法从路径推导 llmdoc 相对路径: ${absolutePath}`);
114
+ throw new CliError(`Unable to derive an llmdoc-relative path from: ${absolutePath}`);
105
115
  };
106
116
  const fromPathIsDirectory = fs.statSync(fromAbsolutePath).isDirectory();
107
117
  if (fromPathIsDirectory) {
@@ -125,10 +135,13 @@ function buildMoveMapping(documents, llmdocDir, fromAbsolutePath, toAbsolutePath
125
135
  }
126
136
  return mapping.sort((left, right) => right.oldLlmdocPath.length - left.oldLlmdocPath.length);
127
137
  }
128
- function rollbackMove(rootDir, toAbsolutePath) {
138
+ function rollbackMove(rootDir, toAbsolutePath, configPath, originalConfig) {
129
139
  try {
130
140
  fs.rmSync(toAbsolutePath, { recursive: true, force: true });
131
141
  gitRestorePaths(rootDir, ["llmdoc"]);
142
+ if (originalConfig !== null) {
143
+ fs.writeFileSync(configPath, originalConfig);
144
+ }
132
145
  return true;
133
146
  }
134
147
  catch {
@@ -2,18 +2,18 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parseDocTargetShape, assertDocKindMatchesShape, assertDocumentKind } from "../lib/doc-shape.js";
4
4
  import { CliError } from "../lib/errors.js";
5
- import { ensureDirectory, findProjectRoot, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
5
+ import { ensureDirectory, findProjectRootForNew, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
6
6
  import { packageRootFromImport } from "../lib/package-root.js";
7
7
  import { loadWorkspace } from "../lib/workspace.js";
8
8
  export function runNew(options) {
9
- const rootDir = findProjectRoot(options.cwd);
9
+ const rootDir = findProjectRootForNew(options.cwd);
10
10
  const repoRelativePath = normalizeDocDestination(options.path);
11
11
  const kind = assertDocumentKind(options.kind);
12
12
  const shape = parseDocTargetShape(repoRelativePath);
13
13
  assertDocKindMatchesShape(shape);
14
14
  const absolutePath = resolveInsideRoot(rootDir, repoRelativePath, { allowMissing: true });
15
15
  if (fs.existsSync(absolutePath)) {
16
- throw new CliError(`目标已存在: ${repoRelativePath}`);
16
+ throw new CliError(`Target already exists: ${repoRelativePath}`);
17
17
  }
18
18
  ensureDirectory(absolutePath);
19
19
  const template = readTemplate();
@@ -21,22 +21,28 @@ export function runNew(options) {
21
21
  // description 经 JSON.stringify 得到合法的 YAML double-quoted scalar,防止引号/冒号/换行破坏 front matter;
22
22
  // replace 一律用函数形式,避免 $& 等替换模式展开。
23
23
  const content = template
24
- .replace("__DESCRIPTION__", () => JSON.stringify(options.description ?? "TODO: 补充文档描述。"))
24
+ .replace("__DESCRIPTION__", () => JSON.stringify(options.description ?? "TODO: Add a document description."))
25
25
  .replace("__KIND__", () => kind)
26
26
  .replace("__TITLE__", () => title);
27
+ const metaExists = fs.existsSync(path.join(rootDir, "llmdoc", "meta.json"));
27
28
  fs.writeFileSync(absolutePath, content);
28
29
  syncMetaEntry(rootDir, shape.llmdocPath);
29
30
  if (options.json) {
30
31
  return {
31
- created: repoRelativePath
32
+ created: repoRelativePath,
33
+ next: metaExists
34
+ ? null
35
+ : "If HEAD has no commit, create the initial Git commit, then run `npx -y @tokenroll/llmdoc init-state`."
32
36
  };
33
37
  }
34
- return `created: ${repoRelativePath}`;
38
+ return metaExists
39
+ ? `created: ${repoRelativePath}`
40
+ : `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.`;
35
41
  }
36
42
  function normalizeDocDestination(input) {
37
43
  const repoRelativePath = normalizeRepoRelativePath(input.startsWith("llmdoc/") ? input : `llmdoc/${input}`);
38
44
  if (!repoRelativePath.startsWith("llmdoc/") || !repoRelativePath.endsWith(".mdx")) {
39
- throw new CliError("new 只能创建 llmdoc/ 下的 .mdx 文档。");
45
+ throw new CliError("new can create only .mdx documents under llmdoc/.");
40
46
  }
41
47
  return repoRelativePath;
42
48
  }
@@ -4,18 +4,20 @@ import { loadWorkspace } from "../lib/workspace.js";
4
4
  export function runPrune(options) {
5
5
  if (!options.report) {
6
6
  return options.json
7
- ? { status: "dry_run", message: "prune 当前仅支持 --report。", writable: false }
8
- : "prune 当前仅支持 --report。";
7
+ ? { status: "dry_run", message: "prune currently supports only --report.", writable: false }
8
+ : "prune currently supports only --report.";
9
9
  }
10
10
  const workspace = loadWorkspace(options.cwd);
11
11
  const growth = computeGrowthState(workspace);
12
12
  const duplicateCandidates = findDuplicateCandidates(workspace.documents);
13
13
  const mergeCandidates = findMergeCandidates(workspace.documents);
14
+ const startupPreloads = workspace.llmdocConfig.preloadPaths.map((preloadPath) => `llmdoc/${preloadPath}`);
14
15
  if (options.json) {
15
16
  return {
16
17
  status: "dry_run",
17
18
  writable: false,
18
19
  growth,
20
+ startupPreloads,
19
21
  duplicateCandidates: duplicateCandidates.map((candidate) => ({
20
22
  paths: [`llmdoc/${candidate.left.llmdocPath}`, `llmdoc/${candidate.right.llmdocPath}`],
21
23
  score: candidate.score,
@@ -32,7 +34,15 @@ export function runPrune(options) {
32
34
  const growthLine = growth.baselineDocumentCount === null
33
35
  ? `growth: ${growth.currentDocumentCount} docs, ~${growth.currentTotalEstimatedTokens} tokens (no convergence baseline)`
34
36
  : `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, ""];
37
+ const lines = [growthLine, "", "startup preload references:"];
38
+ if (startupPreloads.length === 0) {
39
+ lines.push(" none");
40
+ }
41
+ else {
42
+ lines.push(...startupPreloads.map((preloadPath) => ` ${preloadPath}`));
43
+ lines.push(" Keep llmdoc.config.json synchronized when merging or deleting these documents.");
44
+ }
45
+ lines.push("");
36
46
  lines.push("duplicate candidates:");
37
47
  if (duplicateCandidates.length === 0) {
38
48
  lines.push(" none");
@@ -7,23 +7,27 @@ import { estimateTokens } from "../lib/markdown.js";
7
7
  export function runSearch(options) {
8
8
  const workspace = loadWorkspace(options.cwd);
9
9
  const kind = options.kind ? assertDocumentKind(options.kind) : undefined;
10
- const results = searchDocuments(workspace, options.query, {
10
+ const search = searchDocuments(workspace, options.query, {
11
11
  topic: options.topic,
12
12
  kind
13
13
  });
14
14
  const paginated = paginate({
15
- items: results,
15
+ items: search.results,
16
16
  estimate: (entry) => estimateTokens(JSON.stringify(toPayload(entry))),
17
17
  options
18
18
  });
19
19
  if (options.json) {
20
20
  return {
21
21
  query: options.query,
22
+ searchMode: search.mode,
22
23
  results: paginated.items.map(toPayload),
23
24
  pagination: paginationMetadata(paginated)
24
25
  };
25
26
  }
26
27
  const lines = [];
28
+ if (search.mode === "cjk-bigram-fallback") {
29
+ lines.push("note: Chinese segmentation returned no matches; CJK bigram fallback was used.", "");
30
+ }
27
31
  for (const entry of paginated.items) {
28
32
  lines.push(`llmdoc/${entry.document.llmdocPath} [${entry.document.frontmatter.kind}]`);
29
33
  lines.push(` ${entry.document.frontmatter.description}`);
@@ -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);
@@ -10,7 +10,7 @@ export function runShow(options) {
10
10
  const normalized = rawPath.startsWith("llmdoc/") ? rawPath.slice("llmdoc/".length) : rawPath;
11
11
  const document = workspace.documentsByLlmdocPath.get(normalized);
12
12
  if (!document) {
13
- throw new CliError(`文档不存在: ${rawPath}`);
13
+ throw new CliError(`Document does not exist: ${rawPath}`);
14
14
  }
15
15
  return document;
16
16
  });
@@ -39,7 +39,7 @@ export function runStatus(options) {
39
39
  if (unmapped.length > 0) {
40
40
  const shown = unmapped.slice(0, 5);
41
41
  const rest = unmapped.length - shown.length;
42
- lines.push(`unmapped changes (${unmapped.length}): ${shown.join(", ")}${rest > 0 ? ` … +${rest} more (--json 查看全部)` : ""}`);
42
+ lines.push(`unmapped changes (${unmapped.length}): ${shown.join(", ")}${rest > 0 ? ` … +${rest} more (use --json for all)` : ""}`);
43
43
  }
44
44
  lines.push(growthLabel);
45
45
  if (delta.git.degradedReason) {
@@ -68,7 +68,7 @@ export function runTree(options) {
68
68
  lines.push(` ${entry.topic.summary}`);
69
69
  }
70
70
  lines.push("", ...formatPaginationSummary(result));
71
- lines.push("hint: `npx @tokenroll/llmdoc tree --docs` 展开文档级;`... index --topic <t>` 看文档元数据");
71
+ lines.push("hint: use `npx @tokenroll/llmdoc tree --docs` to expand documents; use `... index --topic <t>` for metadata");
72
72
  return lines.join("\n");
73
73
  }
74
74
  function toDocumentSummary(document) {
@@ -34,11 +34,11 @@ export async function runUpgrade(options) {
34
34
  function inspectMissingLlmdoc() {
35
35
  return {
36
36
  status: "no_change",
37
- summary: "当前仓库不存在 llmdoc/,没有可升级的 V2/V3 知识面。",
37
+ summary: "The repository has no llmdoc/ directory and no V2/V3 knowledge surface to upgrade.",
38
38
  legacyPaths: [],
39
39
  targetStructure: [],
40
40
  requiresRecorderSemanticMigration: false,
41
- notes: ["如需首次建立知识面,请走 init,而不是 upgrade。"]
41
+ notes: ["Use init, not upgrade, to create the first knowledge surface."]
42
42
  };
43
43
  }
44
44
  function inspectLlmdocDirectory(llmdocDir) {
@@ -60,9 +60,9 @@ function inspectLlmdocDirectory(llmdocDir) {
60
60
  if (errors.length > 0) {
61
61
  return {
62
62
  status: "dry_run",
63
- summary: "检测到部分 V3 结构,但当前知识面未通过 V3 校验。",
63
+ summary: "A partial V3 structure was detected, but the current knowledge surface failed V3 validation.",
64
64
  legacyPaths: [],
65
- targetStructure: ["修复现有 V3 结构错误后再判断是否需要 upgrade"],
65
+ targetStructure: ["Repair the existing V3 structure before deciding whether upgrade is needed"],
66
66
  requiresRecorderSemanticMigration: false,
67
67
  notes: errors.slice(0, 5).map((issue) => `${issue.path ?? "unknown"}: ${issue.message}`)
68
68
  };
@@ -71,41 +71,41 @@ function inspectLlmdocDirectory(llmdocDir) {
71
71
  catch (error) {
72
72
  return {
73
73
  status: "dry_run",
74
- summary: "检测到部分 V3 结构,但当前知识面无法稳定装载。",
74
+ summary: "A partial V3 structure was detected, but the current knowledge surface cannot be loaded reliably.",
75
75
  legacyPaths: [],
76
- targetStructure: ["修复现有 V3 结构错误后再判断是否需要 upgrade"],
76
+ targetStructure: ["Repair the existing V3 structure before deciding whether upgrade is needed"],
77
77
  requiresRecorderSemanticMigration: false,
78
78
  notes: [error.message]
79
79
  };
80
80
  }
81
81
  return {
82
82
  status: "no_change",
83
- summary: "检测到现有知识面已经是 V3 结构,无需 upgrade。",
83
+ summary: "The existing knowledge surface is already V3; no upgrade is needed.",
84
84
  legacyPaths: [],
85
85
  targetStructure: [],
86
86
  requiresRecorderSemanticMigration: false,
87
- notes: ["upgrade 当前只输出盘点,不会改写 V3 知识。"]
87
+ notes: ["upgrade currently reports an inventory only and does not rewrite V3 knowledge."]
88
88
  };
89
89
  }
90
90
  if (legacyPaths.length === 0 && !hasV3Meta && !hasMdx) {
91
91
  return {
92
92
  status: "dry_run",
93
- summary: "检测到 llmdoc/ 目录,但没有明确的 V2 或 V3 结构特征。",
93
+ summary: "An llmdoc/ directory was found, but it has no definitive V2 or V3 structure markers.",
94
94
  legacyPaths: [],
95
- targetStructure: ["llmdoc/meta.json", "llmdoc/architecture.mdx", "llmdoc/<topic>/*.mdx (纯目录,无 index.mdx 入口节点)"],
95
+ targetStructure: ["llmdoc/meta.json", "llmdoc/architecture.mdx", "llmdoc/<topic>/*.mdx (plain directories, no index.mdx entry nodes)"],
96
96
  requiresRecorderSemanticMigration: false,
97
- notes: ["需要人工确认该目录是否为遗留知识面。"]
97
+ notes: ["A human must confirm whether this directory is a legacy knowledge surface."]
98
98
  };
99
99
  }
100
100
  return {
101
101
  status: "dry_run",
102
- summary: "检测到 legacy/V2 结构,需要 Recorder 参与语义迁移到 V3。",
102
+ summary: "A legacy/V2 structure was detected; Recorder must perform the semantic migration to V3.",
103
103
  legacyPaths,
104
- targetStructure: ["llmdoc/meta.json", "llmdoc/architecture.mdx", "llmdoc/<topic>/*.mdx (纯目录,无 index.mdx 入口节点)"],
104
+ targetStructure: ["llmdoc/meta.json", "llmdoc/architecture.mdx", "llmdoc/<topic>/*.mdx (plain directories, no index.mdx entry nodes)"],
105
105
  requiresRecorderSemanticMigration: true,
106
106
  notes: [
107
- hasV3Meta ? "存在部分 V3 迹象,但 legacy 结构仍在,需要整理边界后再迁移。" : "未发现完整 V3 ledger,需要生成新的 meta.json baseline。",
108
- legacyPaths.includes("state/sync.md") ? "state/sync.md 需要迁移为 meta.json baseline.revision。" : "未发现 state/sync.md watermark。"
107
+ hasV3Meta ? "Some V3 markers exist, but legacy structure remains; reconcile the boundary before migration." : "No complete V3 ledger was found; create a new meta.json baseline.",
108
+ legacyPaths.includes("state/sync.md") ? "Migrate state/sync.md to meta.json baseline.revision." : "No state/sync.md watermark was found."
109
109
  ]
110
110
  };
111
111
  }