@tokenroll/llmdoc 3.3.0 → 3.5.1

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.
package/dist/cli.js CHANGED
@@ -58,7 +58,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
58
58
  "按用途速查:",
59
59
  " 检索(只读) tree → index / search / context → show",
60
60
  " 状态诊断 status · delta · validate",
61
- " 结构改写 new · mv · fingerprint · init-state · commit",
61
+ " 结构改写 new · adopt · mv · fingerprint · init-state · commit",
62
62
  " 维护诊断 prune · upgrade",
63
63
  " 集成 hook · serve",
64
64
  "",
@@ -167,9 +167,10 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
167
167
  });
168
168
  program
169
169
  .command("commit")
170
- .description("一体化收尾:validate 门控 → 提交 llmdoc 写集 → fingerprint → meta 小 commit")
170
+ .description("一体化收尾:validate 门控 → 可选提交正文 → 刷新 changed/verified revision → meta 小 commit")
171
171
  .option("-m, --message <message>", "docs commit message")
172
172
  .option("--all", "fingerprint 全部文档并推进 baseline")
173
+ .option("--verified <paths...>", "正文复核后无需改写,刷新指定文档的 validatedRevision")
173
174
  .option("--no-verify", "透传 git commit --no-verify(husky 等重钩子仓库)")
174
175
  .action(async (commandOptions) => {
175
176
  const { runCommit } = await import("./commands/commit.js");
@@ -179,6 +180,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
179
180
  cwd: rootDir,
180
181
  message: commandOptions.message,
181
182
  all: commandOptions.all,
183
+ verified: commandOptions.verified,
182
184
  noVerify: commandOptions.verify === false
183
185
  }), globalOptions.json));
184
186
  });
@@ -198,6 +200,15 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
198
200
  description: commandOptions.description
199
201
  }), globalOptions.json));
200
202
  });
203
+ program
204
+ .command("adopt")
205
+ .description("无损登记已存在的 .mdx 到 meta.json(validatedRevision: null,不改正文,幂等)")
206
+ .argument("<path...>", "已存在的 llmdoc/ 下相对路径,可多个")
207
+ .action(async (paths) => {
208
+ const { runAdopt } = await import("./commands/adopt.js");
209
+ const rootDir = findProjectRoot(cwd);
210
+ output.push(writeOutput("adopt", runAdopt({ ...globalOptions, cwd: rootDir, paths }), globalOptions.json));
211
+ });
201
212
  program
202
213
  .command("mv")
203
214
  .description("移动/重命名文档或整个 topic,并重写内部引用")
