@tokenroll/llmdoc 3.6.0 → 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.
- package/dist/cli.js +86 -10
- package/dist/commands/adopt.js +4 -0
- package/dist/commands/commit.js +224 -72
- package/dist/commands/context.js +84 -44
- package/dist/commands/dream.js +608 -0
- package/dist/commands/eval.js +379 -0
- package/dist/commands/fingerprint.js +6 -0
- package/dist/commands/hook.js +79 -6
- package/dist/commands/index.js +52 -7
- package/dist/commands/mv.js +8 -0
- package/dist/commands/new.js +7 -0
- package/dist/commands/prune.js +2 -1
- package/dist/commands/search.js +66 -3
- package/dist/commands/show.js +40 -6
- package/dist/commands/status.js +45 -17
- package/dist/commands/tree.js +94 -6
- package/dist/lib/config.js +403 -46
- package/dist/lib/constants.js +23 -0
- package/dist/lib/frontmatter.js +47 -0
- package/dist/lib/git.js +141 -36
- package/dist/lib/markdown.js +3 -2
- package/dist/lib/rewrite.js +9 -3
- package/dist/lib/routing.js +152 -0
- package/dist/lib/schema.js +8 -0
- package/dist/lib/search.js +35 -16
- package/dist/lib/source-id.js +49 -0
- package/dist/lib/sources.js +760 -0
- package/dist/lib/state.js +60 -12
- package/dist/lib/telemetry.js +726 -0
- package/dist/lib/workspace.js +157 -17
- package/package.json +1 -1
- package/schemas/config.schema.json +92 -10
- package/schemas/meta.schema.json +5 -1
- package/schemas/output.schema.json +430 -0
- package/schemas/probes.schema.json +90 -0
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 {
|
|
@@ -57,9 +61,9 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
57
61
|
"",
|
|
58
62
|
"Quick reference by purpose:",
|
|
59
63
|
" Retrieval (read-only) tree → index / search / context → show",
|
|
60
|
-
" State diagnostics status · delta · validate",
|
|
64
|
+
" State diagnostics status · delta · validate · eval",
|
|
61
65
|
" Structural mutation new · adopt · mv · fingerprint · init-state · commit",
|
|
62
|
-
" Maintenance prune · upgrade",
|
|
66
|
+
" Maintenance dream · prune · upgrade",
|
|
63
67
|
" Integration hook · serve",
|
|
64
68
|
"",
|
|
65
69
|
"Common examples:",
|
|
@@ -83,7 +87,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
83
87
|
program
|
|
84
88
|
.command("index")
|
|
85
89
|
.description("list document metadata without reading bodies")
|
|
86
|
-
.option("--topic <topic>", "list documents only under
|
|
90
|
+
.option("--topic <topic>", "list documents only under a local topic or @source[/subdir]")
|
|
87
91
|
.option("--kind <kind>", "filter by kind: architecture | guide | reference")
|
|
88
92
|
.action((commandOptions) => {
|
|
89
93
|
const rootDir = findProjectRoot(cwd);
|
|
@@ -92,7 +96,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
92
96
|
program
|
|
93
97
|
.command("show")
|
|
94
98
|
.description("read one or more document bodies")
|
|
95
|
-
.argument("<path...>", "paths
|
|
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));
|
|
@@ -101,7 +105,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
101
105
|
.command("search")
|
|
102
106
|
.description("search llmdoc documents lexically (Chinese segmentation with CJK bigram fallback)")
|
|
103
107
|
.argument("<query>", "search query")
|
|
104
|
-
.option("--topic <topic>", "limit to a topic")
|
|
108
|
+
.option("--topic <topic>", "limit to a local topic or @source[/subdir]")
|
|
105
109
|
.option("--kind <kind>", "filter by kind: architecture | guide | reference")
|
|
106
110
|
.action((query, commandOptions) => {
|
|
107
111
|
const rootDir = findProjectRoot(cwd);
|
|
@@ -130,10 +134,13 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
130
134
|
});
|
|
131
135
|
program
|
|
132
136
|
.command("status")
|
|
133
|
-
.description("inspect baseline, dirty, and
|
|
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
|
-
|
|
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")
|
|
@@ -172,6 +179,8 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
172
179
|
.option("-m, --message <message>", "docs commit message")
|
|
173
180
|
.option("--all", "fingerprint every document and advance the baseline")
|
|
174
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)")
|
|
175
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");
|
|
@@ -182,6 +191,8 @@ 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
|
});
|
|
@@ -227,6 +238,56 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
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
293
|
.description("inventory legacy/V2 to V3 migration needs")
|
|
@@ -238,7 +299,7 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
238
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("output SessionStart state and apply optional llmdoc.config.json
|
|
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 }));
|
|
@@ -266,6 +327,17 @@ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
|
|
|
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,8 +365,12 @@ function writeOutput(schemaName, value, expectJson = false) {
|
|
|
293
365
|
return stringifyOutput(value);
|
|
294
366
|
}
|
|
295
367
|
function parseInteger(input) {
|
|
296
|
-
const
|
|
297
|
-
if (
|
|
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) {
|
|
298
374
|
throw new CliError(`Invalid integer: ${input}`);
|
|
299
375
|
}
|
|
300
376
|
return value;
|
package/dist/commands/adopt.js
CHANGED
|
@@ -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 条目,
|
|
@@ -13,6 +14,9 @@ export function runAdopt(options) {
|
|
|
13
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
22
|
throw new CliError(`adopt can register only .mdx documents under llmdoc/: ${input}`);
|
package/dist/commands/commit.js
CHANGED
|
@@ -1,38 +1,70 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
1
2
|
import { spawnSync } from "node:child_process";
|
|
2
3
|
import { CliError } from "../lib/errors.js";
|
|
3
4
|
import { findProjectRoot } from "../lib/fs.js";
|
|
4
|
-
import {
|
|
5
|
+
import { parseGitPorcelainZ, readCommitTimestampMs, resolveCommitObjectId } from "../lib/git.js";
|
|
6
|
+
import { isSourceRef } from "../lib/source-id.js";
|
|
7
|
+
import { assertRevisionAdvancePreconditions, readWorkspaceGitState, updateMetaRevisions, writeFileAtomically, writeMeta } from "../lib/state.js";
|
|
5
8
|
import { loadWorkspace, validateWorkspace } from "../lib/workspace.js";
|
|
9
|
+
const VERIFIED_AT_IDEMPOTENCY_MS = 60 * 60 * 1000;
|
|
6
10
|
// llmdoc 写入的一体化收尾:validate 门控 → commit llmdoc 写集 → fingerprint → meta 单独小 commit。
|
|
7
11
|
// 消灭手工三步曲及其 amend 追尾陷阱;--no-verify 透传给 git(husky 等重钩子仓库)。
|
|
8
12
|
export function runCommit(options) {
|
|
9
13
|
const rootDir = findProjectRoot(options.cwd);
|
|
10
14
|
const preflightWorkspace = loadWorkspace(rootDir);
|
|
15
|
+
for (const value of options.verified ?? []) {
|
|
16
|
+
if (isSourceRef(value)) {
|
|
17
|
+
throw new CliError(`External source documents (@...) are read-only and cannot be passed to commit --verified: ${value}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
11
20
|
const verifiedPaths = uniquePaths((options.verified ?? []).map((value) => (value.startsWith("llmdoc/") ? value.slice("llmdoc/".length) : value)));
|
|
12
21
|
if (options.all && verifiedPaths.length > 0) {
|
|
13
22
|
throw new CliError("commit cannot use --all and --verified together.");
|
|
14
23
|
}
|
|
24
|
+
if (options.convergenceSource && !options.refreshConvergence) {
|
|
25
|
+
throw new CliError("--convergence-source requires --refresh-convergence.");
|
|
26
|
+
}
|
|
27
|
+
if (options.convergenceSource &&
|
|
28
|
+
options.convergenceSource !== "prune" &&
|
|
29
|
+
options.convergenceSource !== "dream") {
|
|
30
|
+
throw new CliError(`Invalid convergence source: ${String(options.convergenceSource)}. Expected prune or dream.`);
|
|
31
|
+
}
|
|
32
|
+
const refreshConvergenceSource = options.refreshConvergence
|
|
33
|
+
? (options.convergenceSource ?? "prune")
|
|
34
|
+
: undefined;
|
|
15
35
|
for (const docPath of verifiedPaths) {
|
|
16
36
|
if (!preflightWorkspace.documentsByLlmdocPath.has(docPath)) {
|
|
17
37
|
throw new CliError(`Document does not exist: ${docPath}`);
|
|
18
38
|
}
|
|
19
39
|
}
|
|
20
|
-
const
|
|
40
|
+
const preflightGit = readWorkspaceGitState(preflightWorkspace);
|
|
41
|
+
if (preflightGit.available && preflightGit.detached) {
|
|
42
|
+
throw new CliError("Cannot run commit on a detached HEAD. Create or switch to a branch first (e.g. `git checkout -b <branch>`).", 70);
|
|
43
|
+
}
|
|
44
|
+
const porcelainRaw = runGitRaw(rootDir, ["status", "--porcelain=v1", "-z", "--no-renames", "--", "llmdoc"]);
|
|
45
|
+
const porcelainEntries = parseGitPorcelainZ(porcelainRaw);
|
|
46
|
+
const hasLlmdocChanges = porcelainEntries.length > 0;
|
|
47
|
+
const changedDocPaths = uniquePaths(porcelainEntries
|
|
48
|
+
.map((entry) => entry.path)
|
|
49
|
+
.filter((filePath) => filePath.startsWith("llmdoc/") && filePath.endsWith(".mdx")));
|
|
50
|
+
const gitDeletedDocPaths = new Set(porcelainEntries
|
|
51
|
+
.filter((entry) => (entry.indexStatus === "D" || entry.worktreeStatus === "D") &&
|
|
52
|
+
entry.path.startsWith("llmdoc/") &&
|
|
53
|
+
entry.path.endsWith(".mdx"))
|
|
54
|
+
.map((entry) => entry.path.slice("llmdoc/".length))
|
|
55
|
+
.filter((llmdocPath) => !preflightWorkspace.documentsByLlmdocPath.has(llmdocPath) &&
|
|
56
|
+
!preflightWorkspace.unparsedDocPaths?.has(llmdocPath)));
|
|
57
|
+
// Build candidate validation workspace with only Git-confirmed deleted docs stripped from meta.documents
|
|
58
|
+
// so prune deletions pass preflight while dangling links, requires, preload refs, or unparsed docs still fail.
|
|
59
|
+
const validationWorkspace = buildCandidateValidationWorkspace(preflightWorkspace, gitDeletedDocPaths);
|
|
60
|
+
const issues = validateWorkspace(validationWorkspace);
|
|
21
61
|
const errors = issues.filter((issue) => issue.severity === "error");
|
|
22
62
|
if (errors.length > 0) {
|
|
23
63
|
throw new CliError(`Validation failed; refusing to commit:\n${errors.map((issue) => ` ${issue.code} (${issue.path})`).join("\n")}`);
|
|
24
64
|
}
|
|
25
|
-
|
|
26
|
-
const hasLlmdocChanges = Boolean(porcelain.trim());
|
|
27
|
-
if (!hasLlmdocChanges && !options.all && verifiedPaths.length === 0) {
|
|
65
|
+
if (!hasLlmdocChanges && !options.all && verifiedPaths.length === 0 && !refreshConvergenceSource) {
|
|
28
66
|
return options.json ? { status: "no_change", commits: [], updated: [] } : "no_change: llmdoc/ has no changes to commit";
|
|
29
67
|
}
|
|
30
|
-
const changedDocPaths = porcelain
|
|
31
|
-
.split(/\r?\n/)
|
|
32
|
-
.filter(Boolean)
|
|
33
|
-
.map((line) => line.slice(3).trim())
|
|
34
|
-
.map((filePath) => (filePath.includes(" -> ") ? filePath.split(" -> ").pop() : filePath))
|
|
35
|
-
.filter((filePath) => filePath.startsWith("llmdoc/") && filePath.endsWith(".mdx"));
|
|
36
68
|
const existingChangedDocPaths = changedDocPaths
|
|
37
69
|
.map((filePath) => filePath.slice("llmdoc/".length))
|
|
38
70
|
.filter((llmdocPath) => preflightWorkspace.documentsByLlmdocPath.has(llmdocPath));
|
|
@@ -44,7 +76,8 @@ export function runCommit(options) {
|
|
|
44
76
|
assertRevisionAdvancePreconditions({
|
|
45
77
|
workspace: preflightWorkspace,
|
|
46
78
|
llmdocPaths: targetPaths,
|
|
47
|
-
updateAll: options.all ?? false
|
|
79
|
+
updateAll: options.all ?? false,
|
|
80
|
+
refreshConvergence: Boolean(refreshConvergenceSource)
|
|
48
81
|
});
|
|
49
82
|
}
|
|
50
83
|
catch (error) {
|
|
@@ -56,79 +89,190 @@ export function runCommit(options) {
|
|
|
56
89
|
workspace: preflightWorkspace,
|
|
57
90
|
verifiedPaths,
|
|
58
91
|
updateAll: options.all ?? false,
|
|
92
|
+
refreshConvergenceSource,
|
|
59
93
|
hasLlmdocChanges,
|
|
60
94
|
verifyFlags,
|
|
61
95
|
json: options.json ?? false
|
|
62
96
|
});
|
|
63
97
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
98
|
+
const snapshot = captureRollbackSnapshot(rootDir, preflightWorkspace.metaPath);
|
|
99
|
+
let docsCommit = null;
|
|
100
|
+
try {
|
|
101
|
+
runGit(rootDir, ["add", "--", "llmdoc"]);
|
|
102
|
+
runGit(rootDir, ["commit", ...verifyFlags, "-m", options.message ?? "docs(llmdoc): update knowledge", "--", "llmdoc"]);
|
|
103
|
+
docsCommit = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
|
|
104
|
+
// 重新加载:提交后的 workspace 是 fingerprint 的事实基础;已删除文档的 ledger 孤儿由 updateMetaRevisions 清理。
|
|
105
|
+
const workspace = loadWorkspace(rootDir);
|
|
106
|
+
const existingDocPaths = changedDocPaths
|
|
107
|
+
.map((filePath) => filePath.slice("llmdoc/".length))
|
|
108
|
+
.filter((llmdocPath) => workspace.documentsByLlmdocPath.has(llmdocPath));
|
|
109
|
+
const { meta, updatedPaths } = updateMetaRevisions({
|
|
110
|
+
workspace,
|
|
111
|
+
llmdocPaths: uniquePaths([...existingDocPaths, ...verifiedPaths]),
|
|
112
|
+
updateAll: options.all ?? false,
|
|
113
|
+
refreshConvergenceSource
|
|
114
|
+
});
|
|
115
|
+
writeMeta(workspace.metaPath, meta);
|
|
116
|
+
runGit(rootDir, ["add", "--", "llmdoc/meta.json"]);
|
|
117
|
+
runGit(rootDir, ["commit", ...verifyFlags, "-m", "chore(llmdoc): refresh fingerprints", "--", "llmdoc/meta.json"]);
|
|
118
|
+
const metaCommit = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
|
|
119
|
+
if (options.json) {
|
|
120
|
+
return {
|
|
121
|
+
status: "success",
|
|
122
|
+
commits: [docsCommit, metaCommit],
|
|
123
|
+
updated: updatedPaths,
|
|
124
|
+
baselineAdvanced: options.all ?? false,
|
|
125
|
+
...(refreshConvergenceSource ? { convergenceRefreshed: true } : {})
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
return [
|
|
129
|
+
`committed: ${docsCommit.slice(0, 7)} (docs) + ${metaCommit.slice(0, 7)} (meta)`,
|
|
130
|
+
`fingerprints: ${updatedPaths.length} document(s)${options.all ? ", baseline advanced" : ""}${refreshConvergenceSource ? `, convergence refreshed (${refreshConvergenceSource})` : ""}`
|
|
131
|
+
].join("\n");
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
rollbackCommitTransaction(rootDir, snapshot, docsCommit);
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
93
137
|
}
|
|
94
138
|
function commitMetaOnly(input) {
|
|
95
|
-
const { rootDir, workspace, verifiedPaths, updateAll, hasLlmdocChanges, verifyFlags, json } = input;
|
|
139
|
+
const { rootDir, workspace, verifiedPaths, updateAll, refreshConvergenceSource, hasLlmdocChanges, verifyFlags, json } = input;
|
|
96
140
|
const headRevision = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
|
|
141
|
+
const nowMs = Date.now();
|
|
97
142
|
const requestedPaths = updateAll ? workspace.documents.map((document) => document.llmdocPath) : verifiedPaths;
|
|
98
|
-
const
|
|
143
|
+
const convergenceRefreshNeeded = Boolean(refreshConvergenceSource) &&
|
|
144
|
+
!convergenceIsCurrent(rootDir, workspace, refreshConvergenceSource, nowMs);
|
|
145
|
+
const revisionRefreshNeeded = updateAll
|
|
99
146
|
? !revisionIsCurrent(rootDir, workspace.meta.baseline.revision, headRevision) ||
|
|
100
|
-
requestedPaths.some((docPath) => !
|
|
101
|
-
: requestedPaths.some((docPath) => !
|
|
147
|
+
requestedPaths.some((docPath) => !documentVerificationIsCurrent(rootDir, workspace.meta.documents[docPath], headRevision, nowMs))
|
|
148
|
+
: requestedPaths.some((docPath) => !documentVerificationIsCurrent(rootDir, workspace.meta.documents[docPath], headRevision, nowMs));
|
|
149
|
+
const refreshNeeded = convergenceRefreshNeeded || revisionRefreshNeeded;
|
|
102
150
|
if (!hasLlmdocChanges && !refreshNeeded) {
|
|
103
151
|
return json
|
|
104
152
|
? { status: "no_change", commits: [], updated: [] }
|
|
105
153
|
: "no_change: requested fingerprints are already current";
|
|
106
154
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
155
|
+
const snapshot = captureRollbackSnapshot(rootDir, workspace.metaPath);
|
|
156
|
+
try {
|
|
157
|
+
let updatedPaths = [];
|
|
158
|
+
if (refreshNeeded) {
|
|
159
|
+
const result = updateMetaRevisions({
|
|
160
|
+
workspace,
|
|
161
|
+
llmdocPaths: verifiedPaths,
|
|
162
|
+
updateAll,
|
|
163
|
+
refreshConvergenceSource
|
|
164
|
+
});
|
|
165
|
+
writeMeta(workspace.metaPath, result.meta);
|
|
166
|
+
updatedPaths = result.updatedPaths;
|
|
167
|
+
}
|
|
168
|
+
runGit(rootDir, ["add", "--", "llmdoc/meta.json"]);
|
|
169
|
+
runGit(rootDir, ["commit", ...verifyFlags, "-m", "chore(llmdoc): refresh fingerprints", "--", "llmdoc/meta.json"]);
|
|
170
|
+
const metaCommit = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
|
|
171
|
+
if (json) {
|
|
172
|
+
return {
|
|
173
|
+
status: "success",
|
|
174
|
+
commits: [metaCommit],
|
|
175
|
+
updated: updatedPaths,
|
|
176
|
+
baselineAdvanced: updateAll,
|
|
177
|
+
...(refreshConvergenceSource ? { convergenceRefreshed: true } : {})
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
return [
|
|
181
|
+
`committed: ${metaCommit.slice(0, 7)} (meta)`,
|
|
182
|
+
`fingerprints: ${updatedPaths.length} document(s)${updateAll ? ", baseline advanced" : ""}${refreshConvergenceSource ? `, convergence refreshed (${refreshConvergenceSource})` : ""}`
|
|
183
|
+
].join("\n");
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
rollbackCommitTransaction(rootDir, snapshot, null);
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function buildCandidateValidationWorkspace(workspace, gitDeletedDocPaths) {
|
|
191
|
+
if (!workspace.meta || gitDeletedDocPaths.size === 0) {
|
|
192
|
+
return workspace;
|
|
193
|
+
}
|
|
194
|
+
const candidateMeta = structuredClone(workspace.meta);
|
|
195
|
+
for (const deletedPath of gitDeletedDocPaths) {
|
|
196
|
+
delete candidateMeta.documents[deletedPath];
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
...workspace,
|
|
200
|
+
meta: candidateMeta
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
function captureRollbackSnapshot(rootDir, metaPath) {
|
|
204
|
+
const origHead = runGit(rootDir, ["rev-parse", "HEAD"]).trim();
|
|
205
|
+
const origBranchRef = runGit(rootDir, ["symbolic-ref", "HEAD"]).trim();
|
|
206
|
+
const origIndexTree = runGit(rootDir, ["write-tree"]).trim();
|
|
207
|
+
const origMetaBytes = fs.existsSync(metaPath) ? fs.readFileSync(metaPath) : null;
|
|
208
|
+
return {
|
|
209
|
+
origHead,
|
|
210
|
+
origBranchRef,
|
|
211
|
+
origIndexTree,
|
|
212
|
+
metaPath,
|
|
213
|
+
origMetaBytes
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function rollbackCommitTransaction(rootDir, snapshot, docsCommit) {
|
|
217
|
+
try {
|
|
218
|
+
if (snapshot.origMetaBytes !== null) {
|
|
219
|
+
writeFileAtomically(snapshot.metaPath, snapshot.origMetaBytes);
|
|
220
|
+
}
|
|
221
|
+
else if (fs.existsSync(snapshot.metaPath)) {
|
|
222
|
+
fs.unlinkSync(snapshot.metaPath);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
// Best-effort restore of meta.json.
|
|
227
|
+
}
|
|
228
|
+
if (docsCommit) {
|
|
229
|
+
spawnSync("git", ["update-ref", snapshot.origBranchRef, snapshot.origHead, docsCommit], {
|
|
230
|
+
cwd: rootDir,
|
|
231
|
+
encoding: "utf8"
|
|
113
232
|
});
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
233
|
+
}
|
|
234
|
+
spawnSync("git", ["read-tree", snapshot.origIndexTree], {
|
|
235
|
+
cwd: rootDir,
|
|
236
|
+
encoding: "utf8"
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
function documentVerificationIsCurrent(rootDir, docMeta, headRevision, nowMs) {
|
|
240
|
+
if (!docMeta || !revisionIsCurrent(rootDir, docMeta.validatedRevision, headRevision)) {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
if (docMeta.verifiedAt) {
|
|
244
|
+
const verifiedMs = Date.parse(docMeta.verifiedAt);
|
|
245
|
+
if (Number.isNaN(verifiedMs) || nowMs - verifiedMs >= VERIFIED_AT_IDEMPOTENCY_MS) {
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
// Legacy ledger without verifiedAt: allow zero-diff re-verification when the commit itself is old.
|
|
251
|
+
const commitMs = docMeta.validatedRevision ? readCommitTimestampMs(rootDir, docMeta.validatedRevision) : null;
|
|
252
|
+
if (commitMs === null || nowMs - commitMs >= VERIFIED_AT_IDEMPOTENCY_MS) {
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
function convergenceIsCurrent(rootDir, workspace, source, nowMs) {
|
|
258
|
+
const convergence = workspace.meta?.convergence;
|
|
259
|
+
if (!convergence || convergence.source !== source) {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
const currentDocumentCount = workspace.documents.length;
|
|
263
|
+
const currentTotalEstimatedTokens = workspace.documents.reduce((sum, document) => sum + document.estimatedTokens, 0);
|
|
264
|
+
if (convergence.documentCount !== currentDocumentCount ||
|
|
265
|
+
convergence.totalEstimatedTokens !== currentTotalEstimatedTokens) {
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
const capturedMs = Date.parse(convergence.capturedAt);
|
|
269
|
+
if (Number.isNaN(capturedMs) || nowMs - capturedMs >= VERIFIED_AT_IDEMPOTENCY_MS) {
|
|
270
|
+
return false;
|
|
271
|
+
}
|
|
272
|
+
const headFiles = runGitRaw(rootDir, ["show", "--pretty=", "--name-only", "-z", "HEAD"])
|
|
273
|
+
.split("\0")
|
|
274
|
+
.filter(Boolean);
|
|
275
|
+
return headFiles.length > 0 && headFiles.every((filePath) => filePath === "llmdoc/meta.json");
|
|
132
276
|
}
|
|
133
277
|
// commit 自身会在 fingerprint 锚点之后创建一个只修改 meta.json 的 follow-up commit。
|
|
134
278
|
// 这种差异不代表知识又过期了,否则重复 commit 会无限追逐自己创建的 meta commit。
|
|
@@ -136,11 +280,16 @@ function revisionIsCurrent(rootDir, revision, headRevision) {
|
|
|
136
280
|
if (!revision) {
|
|
137
281
|
return false;
|
|
138
282
|
}
|
|
139
|
-
|
|
283
|
+
const revOid = resolveCommitObjectId(rootDir, revision);
|
|
284
|
+
const headOid = resolveCommitObjectId(rootDir, headRevision);
|
|
285
|
+
if (!revOid || !headOid) {
|
|
286
|
+
return false;
|
|
287
|
+
}
|
|
288
|
+
if (revOid === headOid) {
|
|
140
289
|
return true;
|
|
141
290
|
}
|
|
142
|
-
const changedPaths =
|
|
143
|
-
.split(
|
|
291
|
+
const changedPaths = runGitRaw(rootDir, ["diff", "-z", "--name-only", `${revOid}..${headOid}`, "--"])
|
|
292
|
+
.split("\0")
|
|
144
293
|
.filter(Boolean);
|
|
145
294
|
return changedPaths.every((filePath) => filePath === "llmdoc/meta.json");
|
|
146
295
|
}
|
|
@@ -148,6 +297,9 @@ function uniquePaths(paths) {
|
|
|
148
297
|
return [...new Set(paths)].sort();
|
|
149
298
|
}
|
|
150
299
|
function runGit(rootDir, args) {
|
|
300
|
+
return runGitRaw(rootDir, args).trim();
|
|
301
|
+
}
|
|
302
|
+
function runGitRaw(rootDir, args) {
|
|
151
303
|
const result = spawnSync("git", ["-c", "core.quotePath=false", ...args], { cwd: rootDir, encoding: "utf8" });
|
|
152
304
|
if (result.status !== 0) {
|
|
153
305
|
throw new CliError((result.stderr || result.stdout || `git ${args[0]} failed`).trim());
|