@tokenroll/llmdoc 3.0.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.
@@ -0,0 +1,65 @@
1
+ import { DEFAULT_BUDGET, DEFAULT_LIMIT } from "./constants.js";
2
+ import { CliError } from "./errors.js";
3
+ export function paginate({ items, estimate, options }) {
4
+ const totalEstimatedTokens = items.reduce((sum, item) => sum + estimate(item), 0);
5
+ const limit = options.limit ?? DEFAULT_LIMIT;
6
+ const budget = options.budget ?? DEFAULT_BUDGET;
7
+ const offset = decodeCursor(options.cursor);
8
+ if (offset < 0 || offset > items.length) {
9
+ throw new CliError("cursor 非法或已失效。");
10
+ }
11
+ const selected = [];
12
+ let usedBudget = 0;
13
+ let index = offset;
14
+ while (index < items.length && selected.length < limit) {
15
+ const item = items[index];
16
+ const itemBudget = estimate(item);
17
+ const nextBudget = usedBudget + itemBudget;
18
+ if (selected.length > 0 && nextBudget > budget) {
19
+ break;
20
+ }
21
+ selected.push(item);
22
+ usedBudget = nextBudget;
23
+ index += 1;
24
+ }
25
+ if (selected.length === 0 && items[offset]) {
26
+ selected.push(items[offset]);
27
+ usedBudget = estimate(items[offset]);
28
+ index = offset + 1;
29
+ }
30
+ return {
31
+ items: selected,
32
+ totalItems: items.length,
33
+ returnedItems: selected.length,
34
+ totalEstimatedTokens,
35
+ returnedEstimatedTokens: usedBudget,
36
+ nextCursor: index < items.length ? encodeCursor({ offset: index }) : null
37
+ };
38
+ }
39
+ export function paginationMetadata(result) {
40
+ return {
41
+ totalItems: result.totalItems,
42
+ returnedItems: result.returnedItems,
43
+ totalEstimatedTokens: result.totalEstimatedTokens,
44
+ returnedEstimatedTokens: result.returnedEstimatedTokens,
45
+ nextCursor: result.nextCursor
46
+ };
47
+ }
48
+ function encodeCursor(payload) {
49
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
50
+ }
51
+ function decodeCursor(cursor) {
52
+ if (!cursor) {
53
+ return 0;
54
+ }
55
+ try {
56
+ const payload = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
57
+ if (!Number.isInteger(payload.offset) || payload.offset < 0) {
58
+ throw new Error("cursor offset invalid");
59
+ }
60
+ return payload.offset;
61
+ }
62
+ catch {
63
+ throw new CliError("cursor 非法或已损坏。");
64
+ }
65
+ }
@@ -0,0 +1,110 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import matter from "gray-matter";
4
+ import { resolveDocLink } from "./markdown.js";
5
+ export function updateDocumentForMove(document, mapping) {
6
+ const frontmatter = structuredClone(document.frontmatter);
7
+ frontmatter.relations = updateRelations(frontmatter.relations, mapping);
8
+ let body = document.body;
9
+ body = rewriteMarkdownLinks({
10
+ sourceLlmdocPathBefore: document.llmdocPath,
11
+ sourceLlmdocPathAfter: rewriteLlmdocTarget(document.llmdocPath, mapping),
12
+ body,
13
+ mapping
14
+ });
15
+ return matter.stringify(body, frontmatter);
16
+ }
17
+ function updateRelations(relations, mapping) {
18
+ if (!relations) {
19
+ return relations;
20
+ }
21
+ const patchPath = (input) => rewriteLlmdocTarget(input, mapping);
22
+ const next = {};
23
+ if (relations.requires?.length) {
24
+ next.requires = relations.requires.map(patchPath);
25
+ }
26
+ if (relations.related?.length) {
27
+ next.related = relations.related.map(patchPath);
28
+ }
29
+ return Object.keys(next).length > 0 ? next : undefined;
30
+ }
31
+ function rewriteMarkdownLinks(input) {
32
+ const { sourceLlmdocPathBefore, sourceLlmdocPathAfter, body, mapping } = input;
33
+ const linkPattern = /(?<!!)\[([^\]]*)]\(([^)]+)\)/g;
34
+ let openFence = null;
35
+ const parts = body.split(/(\r?\n)/);
36
+ return parts
37
+ .map((part, index) => {
38
+ if (index % 2 === 1) {
39
+ return part;
40
+ }
41
+ const fence = part.match(/^\s*(`{3,}|~{3,})/);
42
+ if (fence) {
43
+ const token = fence[1];
44
+ const marker = token[0];
45
+ if (!openFence) {
46
+ openFence = { marker, length: token.length };
47
+ }
48
+ else if (openFence.marker === marker && token.length >= openFence.length) {
49
+ openFence = null;
50
+ }
51
+ return part;
52
+ }
53
+ if (openFence) {
54
+ return part;
55
+ }
56
+ return rewriteOutsideInlineCode(part, (plainText) => plainText.replace(linkPattern, (fullMatch, label, target) => {
57
+ if (target.startsWith("http://") ||
58
+ target.startsWith("https://") ||
59
+ target.startsWith("mailto:") ||
60
+ target.startsWith("#")) {
61
+ return fullMatch;
62
+ }
63
+ const { pathname, suffix } = splitLinkTarget(target);
64
+ const resolvedBefore = resolveDocLink(sourceLlmdocPathBefore, pathname);
65
+ const rewrittenTarget = rewriteLlmdocTarget(resolvedBefore, mapping);
66
+ const sourceDirAfter = path.posix.dirname(sourceLlmdocPathAfter);
67
+ const relativeAfter = path.posix.relative(sourceDirAfter, rewrittenTarget) || path.posix.basename(rewrittenTarget);
68
+ return `[${label}](${relativeAfter}${suffix})`;
69
+ }));
70
+ })
71
+ .join("");
72
+ }
73
+ function splitLinkTarget(target) {
74
+ const suffixOffsets = [target.indexOf("?"), target.indexOf("#")].filter((offset) => offset >= 0);
75
+ const suffixOffset = suffixOffsets.length > 0 ? Math.min(...suffixOffsets) : target.length;
76
+ return {
77
+ pathname: target.slice(0, suffixOffset),
78
+ suffix: target.slice(suffixOffset)
79
+ };
80
+ }
81
+ function rewriteOutsideInlineCode(line, transform) {
82
+ const codeSpan = /(`+)(.*?)\1/g;
83
+ let cursor = 0;
84
+ let result = "";
85
+ for (const match of line.matchAll(codeSpan)) {
86
+ const offset = match.index ?? 0;
87
+ result += transform(line.slice(cursor, offset));
88
+ result += match[0];
89
+ cursor = offset + match[0].length;
90
+ }
91
+ result += transform(line.slice(cursor));
92
+ return result;
93
+ }
94
+ function rewriteLlmdocTarget(input, mapping) {
95
+ for (const item of mapping) {
96
+ if (input === item.oldLlmdocPath) {
97
+ return item.newLlmdocPath;
98
+ }
99
+ if (input.startsWith(`${item.oldLlmdocPath}/`)) {
100
+ return `${item.newLlmdocPath}${input.slice(item.oldLlmdocPath.length)}`;
101
+ }
102
+ }
103
+ return input;
104
+ }
105
+ export function writeFileIfChanged(filePath, nextContent) {
106
+ const current = fs.readFileSync(filePath, "utf8");
107
+ if (current !== nextContent) {
108
+ fs.writeFileSync(filePath, nextContent);
109
+ }
110
+ }
@@ -0,0 +1,63 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import Ajv2020Module from "ajv/dist/2020.js";
4
+ import { packageRootFromImport } from "./package-root.js";
5
+ const Ajv2020 = Ajv2020Module;
6
+ const ajv = new Ajv2020({ allErrors: true, strict: false });
7
+ function readSchema(fileName) {
8
+ const packageRoot = packageRootFromImport(import.meta.url);
9
+ const schemaPath = path.join(packageRoot, "schemas", fileName);
10
+ return JSON.parse(fs.readFileSync(schemaPath, "utf8"));
11
+ }
12
+ const docValidator = ajv.compile(readSchema("doc-frontmatter.schema.json"));
13
+ const metaValidator = ajv.compile(readSchema("meta.schema.json"));
14
+ export function validateDocFrontmatter(input) {
15
+ const ok = docValidator(input);
16
+ if (ok) {
17
+ return [];
18
+ }
19
+ return (docValidator.errors ?? []).map(formatAjvError);
20
+ }
21
+ export function validateMeta(input) {
22
+ const ok = metaValidator(input);
23
+ if (!ok) {
24
+ return (metaValidator.errors ?? []).map(formatAjvError);
25
+ }
26
+ const meta = input;
27
+ const errors = [];
28
+ if (!isValidUtcTimestamp(meta.baseline.verifiedAt)) {
29
+ errors.push("/baseline/verifiedAt must be a real RFC3339 UTC timestamp");
30
+ }
31
+ if (!isValidUtcTimestamp(meta.convergence.capturedAt)) {
32
+ errors.push("/convergence/capturedAt must be a real RFC3339 UTC timestamp");
33
+ }
34
+ return errors;
35
+ }
36
+ function formatAjvError(error) {
37
+ return `${error.instancePath || "/"} ${error.message ?? "invalid"}`;
38
+ }
39
+ function isValidUtcTimestamp(input) {
40
+ const match = input.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z$/);
41
+ if (!match) {
42
+ return false;
43
+ }
44
+ const [, yearText, monthText, dayText, hourText, minuteText, secondText] = match;
45
+ const year = Number(yearText);
46
+ const month = Number(monthText);
47
+ const day = Number(dayText);
48
+ const hour = Number(hourText);
49
+ const minute = Number(minuteText);
50
+ const second = Number(secondText);
51
+ if (year < 1 || month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59) {
52
+ return false;
53
+ }
54
+ const parsed = new Date(0);
55
+ parsed.setUTCFullYear(year, month - 1, day);
56
+ parsed.setUTCHours(hour, minute, second, 0);
57
+ return (parsed.getUTCFullYear() === year &&
58
+ parsed.getUTCMonth() === month - 1 &&
59
+ parsed.getUTCDate() === day &&
60
+ parsed.getUTCHours() === hour &&
61
+ parsed.getUTCMinutes() === minute &&
62
+ parsed.getUTCSeconds() === second);
63
+ }
@@ -0,0 +1,157 @@
1
+ import fs from "node:fs";
2
+ import { Minimatch } from "minimatch";
3
+ import { CACHE_DIR, SEARCH_CACHE_FILE } from "./constants.js";
4
+ import { ensureDirectory, resolveInsideRoot } from "./fs.js";
5
+ export function searchDocuments(workspace, query, filters) {
6
+ const tokens = tokenize(query);
7
+ const cache = loadSearchCache(workspace);
8
+ const filteredDocs = workspace.documents.filter((document) => {
9
+ if (filters?.topic && document.topic !== filters.topic) {
10
+ return false;
11
+ }
12
+ if (filters?.kind && document.frontmatter.kind !== filters.kind) {
13
+ return false;
14
+ }
15
+ return true;
16
+ });
17
+ const documentFrequency = new Map();
18
+ for (const token of tokens) {
19
+ let count = 0;
20
+ for (const document of filteredDocs) {
21
+ const searchableText = cache.entries[document.llmdocPath]?.searchableText ?? buildSearchableText(document);
22
+ if (searchableText.includes(token)) {
23
+ count += 1;
24
+ }
25
+ }
26
+ documentFrequency.set(token, count);
27
+ }
28
+ return filteredDocs
29
+ .map((document) => {
30
+ const searchableText = cache.entries[document.llmdocPath]?.searchableText ?? buildSearchableText(document);
31
+ const wordCount = tokenize(searchableText).length || 1;
32
+ let score = 0;
33
+ for (const token of tokens) {
34
+ const frequency = countSubstring(searchableText, token);
35
+ if (frequency === 0) {
36
+ continue;
37
+ }
38
+ const df = documentFrequency.get(token) ?? 0;
39
+ const idf = Math.log(1 + (filteredDocs.length - df + 0.5) / (df + 0.5));
40
+ score += idf * ((frequency * 2.2) / (frequency + 1.2 * (1 - 0.75 + 0.75 * (wordCount / 200))));
41
+ }
42
+ return {
43
+ document,
44
+ score,
45
+ snippet: buildSnippet(document.body, tokens)
46
+ };
47
+ })
48
+ .filter((entry) => entry.score > 0)
49
+ .sort((left, right) => right.score - left.score || left.document.llmdocPath.localeCompare(right.document.llmdocPath));
50
+ }
51
+ export function matchesCodePathPattern(pattern, repoRelativePath) {
52
+ const normalizedPattern = normalizeCodePathPattern(pattern);
53
+ if (normalizedPattern === repoRelativePath) {
54
+ return true;
55
+ }
56
+ if (!/[*?[\]{}]/.test(normalizedPattern)) {
57
+ return false;
58
+ }
59
+ return new Minimatch(normalizedPattern, { dot: true, nocase: false }).match(repoRelativePath);
60
+ }
61
+ function normalizeCodePathPattern(pattern) {
62
+ let normalized = pattern.replaceAll("\\", "/");
63
+ while (normalized.startsWith("./")) {
64
+ normalized = normalized.slice(2);
65
+ }
66
+ return normalized.replace(/\/+$/, "");
67
+ }
68
+ function loadSearchCache(workspace) {
69
+ const next = {
70
+ version: 1,
71
+ entries: {}
72
+ };
73
+ const cachePath = resolveCachePath(workspace);
74
+ const existing = cachePath ? readCache(cachePath) : null;
75
+ for (const document of workspace.documents) {
76
+ const stats = fs.statSync(document.absolutePath);
77
+ const cachedEntry = existing?.entries[document.llmdocPath];
78
+ if (cachedEntry && cachedEntry.mtimeMs === stats.mtimeMs) {
79
+ next.entries[document.llmdocPath] = cachedEntry;
80
+ continue;
81
+ }
82
+ next.entries[document.llmdocPath] = {
83
+ llmdocPath: document.llmdocPath,
84
+ mtimeMs: stats.mtimeMs,
85
+ searchableText: buildSearchableText(document)
86
+ };
87
+ }
88
+ if (cachePath) {
89
+ try {
90
+ ensureDirectory(cachePath);
91
+ fs.writeFileSync(cachePath, JSON.stringify(next, null, 2));
92
+ }
93
+ catch {
94
+ return next;
95
+ }
96
+ }
97
+ return next;
98
+ }
99
+ function readCache(cachePath) {
100
+ if (!fs.existsSync(cachePath)) {
101
+ return null;
102
+ }
103
+ try {
104
+ return JSON.parse(fs.readFileSync(cachePath, "utf8"));
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ }
110
+ function resolveCachePath(workspace) {
111
+ try {
112
+ return resolveInsideRoot(workspace.rootDir, `${CACHE_DIR}/${SEARCH_CACHE_FILE}`, { allowMissing: true });
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ }
118
+ function buildSearchableText(document) {
119
+ return [
120
+ document.frontmatter.description,
121
+ document.title ?? "",
122
+ document.body
123
+ ]
124
+ .join("\n")
125
+ .toLowerCase();
126
+ }
127
+ function tokenize(input) {
128
+ return input
129
+ .toLowerCase()
130
+ .split(/[^a-z0-9\u4e00-\u9fff_-]+/)
131
+ .map((token) => token.trim())
132
+ .filter(Boolean);
133
+ }
134
+ function buildSnippet(body, tokens) {
135
+ const lines = body.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
136
+ const loweredTokens = tokens.map((token) => token.toLowerCase());
137
+ const line = lines.find((candidate) => loweredTokens.some((token) => candidate.toLowerCase().includes(token))) ??
138
+ lines[0] ??
139
+ "";
140
+ return line.slice(0, 180);
141
+ }
142
+ function countSubstring(haystack, needle) {
143
+ if (!needle) {
144
+ return 0;
145
+ }
146
+ let count = 0;
147
+ let offset = 0;
148
+ while (offset < haystack.length) {
149
+ const index = haystack.indexOf(needle, offset);
150
+ if (index === -1) {
151
+ break;
152
+ }
153
+ count += 1;
154
+ offset = index + needle.length;
155
+ }
156
+ return count;
157
+ }
@@ -0,0 +1,251 @@
1
+ import fs from "node:fs";
2
+ import { canAdvanceRevisions, gitCommitExists, readChangedPathsSince, readGitState } from "./git.js";
3
+ import { normalizeRepoRelativePath } from "./fs.js";
4
+ import { matchesCodePathPattern } from "./search.js";
5
+ export function analyzeDelta(workspace, scope) {
6
+ const git = readWorkspaceGitState(workspace);
7
+ const scopedDocuments = applyScope(workspace.documents, scope);
8
+ const dirtyPaths = uniquePaths([...git.stagedPaths, ...git.unstagedPaths, ...git.untrackedPaths].filter(isImplementationSurfacePath));
9
+ const invalidRevisionDocuments = [];
10
+ const invalidRevisionReasons = [];
11
+ const changedPathsByRevision = new Map();
12
+ const commitExistsByRevision = new Map();
13
+ const cachedCommitExists = (revision) => {
14
+ const cached = commitExistsByRevision.get(revision);
15
+ if (cached !== undefined) {
16
+ return cached;
17
+ }
18
+ const exists = gitCommitExists(workspace.rootDir, revision);
19
+ commitExistsByRevision.set(revision, exists);
20
+ return exists;
21
+ };
22
+ const directImpacts = scopedDocuments
23
+ .map((document) => {
24
+ const validatedRevision = workspace.meta?.documents[document.llmdocPath]?.validatedRevision ?? null;
25
+ const revisionInvalid = !validatedRevision ||
26
+ !git.headRevision ||
27
+ !cachedCommitExists(validatedRevision);
28
+ if (revisionInvalid) {
29
+ invalidRevisionDocuments.push(document);
30
+ invalidRevisionReasons.push(!validatedRevision
31
+ ? `文档 ${document.llmdocPath} 缺少 validatedRevision`
32
+ : `文档 ${document.llmdocPath} 的 validatedRevision 不存在于当前 git 历史: ${validatedRevision}`);
33
+ }
34
+ const changedCommittedPaths = !revisionInvalid && git.headRevision && validatedRevision !== git.headRevision
35
+ ? getChangedPathsForRevision(workspace.rootDir, validatedRevision, git.headRevision, changedPathsByRevision).filter((filePath) => isImplementationSurfacePath(filePath) && documentMatchesPath(document, filePath))
36
+ : [];
37
+ const dirtyDocumentPaths = dirtyPaths.filter((filePath) => documentMatchesPath(document, filePath));
38
+ return {
39
+ document,
40
+ changedCommittedPaths,
41
+ dirtyPaths: dirtyDocumentPaths,
42
+ needsReviewBecauseOf: revisionInvalid ? ["validatedRevision invalid"] : []
43
+ };
44
+ })
45
+ .filter((impact) => impact.changedCommittedPaths.length > 0 ||
46
+ impact.dirtyPaths.length > 0 ||
47
+ impact.needsReviewBecauseOf.includes("validatedRevision invalid"));
48
+ const directMap = new Map(directImpacts.map((impact) => [impact.document.llmdocPath, impact]));
49
+ const reverseRequires = buildReverseRequires(workspace.documents);
50
+ const needsReviewMap = new Map();
51
+ for (const impact of directImpacts) {
52
+ for (const dependent of reverseRequires.get(impact.document.llmdocPath) ?? []) {
53
+ if (!scopedDocuments.some((document) => document.llmdocPath === dependent.llmdocPath)) {
54
+ continue;
55
+ }
56
+ if (!directMap.has(dependent.llmdocPath)) {
57
+ needsReviewMap.set(dependent.llmdocPath, dependent);
58
+ }
59
+ const existing = directMap.get(dependent.llmdocPath);
60
+ if (existing) {
61
+ existing.needsReviewBecauseOf.push(impact.document.llmdocPath);
62
+ }
63
+ }
64
+ }
65
+ const needsReview = [...needsReviewMap.values()].sort((left, right) => left.llmdocPath.localeCompare(right.llmdocPath));
66
+ const dirtyDocuments = directImpacts.filter((impact) => impact.dirtyPaths.length > 0).map((impact) => impact.document);
67
+ const baselineCommittedPaths = git.committedChangedPaths.filter(isImplementationSurfacePath);
68
+ const unmappedCommittedPaths = baselineCommittedPaths.filter((filePath) => !workspace.documents.some((document) => documentMatchesPath(document, filePath)));
69
+ const unmappedDirtyPaths = dirtyPaths.filter((filePath) => !workspace.documents.some((document) => documentMatchesPath(document, filePath)));
70
+ const reasons = [];
71
+ if (!git.available || git.degradedReason) {
72
+ reasons.push(git.degradedReason ?? "git 状态不可用");
73
+ }
74
+ if (invalidRevisionReasons.length > 0) {
75
+ reasons.push(...invalidRevisionReasons);
76
+ }
77
+ if (unmappedCommittedPaths.length > 0 || unmappedDirtyPaths.length > 0) {
78
+ reasons.push("存在未映射代码路径");
79
+ }
80
+ if (needsReview.length > 0) {
81
+ reasons.push("存在 requires 反向一跳需复核文档");
82
+ }
83
+ if (directImpacts.length > 8) {
84
+ reasons.push("受影响文档过多,建议 deep");
85
+ }
86
+ if (dirtyDocuments.length > 0) {
87
+ reasons.push("存在未提交 dirty 关联代码");
88
+ }
89
+ const suggestedMode = reasons.some((reason) => ["未映射", "需复核", "过多", "dirty", "不可用", "不存在于当前 git 历史", "validatedRevision", "缺少"].some((keyword) => reason.includes(keyword)))
90
+ ? "deep"
91
+ : "light";
92
+ return {
93
+ git,
94
+ impacts: directImpacts.sort((left, right) => left.document.llmdocPath.localeCompare(right.document.llmdocPath)),
95
+ needsReview,
96
+ dirtyDocuments: dirtyDocuments.sort((left, right) => left.llmdocPath.localeCompare(right.llmdocPath)),
97
+ unmappedCommittedPaths,
98
+ unmappedDirtyPaths,
99
+ suggestedMode,
100
+ reasons,
101
+ scopedDocuments
102
+ };
103
+ }
104
+ export function readWorkspaceGitState(workspace) {
105
+ return readGitState(workspace.rootDir, workspace.meta?.baseline.revision ?? null);
106
+ }
107
+ export function parseScope(values, workspace) {
108
+ if (!values || values.length === 0) {
109
+ return undefined;
110
+ }
111
+ const topics = new Set();
112
+ const documentPaths = new Set();
113
+ for (const value of values) {
114
+ const raw = value.trim();
115
+ if (workspace.topics.has(raw)) {
116
+ topics.add(raw);
117
+ continue;
118
+ }
119
+ const normalized = normalizeRepoRelativePath(raw.startsWith("llmdoc/") ? raw : `llmdoc/${raw}`).slice("llmdoc/".length);
120
+ if (workspace.topics.has(normalized)) {
121
+ topics.add(normalized);
122
+ continue;
123
+ }
124
+ if (!workspace.documentsByLlmdocPath.has(normalized)) {
125
+ throw new Error(`scope 未命中任何 topic 或文档: ${raw}`);
126
+ }
127
+ documentPaths.add(normalized);
128
+ }
129
+ return { topics, documentPaths };
130
+ }
131
+ export function computeGrowthState(workspace) {
132
+ const currentDocumentCount = workspace.documents.length;
133
+ const currentTotalEstimatedTokens = workspace.documents.reduce((sum, document) => sum + document.estimatedTokens, 0);
134
+ const baselineDocumentCount = workspace.meta?.convergence.documentCount ?? null;
135
+ const baselineTotalEstimatedTokens = workspace.meta?.convergence.totalEstimatedTokens ?? null;
136
+ const documentDelta = baselineDocumentCount === null ? null : currentDocumentCount - baselineDocumentCount;
137
+ const tokenDelta = baselineTotalEstimatedTokens === null ? null : currentTotalEstimatedTokens - baselineTotalEstimatedTokens;
138
+ const exceedsGate = tokenDelta !== null ? tokenDelta > Math.max(500, Math.round((baselineTotalEstimatedTokens ?? 0) * 0.2)) : false;
139
+ return {
140
+ currentDocumentCount,
141
+ currentTotalEstimatedTokens,
142
+ baselineDocumentCount,
143
+ baselineTotalEstimatedTokens,
144
+ documentDelta,
145
+ tokenDelta,
146
+ exceedsGate
147
+ };
148
+ }
149
+ export function updateMetaRevisions(input) {
150
+ const { workspace, llmdocPaths, updateAll } = input;
151
+ if (!workspace.meta) {
152
+ throw new Error("缺少 meta.json");
153
+ }
154
+ const git = readWorkspaceGitState(workspace);
155
+ const advance = canAdvanceRevisions(git);
156
+ if (!advance.ok) {
157
+ throw new Error(advance.reason);
158
+ }
159
+ const targetPaths = updateAll ? workspace.documents.map((document) => document.llmdocPath) : llmdocPaths;
160
+ const dirtyPaths = uniquePaths([...git.stagedPaths, ...git.unstagedPaths, ...git.untrackedPaths]).filter(isImplementationSurfacePath);
161
+ // 只有映射到某份文档 code.paths 的 dirty 变更才阻塞推进;
162
+ // 无关的 untracked/dirty 文件不影响 revision 的真实性,不应拦路。
163
+ const blocked = targetPaths.filter((docPath) => {
164
+ const document = workspace.documentsByLlmdocPath.get(docPath);
165
+ return document ? dirtyPaths.some((filePath) => documentMatchesPath(document, filePath)) : false;
166
+ });
167
+ if (blocked.length > 0) {
168
+ throw new Error(updateAll
169
+ ? `全量 fingerprint 时以下文档关联代码存在 dirty 变更,不能伪造 revision: ${blocked.join(", ")}`
170
+ : `以下文档关联代码存在 dirty 变更,不能伪造 revision: ${blocked.join(", ")}`);
171
+ }
172
+ const nextMeta = structuredClone(workspace.meta);
173
+ // 文档已被删除的孤儿 ledger 条目在此顺带清理:
174
+ // recorder 不允许手编辑 meta.json,删除文档后的 ledger 收敛只能由 CLI 完成。
175
+ for (const docPath of Object.keys(nextMeta.documents)) {
176
+ if (!workspace.documentsByLlmdocPath.has(docPath)) {
177
+ delete nextMeta.documents[docPath];
178
+ }
179
+ }
180
+ for (const docPath of targetPaths) {
181
+ nextMeta.documents[docPath] = {
182
+ validatedRevision: git.headRevision
183
+ };
184
+ }
185
+ if (updateAll) {
186
+ nextMeta.baseline.revision = git.headRevision;
187
+ nextMeta.baseline.verifiedAt = new Date().toISOString();
188
+ }
189
+ return { meta: nextMeta, updatedPaths: targetPaths.slice().sort() };
190
+ }
191
+ export function writeMeta(metaPath, meta) {
192
+ fs.writeFileSync(metaPath, `${JSON.stringify(meta, null, 2)}\n`);
193
+ }
194
+ function applyScope(documents, scope) {
195
+ if (!scope) {
196
+ return documents.slice();
197
+ }
198
+ return documents.filter((document) => {
199
+ if (document.topic && scope.topics.has(document.topic)) {
200
+ return true;
201
+ }
202
+ return scope.documentPaths.has(document.llmdocPath);
203
+ });
204
+ }
205
+ function documentMatchesPath(document, repoRelativePath) {
206
+ return (document.frontmatter.code?.paths ?? []).some((pattern) => matchesCodePathPattern(pattern, repoRelativePath));
207
+ }
208
+ function uniquePaths(paths) {
209
+ return [...new Set(paths)].sort();
210
+ }
211
+ const NON_IMPLEMENTATION_BASENAMES = new Set([
212
+ ".gitignore",
213
+ ".gitattributes",
214
+ "package-lock.json",
215
+ "yarn.lock",
216
+ "pnpm-lock.yaml",
217
+ "bun.lockb",
218
+ "Cargo.lock",
219
+ "poetry.lock",
220
+ "uv.lock",
221
+ "composer.lock",
222
+ "Gemfile.lock",
223
+ "go.sum"
224
+ ]);
225
+ function isImplementationSurfacePath(repoRelativePath) {
226
+ if (repoRelativePath.startsWith("llmdoc/") || repoRelativePath.startsWith(".llmdoc-tmp/")) {
227
+ return false;
228
+ }
229
+ const basename = repoRelativePath.split("/").pop() ?? repoRelativePath;
230
+ return !NON_IMPLEMENTATION_BASENAMES.has(basename);
231
+ }
232
+ function buildReverseRequires(documents) {
233
+ const mapping = new Map();
234
+ for (const document of documents) {
235
+ for (const requirement of document.frontmatter.relations?.requires ?? []) {
236
+ const bucket = mapping.get(requirement) ?? [];
237
+ bucket.push(document);
238
+ mapping.set(requirement, bucket);
239
+ }
240
+ }
241
+ return mapping;
242
+ }
243
+ function getChangedPathsForRevision(rootDir, revision, headRevision, cache) {
244
+ const cached = cache.get(revision);
245
+ if (cached) {
246
+ return cached;
247
+ }
248
+ const paths = readChangedPathsSince(rootDir, revision, headRevision);
249
+ cache.set(revision, paths);
250
+ return paths;
251
+ }