@@ -0,0 +1,65 @@
1
+ import fs from "node:fs";
2
+ import { assertDocKindMatchesShape, parseDocTargetShape } from "../lib/doc-shape.js";
3
+ import { CliError } from "../lib/errors.js";
4
+ import { findProjectRoot, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
5
+ import { writeMeta } from "../lib/state.js";
6
+ import { loadWorkspace, validateWorkspace } from "../lib/workspace.js";
7
+ // 无损登记已存在的合法 .mdx 到 meta.json:只新增 validatedRevision: null 条目,
8
+ // 不重写正文;已登记路径幂等 no-op。有效 revision 仍需后续 fingerprint 验证后写入。
9
+ export function runAdopt(options) {
10
+ const rootDir = findProjectRoot(options.cwd);
11
+ const workspace = loadWorkspace(rootDir);
12
+ if (!workspace.meta) {
13
+ throw new CliError("缺少 llmdoc/meta.json,先运行 llmdoc init-state。");
14
+ }
15
+ const llmdocPaths = options.paths.map((input) => {
16
+ const repoRelativePath = normalizeRepoRelativePath(input.startsWith("llmdoc/") ? input : `llmdoc/${input}`);
17
+ if (!repoRelativePath.startsWith("llmdoc/") || !repoRelativePath.endsWith(".mdx")) {
18
+ throw new CliError(`adopt 只能登记 llmdoc/ 下的 .mdx 文档: ${input}`);
19
+ }
20
+ const shape = parseDocTargetShape(repoRelativePath);
21
+ assertDocKindMatchesShape(shape);
22
+ const absolutePath = resolveInsideRoot(rootDir, repoRelativePath, { allowMissing: true });
23
+ if (!fs.existsSync(absolutePath)) {
24
+ throw new CliError(`目标不存在,adopt 只登记已有文档(新建请用 llmdoc new): ${repoRelativePath}`);
25
+ }
26
+ if (!workspace.documentsByLlmdocPath.has(shape.llmdocPath)) {
27
+ throw new CliError(`文档未被 workspace 识别(front matter 可能不合法): ${repoRelativePath}`);
28
+ }
29
+ return shape.llmdocPath;
30
+ });
31
+ // 目标文档自身必须通过结构校验;meta.entry.missing 正是 adopt 要修复的问题,予以豁免。
32
+ const targetRepoPaths = new Set(llmdocPaths.map((llmdocPath) => `llmdoc/${llmdocPath}`));
33
+ const blockingIssues = validateWorkspace(workspace).filter((issue) => issue.severity === "error" && issue.path !== undefined && targetRepoPaths.has(issue.path) && issue.code !== "meta.entry.missing");
34
+ if (blockingIssues.length > 0) {
35
+ throw new CliError(`目标文档未通过校验,拒绝登记:\n${blockingIssues.map((issue) => ` ${issue.code} (${issue.path}) ${issue.message}`).join("\n")}`);
36
+ }
37
+ const adopted = [];
38
+ const alreadyRegistered = [];
39
+ for (const llmdocPath of llmdocPaths) {
40
+ if (workspace.meta.documents[llmdocPath]) {
41
+ alreadyRegistered.push(llmdocPath);
42
+ }
43
+ else {
44
+ workspace.meta.documents[llmdocPath] = { validatedRevision: null };
45
+ adopted.push(llmdocPath);
46
+ }
47
+ }
48
+ if (adopted.length > 0) {
49
+ writeMeta(workspace.metaPath, workspace.meta);
50
+ }
51
+ if (options.json) {
52
+ return {
53
+ adopted: adopted.slice().sort(),
54
+ alreadyRegistered: alreadyRegistered.slice().sort()
55
+ };
56
+ }
57
+ const lines = [`adopted: ${adopted.length} document(s)${adopted.length > 0 ? ` — ${adopted.join(", ")}` : ""}`];
58
+ if (alreadyRegistered.length > 0) {
59
+ lines.push(`already registered (no-op): ${alreadyRegistered.join(", ")}`);
60
+ }
61
+ if (adopted.length > 0) {
62
+ lines.push("validatedRevision 登记为 null;经 validate 后用 fingerprint/commit 写入有效 revision。");
63
+ }
64
+ return lines.join("\n");
65
+ }
@@ -1,19 +1,30 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { CliError } from "../lib/errors.js";
3
3
  import { findProjectRoot } from "../lib/fs.js";
4
- import { updateMetaRevisions, writeMeta } from "../lib/state.js";
4
+ import { assertRevisionAdvancePreconditions, updateMetaRevisions, writeMeta } from "../lib/state.js";
5
5
  import { loadWorkspace, validateWorkspace } from "../lib/workspace.js";
6
6
  // llmdoc 写入的一体化收尾:validate 门控 → commit llmdoc 写集 → fingerprint → meta 单独小 commit。
7
7
  // 消灭手工三步曲及其 amend 追尾陷阱;--no-verify 透传给 git(husky 等重钩子仓库)。
8
8
  export function runCommit(options) {
9
9
  const rootDir = findProjectRoot(options.cwd);
10
- const issues = validateWorkspace(loadWorkspace(rootDir));
10
+ const preflightWorkspace = loadWorkspace(rootDir);
11
+ const verifiedPaths = uniquePaths((options.verified ?? []).map((value) => (value.startsWith("llmdoc/") ? value.slice("llmdoc/".length) : value)));
12
+ if (options.all && verifiedPaths.length > 0) {
13
+ throw new CliError("commit 不能同时使用 --all 与 --verified。");
14
+ }
15
+ for (const docPath of verifiedPaths) {
16
+ if (!preflightWorkspace.documentsByLlmdocPath.has(docPath)) {
17
+ throw new CliError(`文档不存在: ${docPath}`);
18
+ }
19
+ }
20
+ const issues = validateWorkspace(preflightWorkspace);
11
21
  const errors = issues.filter((issue) => issue.severity === "error");
12
22
  if (errors.length > 0) {
13
23
  throw new CliError(`validate 未通过,拒绝提交:\n${errors.map((issue) => ` ${issue.code} (${issue.path})`).join("\n")}`);
14
24
  }
15
25
  const porcelain = runGit(rootDir, ["status", "--porcelain", "--", "llmdoc"]);
16
- if (!porcelain.trim()) {
26
+ const hasLlmdocChanges = Boolean(porcelain.trim());
27
+ if (!hasLlmdocChanges && !options.all && verifiedPaths.length === 0) {
17
28
  return options.json ? { status: "no_change", commits: [], updated: [] } : "no_change: llmdoc/ 无待提交变更";
18
29
  }
19
30
  const changedDocPaths = porcelain
@@ -22,7 +33,34 @@ export function runCommit(options) {
22
33
  .map((line) => line.slice(3).trim())
23
34
  .map((filePath) => (filePath.includes(" -> ") ? filePath.split(" -> ").pop() : filePath))
24
35
  .filter((filePath) => filePath.startsWith("llmdoc/") && filePath.endsWith(".mdx"));
36
+ const existingChangedDocPaths = changedDocPaths
37
+ .map((filePath) => filePath.slice("llmdoc/".length))
38
+ .filter((llmdocPath) => preflightWorkspace.documentsByLlmdocPath.has(llmdocPath));
39
+ const targetPaths = uniquePaths([...existingChangedDocPaths, ...verifiedPaths]);
25
40
  const verifyFlags = options.noVerify ? ["--no-verify"] : [];
41
+ // 在创建任何 commit 前预检 fingerprint 的全部前置条件(git 可推进、关联源码无 dirty):
42
+ // 预检失败时 fail-closed,工作树保持调用前状态,避免留下 docs 已提交但 meta 未刷新的半完成状态。
43
+ try {
44
+ assertRevisionAdvancePreconditions({
45
+ workspace: preflightWorkspace,
46
+ llmdocPaths: targetPaths,
47
+ updateAll: options.all ?? false
48
+ });
49
+ }
50
+ catch (error) {
51
+ throw new CliError(`fingerprint 预检未通过,未创建任何 commit: ${error.message}`, 70);
52
+ }
53
+ if (changedDocPaths.length === 0) {
54
+ return commitMetaOnly({
55
+ rootDir,
56
+ workspace: preflightWorkspace,
57
+ verifiedPaths,
58
+ updateAll: options.all ?? false,
59
+ hasLlmdocChanges,
60
+ verifyFlags,
61
+ json: options.json ?? false
62
+ });
63
+ }
26
64
  runGit(rootDir, ["add", "--", "llmdoc"]);
27
65
  runGit(rootDir, ["commit", ...verifyFlags, "-m", options.message ?? "docs(llmdoc): update knowledge", "--", "llmdoc"]);
28
66
  const docsCommit = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
@@ -33,7 +71,7 @@ export function runCommit(options) {
33
71
  .filter((llmdocPath) => workspace.documentsByLlmdocPath.has(llmdocPath));
34
72
  const { meta, updatedPaths } = updateMetaRevisions({
35
73
  workspace,
36
- llmdocPaths: existingDocPaths,
74
+ llmdocPaths: uniquePaths([...existingDocPaths, ...verifiedPaths]),
37
75
  updateAll: options.all ?? false
38
76
  });
39
77
  writeMeta(workspace.metaPath, meta);
@@ -53,6 +91,62 @@ export function runCommit(options) {
53
91
  `fingerprints: ${updatedPaths.length} document(s)${options.all ? ", baseline advanced" : ""}`
54
92
  ].join("\n");
55
93
  }
94
+ function commitMetaOnly(input) {
95
+ const { rootDir, workspace, verifiedPaths, updateAll, hasLlmdocChanges, verifyFlags, json } = input;
96
+ const headRevision = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
97
+ const requestedPaths = updateAll ? workspace.documents.map((document) => document.llmdocPath) : verifiedPaths;
98
+ const refreshNeeded = updateAll
99
+ ? !revisionIsCurrent(rootDir, workspace.meta.baseline.revision, headRevision) ||
100
+ requestedPaths.some((docPath) => !revisionIsCurrent(rootDir, workspace.meta.documents[docPath]?.validatedRevision ?? null, headRevision))
101
+ : requestedPaths.some((docPath) => !revisionIsCurrent(rootDir, workspace.meta.documents[docPath]?.validatedRevision ?? null, headRevision));
102
+ if (!hasLlmdocChanges && !refreshNeeded) {
103
+ return json
104
+ ? { status: "no_change", commits: [], updated: [] }
105
+ : "no_change: requested fingerprints are already current";
106
+ }
107
+ let updatedPaths = [];
108
+ if (refreshNeeded) {
109
+ const result = updateMetaRevisions({
110
+ workspace,
111
+ llmdocPaths: verifiedPaths,
112
+ updateAll
113
+ });
114
+ writeMeta(workspace.metaPath, result.meta);
115
+ updatedPaths = result.updatedPaths;
116
+ }
117
+ runGit(rootDir, ["add", "--", "llmdoc/meta.json"]);
118
+ runGit(rootDir, ["commit", ...verifyFlags, "-m", "chore(llmdoc): refresh fingerprints", "--", "llmdoc/meta.json"]);
119
+ const metaCommit = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
120
+ if (json) {
121
+ return {
122
+ status: "success",
123
+ commits: [metaCommit],
124
+ updated: updatedPaths,
125
+ baselineAdvanced: updateAll
126
+ };
127
+ }
128
+ return [
129
+ `committed: ${metaCommit.slice(0, 7)} (meta)`,
130
+ `fingerprints: ${updatedPaths.length} document(s)${updateAll ? ", baseline advanced" : ""}`
131
+ ].join("\n");
132
+ }
133
+ // commit 自身会在 fingerprint 锚点之后创建一个只修改 meta.json 的 follow-up commit。
134
+ // 这种差异不代表知识又过期了,否则重复 commit 会无限追逐自己创建的 meta commit。
135
+ function revisionIsCurrent(rootDir, revision, headRevision) {
136
+ if (!revision) {
137
+ return false;
138
+ }
139
+ if (revision === headRevision) {
140
+ return true;
141
+ }
142
+ const changedPaths = runGit(rootDir, ["diff", "--name-only", `${revision}..${headRevision}`, "--"])
143
+ .split(/\r?\n/)
144
+ .filter(Boolean);
145
+ return changedPaths.every((filePath) => filePath === "llmdoc/meta.json");
146
+ }
147
+ function uniquePaths(paths) {
148
+ return [...new Set(paths)].sort();
149
+ }
56
150
  function runGit(rootDir, args) {
57
151
  const result = spawnSync("git", ["-c", "core.quotePath=false", ...args], { cwd: rootDir, encoding: "utf8" });
58
152
  if (result.status !== 0) {
@@ -33,14 +33,31 @@ function runSessionStart(cwd, stdin) {
33
33
  try {
34
34
  const workspace = loadWorkspace(cwd);
35
35
  const delta = analyzeDelta(workspace);
36
- const baseline = workspace.meta?.baseline.revision ? workspace.meta.baseline.revision.slice(0, 7) : "缺失";
37
- const freshness = delta.git.baselineBehindHead === null ? "落后未知" : delta.git.baselineBehindHead === 0 ? "与 HEAD 同步" : `落后 HEAD ${delta.git.baselineBehindHead} commit`;
38
- const parts = [`llmdoc ${lifecycle}`, `baseline ${baseline}(${freshness})`];
39
- if (delta.impacts.length === 0 && delta.needsReview.length === 0) {
36
+ const signal = summarizeHookDelta(delta);
37
+ const pendingLessonCandidates = countPendingLessonCandidates(cwd);
38
+ const parts = [`llmdoc ${lifecycle}`];
39
+ // fingerprint/commit 正常收尾会让 HEAD 前进到仅修改 llmdoc/meta.json 的 follow-up commit。
40
+ // 没有可执行影响时不展示 raw baseline 落后数,避免把知识面自身更新误报成需要再次 update。
41
+ if (!signal.shouldUpdate) {
40
42
  parts.push("文档无待处理影响");
43
+ if (pendingLessonCandidates > 0) {
44
+ parts.push(`待处理反思候选 ${pendingLessonCandidates} 个`);
45
+ }
46
+ return parts.join("; ");
41
47
  }
42
- else {
43
- parts.push(`受影响 ${delta.impacts.length} 篇, 待复核 ${delta.needsReview.length} 篇 → 建议先看 npx @tokenroll/llmdoc delta`);
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} 个`);
44
61
  }
45
62
  return parts.join("; ");
46
63
  }
@@ -52,21 +69,29 @@ function runStop(cwd) {
52
69
  try {
53
70
  const workspace = loadWorkspace(cwd);
54
71
  const delta = analyzeDelta(workspace);
55
- const unmappedCount = delta.unmappedCommittedPaths.length + delta.unmappedDirtyPaths.length;
56
- const shouldUpdate = delta.impacts.length > 0 || unmappedCount > 0;
57
- if (!shouldUpdate) {
72
+ const signal = summarizeHookDelta(delta);
73
+ const pendingLessonCandidates = countPendingLessonCandidates(cwd);
74
+ if (!signal.shouldUpdate && pendingLessonCandidates === 0) {
58
75
  return { continue: true };
59
76
  }
60
77
  const summary = [
61
- delta.impacts.length > 0 ? `${delta.impacts.length} 篇文档受代码变更影响` : null,
62
- unmappedCount > 0 ? `${unmappedCount} 个代码路径未映射到任何文档` : null
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
63
82
  ]
64
83
  .filter(Boolean)
65
84
  .join(", ");
66
85
  const reasons = delta.reasons.length > 0 ? `信号: ${delta.reasons.join("; ")}` : "";
86
+ const updateCommand = pendingLessonCandidates > 0 ? "/llmdoc:update --reflection" : "/llmdoc:update";
87
+ const guidance = pendingLessonCandidates > 0
88
+ ? signal.shouldUpdate
89
+ ? "workflow 会读取 pending 候选;代码影响面可先用 npx @tokenroll/llmdoc delta 查看"
90
+ : "workflow 会读取 pending 候选"
91
+ : "先用 npx @tokenroll/llmdoc delta 查看影响面";
67
92
  return {
68
93
  continue: true,
69
- systemMessage: `llmdoc: ${summary},建议运行 /llmdoc:update(先用 npx @tokenroll/llmdoc delta 查看影响面)。${reasons}`
94
+ systemMessage: `llmdoc: ${summary},建议运行 ${updateCommand}(${guidance})。${reasons}`
70
95
  };
71
96
  }
72
97
  catch (error) {
@@ -76,12 +101,38 @@ function runStop(cwd) {
76
101
  };
77
102
  }
78
103
  }
104
+ function summarizeHookDelta(delta) {
105
+ const impactedCount = delta.impacts.length;
106
+ const needsReviewCount = delta.needsReview.length;
107
+ const unmappedCount = delta.unmappedCommittedPaths.length + delta.unmappedDirtyPaths.length;
108
+ return {
109
+ shouldUpdate: impactedCount > 0 || needsReviewCount > 0 || unmappedCount > 0,
110
+ impactedCount,
111
+ needsReviewCount,
112
+ unmappedCount
113
+ };
114
+ }
79
115
  function runCompact() {
80
116
  return {
81
117
  continue: true,
82
- systemMessage: "即将 compact:请在 summary 中写入 LLMDOC_STATE(active goal、已读 llmdoc 文档、关键结论与不变量、用户决策、next step、open risks)。恢复后若该状态仍充分,直接继续,不要重放 tree/show。"
118
+ systemMessage: "即将 compact:请在 summary 中写入 LLMDOC_STATE(active goal、已读 llmdoc 文档、关键结论与不变量、用户决策、lesson_candidates、next step、open risks)。恢复后若该状态仍充分,直接继续,不要重放 tree/show。"
83
119
  };
84
120
  }
121
+ function countPendingLessonCandidates(cwd) {
122
+ const pendingDir = path.join(cwd, ".llmdoc-tmp", "reflections", "pending");
123
+ try {
124
+ return fs
125
+ .readdirSync(pendingDir, { withFileTypes: true })
126
+ .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md")).length;
127
+ }
128
+ catch (error) {
129
+ const code = error.code;
130
+ if (code === "ENOENT" || code === "ENOTDIR") {
131
+ return 0;
132
+ }
133
+ throw error;
134
+ }
135
+ }
85
136
  function inferSource(stdin) {
86
137
  const text = stdin.trim();
87
138
  if (!text) {
@@ -1,14 +1,17 @@
1
- import { computeGrowthState, analyzeDelta } from "../lib/state.js";
1
+ import { readCommitsWithChangedPathsSince } from "../lib/git.js";
2
+ import { computeGrowthState, analyzeDelta, isImplementationSurfacePath, loadIgnorePatterns } from "../lib/state.js";
2
3
  import { loadWorkspace } from "../lib/workspace.js";
3
4
  export function runStatus(options) {
4
5
  const workspace = loadWorkspace(options.cwd);
5
6
  const delta = analyzeDelta(workspace);
6
7
  const growth = computeGrowthState(workspace);
8
+ const relevantCommitsBehindHead = countRelevantCommitsBehindHead(workspace.rootDir, workspace.meta?.baseline.revision ?? null, delta);
7
9
  if (options.json) {
8
10
  return {
9
11
  baseline: workspace.meta?.baseline.revision ?? null,
10
12
  head: delta.git.headRevision,
11
13
  commitsBehindHead: delta.git.baselineBehindHead,
14
+ relevantCommitsBehindHead,
12
15
  degradedReason: delta.git.degradedReason,
13
16
  documents: {
14
17
  total: workspace.documents.length,
@@ -24,7 +27,7 @@ export function runStatus(options) {
24
27
  };
25
28
  }
26
29
  const baseline = workspace.meta?.baseline.revision ?? "missing";
27
- const behind = delta.git.baselineBehindHead === null ? "unknown" : `${delta.git.baselineBehindHead} commits behind HEAD`;
30
+ const behind = formatBehindLabel(delta.git.baselineBehindHead, relevantCommitsBehindHead);
28
31
  const unmapped = [...delta.unmappedCommittedPaths, ...delta.unmappedDirtyPaths];
29
32
  const growthLabel = growth.baselineDocumentCount === null
30
33
  ? `growth: ${growth.currentDocumentCount} docs, ~${growth.currentTotalEstimatedTokens} tokens (no convergence baseline)`
@@ -44,3 +47,31 @@ export function runStatus(options) {
44
47
  }
45
48
  return lines.join("\n");
46
49
  }
50
+ // "有效源码落后"计数:baseline..HEAD 中至少触碰一个 implementation surface 路径的提交数。
51
+ // 只改 llmdoc/** 的提交(尤其 commit 收尾的 meta follow-up)不代表知识过期,不应计入。
52
+ function countRelevantCommitsBehindHead(rootDir, baselineRevision, delta) {
53
+ if (!baselineRevision || !delta.git.headRevision || delta.git.baselineBehindHead === null) {
54
+ return null;
55
+ }
56
+ if (delta.git.baselineBehindHead === 0) {
57
+ return 0;
58
+ }
59
+ const commits = readCommitsWithChangedPathsSince(rootDir, baselineRevision, delta.git.headRevision);
60
+ if (commits === null) {
61
+ return null;
62
+ }
63
+ const ignorePatterns = loadIgnorePatterns(rootDir);
64
+ return commits.filter((commit) => commit.paths.some((filePath) => isImplementationSurfacePath(filePath, ignorePatterns))).length;
65
+ }
66
+ function formatBehindLabel(commitsBehindHead, relevantCommitsBehindHead) {
67
+ if (commitsBehindHead === null) {
68
+ return "unknown";
69
+ }
70
+ if (commitsBehindHead > 0 && relevantCommitsBehindHead === 0) {
71
+ return `${commitsBehindHead} commits behind HEAD, metadata-only; knowledge clean`;
72
+ }
73
+ if (commitsBehindHead > 0 && relevantCommitsBehindHead !== null) {
74
+ return `${commitsBehindHead} commits behind HEAD, ${relevantCommitsBehindHead} relevant source commits`;
75
+ }
76
+ return `${commitsBehindHead} commits behind HEAD`;
77
+ }
package/dist/lib/git.js CHANGED
@@ -83,6 +83,31 @@ export function readChangedPathsSince(rootDir, revision, headRevision) {
83
83
  }
84
84
  return readPathList(rootDir, ["diff", "--name-only", "--no-renames", `${revision}..${headRevision}`]);
85
85
  }
86
+ // 逐 commit 列出 baseline..HEAD 中每个提交触碰的路径,供"有效源码落后"计数:
87
+ // \x01 前缀作 commit 分隔哨兵,避免 40 位 hex 路径名的歧义;merge commit 默认不列文件,视为无自身变更。
88
+ export function readCommitsWithChangedPathsSince(rootDir, revision, headRevision) {
89
+ if (!gitCommitExists(rootDir, revision)) {
90
+ return null;
91
+ }
92
+ const output = runGitSafe(rootDir, ["log", "--format=%x01%H", "--name-only", "--no-renames", `${revision}..${headRevision}`]);
93
+ if (output === null) {
94
+ return null;
95
+ }
96
+ const commits = [];
97
+ for (const line of output.split(/\r?\n/)) {
98
+ const trimmed = line.trim();
99
+ if (!trimmed) {
100
+ continue;
101
+ }
102
+ if (trimmed.startsWith("\u0001")) {
103
+ commits.push({ revision: trimmed.slice(1), paths: [] });
104
+ }
105
+ else if (commits.length > 0) {
106
+ commits[commits.length - 1].paths.push(trimmed);
107
+ }
108
+ }
109
+ return commits;
110
+ }
86
111
  export function canAdvanceRevisions(gitState) {
87
112
  if (!gitState.available || !gitState.headRevision) {
88
113
  return { ok: false, reason: gitState.degradedReason ?? "git 状态不可用。" };
package/dist/lib/state.js CHANGED
@@ -148,7 +148,9 @@ export function computeGrowthState(workspace) {
148
148
  exceedsGate
149
149
  };
150
150
  }
151
- export function updateMetaRevisions(input) {
151
+ // fingerprint 推进的全部前置条件(git 可推进 + 关联源码无 dirty),
152
+ // 供 updateMetaRevisions 执行前使用,也供 commit 在创建任何 commit 前 preflight,失败时 fail-closed。
153
+ export function assertRevisionAdvancePreconditions(input) {
152
154
  const { workspace, llmdocPaths, updateAll } = input;
153
155
  if (!workspace.meta) {
154
156
  throw new Error("缺少 meta.json");
@@ -172,6 +174,11 @@ export function updateMetaRevisions(input) {
172
174
  ? `全量 fingerprint 时以下文档关联代码存在 dirty 变更,不能伪造 revision: ${blocked.join(", ")}`
173
175
  : `以下文档关联代码存在 dirty 变更,不能伪造 revision: ${blocked.join(", ")}`);
174
176
  }
177
+ return { git, targetPaths };
178
+ }
179
+ export function updateMetaRevisions(input) {
180
+ const { workspace, updateAll } = input;
181
+ const { git, targetPaths } = assertRevisionAdvancePreconditions(input);
175
182
  const nextMeta = structuredClone(workspace.meta);
176
183
  // 文档已被删除的孤儿 ledger 条目在此顺带清理:
177
184
  // recorder 不允许手编辑 meta.json,删除文档后的 ledger 收敛只能由 CLI 完成。
@@ -249,7 +256,7 @@ export function loadIgnorePatterns(rootDir) {
249
256
  ignorePatternsCache.set(rootDir, patterns);
250
257
  return patterns;
251
258
  }
252
- function isImplementationSurfacePath(repoRelativePath, ignorePatterns = []) {
259
+ export function isImplementationSurfacePath(repoRelativePath, ignorePatterns = []) {
253
260
  if (repoRelativePath.startsWith("llmdoc/") || repoRelativePath.startsWith(".llmdoc-tmp/")) {
254
261
  return false;
255
262
  }
@@ -339,7 +339,7 @@ export function validateWorkspace(workspace) {
339
339
  severity: "error",
340
340
  code: "meta.entry.missing",
341
341
  path: `llmdoc/${docPath}`,
342
- message: "meta.json 缺少对应 documents entry。"
342
+ message: "meta.json 缺少对应 documents entry。可用 `llmdoc adopt <path>` 无损登记。"
343
343
  });
344
344
  }
345
345
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenroll/llmdoc",
3
- "version": "3.3.0",
3
+ "version": "3.5.1",
4
4
  "description": "V3 runtime CLI for llmdoc repositories",
5
5
  "homepage": "https://github.com/TokenRollAI/llmdoc",
6
6
  "repository": {
@@ -478,6 +478,7 @@
478
478
  "baseline",
479
479
  "head",
480
480
  "commitsBehindHead",
481
+ "relevantCommitsBehindHead",
481
482
  "degradedReason",
482
483
  "documents",
483
484
  "unmapped",
@@ -503,6 +504,13 @@
503
504
  ],
504
505
  "minimum": 0
505
506
  },
507
+ "relevantCommitsBehindHead": {
508
+ "type": [
509
+ "integer",
510
+ "null"
511
+ ],
512
+ "minimum": 0
513
+ },
506
514
  "degradedReason": {
507
515
  "type": [
508
516
  "string",
@@ -852,6 +860,30 @@
852
860
  }
853
861
  }
854
862
  },
863
+ "adopt": {
864
+ "type": "object",
865
+ "additionalProperties": false,
866
+ "required": [
867
+ "adopted",
868
+ "alreadyRegistered"
869
+ ],
870
+ "properties": {
871
+ "adopted": {
872
+ "type": "array",
873
+ "items": {
874
+ "type": "string",
875
+ "minLength": 1
876
+ }
877
+ },
878
+ "alreadyRegistered": {
879
+ "type": "array",
880
+ "items": {
881
+ "type": "string",
882
+ "minLength": 1
883
+ }
884
+ }
885
+ }
886
+ },
855
887
  "mv": {
856
888
  "type": "object",
857
889
  "additionalProperties": false,