@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.
package/dist/cli.js ADDED
@@ -0,0 +1,261 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { Command } from "commander";
4
+ import { findProjectRoot, findProjectRootOrNull } from "./lib/fs.js";
5
+ import { CliError } from "./lib/errors.js";
6
+ import { runTree } from "./commands/tree.js";
7
+ import { runIndex } from "./commands/index.js";
8
+ import { runShow } from "./commands/show.js";
9
+ import { runSearch } from "./commands/search.js";
10
+ import { runContext } from "./commands/context.js";
11
+ import { runValidate } from "./commands/validate.js";
12
+ import { runNew } from "./commands/new.js";
13
+ import { runMove } from "./commands/mv.js";
14
+ import { runStatus } from "./commands/status.js";
15
+ import { runDelta } from "./commands/delta.js";
16
+ import { runFingerprint } from "./commands/fingerprint.js";
17
+ import { runHook } from "./commands/hook.js";
18
+ import { runPrune } from "./commands/prune.js";
19
+ import { parseAndValidateJsonString, stringifyValidatedOutput } from "./lib/output-schema.js";
20
+ import { packageRootFromImport } from "./lib/package-root.js";
21
+ export async function runCli(argv, cwd = process.cwd(), stdin = "") {
22
+ if (argv.includes("--version") || argv.includes("-V")) {
23
+ return {
24
+ exitCode: 0,
25
+ stdout: readPackageVersion()
26
+ };
27
+ }
28
+ const program = new Command();
29
+ const output = [];
30
+ let exitCode = 0;
31
+ let globalOptions;
32
+ try {
33
+ globalOptions = parseGlobalOptions(argv);
34
+ }
35
+ catch (error) {
36
+ if (error instanceof CliError) {
37
+ return {
38
+ exitCode: error.exitCode,
39
+ stdout: error.message
40
+ };
41
+ }
42
+ throw error;
43
+ }
44
+ program.name("llmdoc").version(readPackageVersion(), "--version", "输出 CLI 版本").showHelpAfterError();
45
+ program.option("--json", "输出 JSON").option("--cursor <cursor>").option("--budget <budget>", "预算 token", parseInteger).option("--limit <limit>", "返回条数", parseInteger);
46
+ program
47
+ .command("tree")
48
+ .description("输出 llmdoc 全局地图")
49
+ .option("--docs", "展开到文档级")
50
+ .action((commandOptions) => {
51
+ const rootDir = findProjectRoot(cwd);
52
+ const result = runTree({ ...globalOptions, ...commandOptions, cwd: rootDir });
53
+ output.push(writeOutput(commandOptions.docs ? "treeDocs" : "treeTopics", result, globalOptions.json));
54
+ });
55
+ program
56
+ .command("index")
57
+ .description("列出文档元数据索引")
58
+ .option("--topic <topic>")
59
+ .option("--kind <kind>")
60
+ .action((commandOptions) => {
61
+ const rootDir = findProjectRoot(cwd);
62
+ output.push(writeOutput("index", runIndex({ ...globalOptions, ...commandOptions, cwd: rootDir }), globalOptions.json));
63
+ });
64
+ program
65
+ .command("show")
66
+ .description("读取一个或多个文档正文")
67
+ .argument("<path...>")
68
+ .action((paths) => {
69
+ const rootDir = findProjectRoot(cwd);
70
+ output.push(writeOutput("show", runShow({ ...globalOptions, cwd: rootDir, paths }), globalOptions.json));
71
+ });
72
+ program
73
+ .command("search")
74
+ .description("按词法检索 llmdoc 文档")
75
+ .argument("<query>")
76
+ .option("--topic <topic>")
77
+ .option("--kind <kind>")
78
+ .action((query, commandOptions) => {
79
+ const rootDir = findProjectRoot(cwd);
80
+ output.push(writeOutput("search", runSearch({ ...globalOptions, ...commandOptions, cwd: rootDir, query }), globalOptions.json));
81
+ });
82
+ program
83
+ .command("context")
84
+ .description("按源码文件反查应读文档")
85
+ .requiredOption("--files <files...>")
86
+ .action((commandOptions) => {
87
+ const rootDir = findProjectRoot(cwd);
88
+ output.push(writeOutput("context", runContext({
89
+ ...globalOptions,
90
+ cwd: rootDir,
91
+ files: commandOptions.files
92
+ }), globalOptions.json));
93
+ });
94
+ program
95
+ .command("validate")
96
+ .description("校验 llmdoc 结构与引用")
97
+ .action((commandOptions) => {
98
+ const rootDir = findProjectRoot(cwd);
99
+ const result = runValidate({ ...globalOptions, ...commandOptions, cwd: rootDir });
100
+ exitCode = result.exitCode;
101
+ output.push(writeOutput("validate", result.output, globalOptions.json));
102
+ });
103
+ program
104
+ .command("status")
105
+ .description("查看 baseline、dirty 与增长状态")
106
+ .action((commandOptions) => {
107
+ const rootDir = findProjectRoot(cwd);
108
+ output.push(writeOutput("status", runStatus({ ...globalOptions, ...commandOptions, cwd: rootDir }), globalOptions.json));
109
+ });
110
+ program
111
+ .command("delta")
112
+ .description("查看代码变化对应的文档影响面")
113
+ .option("--scope <scope...>")
114
+ .action((commandOptions) => {
115
+ const rootDir = findProjectRoot(cwd);
116
+ output.push(writeOutput("delta", runDelta({ ...globalOptions, ...commandOptions, cwd: rootDir }), globalOptions.json));
117
+ });
118
+ program
119
+ .command("fingerprint")
120
+ .description("刷新文档 validatedRevision 或 baseline")
121
+ .option("--update <path...>")
122
+ .option("--all", "更新全部文档并推进 baseline")
123
+ .action((commandOptions) => {
124
+ const rootDir = findProjectRoot(cwd);
125
+ output.push(writeOutput("fingerprint", runFingerprint({
126
+ ...globalOptions,
127
+ cwd: rootDir,
128
+ update: commandOptions.update,
129
+ all: commandOptions.all
130
+ }), globalOptions.json));
131
+ });
132
+ program
133
+ .command("prune")
134
+ .description("输出只读收敛候选报告")
135
+ .option("--report", "输出只读收敛报告")
136
+ .action((commandOptions) => {
137
+ const rootDir = findProjectRoot(cwd);
138
+ output.push(writeOutput("prune", runPrune({ ...globalOptions, cwd: rootDir, report: commandOptions.report }), globalOptions.json));
139
+ });
140
+ program
141
+ .command("upgrade")
142
+ .description("盘点 legacy/V2 到 V3 的迁移需求")
143
+ .action(async (commandOptions) => {
144
+ const { runUpgrade } = await import("./commands/upgrade.js");
145
+ const rootDir = findProjectRootOrNull(cwd) ?? cwd;
146
+ output.push(writeOutput("upgrade", await runUpgrade({ ...globalOptions, ...commandOptions, cwd: rootDir }), globalOptions.json));
147
+ });
148
+ const hookCommand = program.command("hook");
149
+ hookCommand
150
+ .command("session-start")
151
+ .description("输出 SessionStart 短状态信号")
152
+ .action(() => {
153
+ const rootDir = findProjectRootOrNull(cwd) ?? cwd;
154
+ output.push(runHook({ cwd: rootDir, mode: "session-start", stdin }));
155
+ });
156
+ hookCommand
157
+ .command("stop")
158
+ .description("输出 Stop hook JSON 提醒")
159
+ .action(() => {
160
+ const rootDir = findProjectRootOrNull(cwd) ?? cwd;
161
+ output.push(parseAndValidateJsonString("hook", runHook({ cwd: rootDir, mode: "stop", stdin })));
162
+ });
163
+ hookCommand
164
+ .command("compact")
165
+ .description("输出 PreCompact hook JSON 指令")
166
+ .action(() => {
167
+ const rootDir = findProjectRootOrNull(cwd) ?? cwd;
168
+ output.push(parseAndValidateJsonString("hook", runHook({ cwd: rootDir, mode: "compact", stdin })));
169
+ });
170
+ program
171
+ .command("serve")
172
+ .description("启动本地 Web Viewer(HTTP 服务,浏览文档结构与关联,Ctrl-C 退出)")
173
+ .option("--port <port>", "监听端口", parseInteger)
174
+ .action(async (commandOptions) => {
175
+ const { runServe } = await import("./commands/serve.js");
176
+ const rootDir = findProjectRoot(cwd);
177
+ output.push(await runServe({ cwd: rootDir, port: commandOptions.port }));
178
+ });
179
+ program
180
+ .command("new")
181
+ .argument("<path>")
182
+ .requiredOption("--kind <kind>")
183
+ .option("--description <description>")
184
+ .action((targetPath, commandOptions) => {
185
+ const rootDir = findProjectRoot(cwd);
186
+ output.push(writeOutput("new", runNew({
187
+ ...globalOptions,
188
+ cwd: rootDir,
189
+ path: targetPath,
190
+ kind: commandOptions.kind,
191
+ description: commandOptions.description
192
+ }), globalOptions.json));
193
+ });
194
+ program
195
+ .command("mv")
196
+ .argument("<from>")
197
+ .argument("<to>")
198
+ .action((from, to) => {
199
+ const rootDir = findProjectRoot(cwd);
200
+ output.push(writeOutput("mv", runMove({ ...globalOptions, cwd: rootDir, from, to }), globalOptions.json));
201
+ });
202
+ try {
203
+ await program.parseAsync(argv, { from: "user" });
204
+ }
205
+ catch (error) {
206
+ if (error instanceof CliError) {
207
+ return {
208
+ exitCode: error.exitCode,
209
+ stdout: error.message
210
+ };
211
+ }
212
+ throw error;
213
+ }
214
+ return {
215
+ exitCode,
216
+ stdout: output.join("\n")
217
+ };
218
+ }
219
+ function stringifyOutput(value) {
220
+ return typeof value === "string" ? value : JSON.stringify(value, null, 2);
221
+ }
222
+ function writeOutput(schemaName, value, expectJson = false) {
223
+ if (expectJson) {
224
+ return stringifyValidatedOutput(schemaName, value);
225
+ }
226
+ return stringifyOutput(value);
227
+ }
228
+ function parseInteger(input) {
229
+ const value = Number.parseInt(input, 10);
230
+ if (Number.isNaN(value) || value <= 0) {
231
+ throw new CliError(`非法整数: ${input}`);
232
+ }
233
+ return value;
234
+ }
235
+ function readPackageVersion() {
236
+ const packageRoot = packageRootFromImport(import.meta.url);
237
+ const packageJson = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
238
+ return packageJson.version;
239
+ }
240
+ function parseGlobalOptions(argv) {
241
+ const options = {};
242
+ for (let index = 0; index < argv.length; index += 1) {
243
+ const token = argv[index];
244
+ if (token === "--json") {
245
+ options.json = true;
246
+ }
247
+ else if (token === "--cursor" && argv[index + 1]) {
248
+ options.cursor = argv[index + 1];
249
+ index += 1;
250
+ }
251
+ else if (token === "--budget" && argv[index + 1]) {
252
+ options.budget = parseInteger(argv[index + 1]);
253
+ index += 1;
254
+ }
255
+ else if (token === "--limit" && argv[index + 1]) {
256
+ options.limit = parseInteger(argv[index + 1]);
257
+ index += 1;
258
+ }
259
+ }
260
+ return options;
261
+ }
@@ -0,0 +1,78 @@
1
+ import { loadWorkspace } from "../lib/workspace.js";
2
+ import { matchesCodePathPattern } from "../lib/search.js";
3
+ import { CliError } from "../lib/errors.js";
4
+ import { formatPaginationSummary } from "../lib/format.js";
5
+ import { paginate, paginationMetadata } from "../lib/pagination.js";
6
+ import { normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
7
+ import { estimateTokens } from "../lib/markdown.js";
8
+ export function runContext(options) {
9
+ if (options.files.length === 0) {
10
+ throw new CliError("context 需要至少一个 --files 输入。");
11
+ }
12
+ const workspace = loadWorkspace(options.cwd);
13
+ const normalizedFiles = options.files.map((file) => {
14
+ const normalized = normalizeRepoRelativePath(file);
15
+ // 允许尚不存在的路径:"我要新建/删除这个文件,该先读哪些文档"是合法问法;
16
+ // resolveInsideRoot 仍负责拦截越界与 symlink 逃逸。
17
+ const absolutePath = resolveInsideRoot(workspace.rootDir, normalized, { allowMissing: true });
18
+ return {
19
+ normalized,
20
+ absolutePath
21
+ };
22
+ });
23
+ const impacted = workspace.documents.filter((document) => normalizedFiles.some((file) => (document.frontmatter.code?.paths ?? []).some((pattern) => matchesCodePathPattern(pattern, file.normalized))));
24
+ const prerequisites = collectRequires(workspace, impacted);
25
+ const rows = [
26
+ ...impacted.map((document) => ({ role: "impacted", document })),
27
+ ...prerequisites.map((document) => ({ role: "requires", document }))
28
+ ];
29
+ const result = paginate({
30
+ items: rows,
31
+ estimate: (row) => estimateTokens(JSON.stringify({ role: row.role, ...toPayload(row.document) })),
32
+ options
33
+ });
34
+ if (options.json) {
35
+ return {
36
+ impacted: result.items.filter((row) => row.role === "impacted").map((row) => toPayload(row.document)),
37
+ prerequisites: result.items.filter((row) => row.role === "requires").map((row) => toPayload(row.document)),
38
+ pagination: paginationMetadata(result)
39
+ };
40
+ }
41
+ const lines = [`${impacted.length} documents impacted, ${prerequisites.length} recommended prerequisites:`, ""];
42
+ for (const row of result.items) {
43
+ const prefix = row.role === "requires" ? " requires ->" : " ";
44
+ const document = row.document;
45
+ lines.push(`${prefix} llmdoc/${document.llmdocPath} [${document.frontmatter.kind}]`);
46
+ lines.push(` ${document.frontmatter.description}`);
47
+ }
48
+ lines.push("", ...formatPaginationSummary(result));
49
+ return lines.join("\n");
50
+ }
51
+ function collectRequires(workspace, impacted) {
52
+ const seen = new Set(impacted.map((document) => document.llmdocPath));
53
+ const queue = [...impacted];
54
+ const results = [];
55
+ while (queue.length > 0) {
56
+ const current = queue.shift();
57
+ for (const requirement of current.frontmatter.relations?.requires ?? []) {
58
+ if (seen.has(requirement)) {
59
+ continue;
60
+ }
61
+ const next = workspace.documentsByLlmdocPath.get(requirement);
62
+ if (!next) {
63
+ continue;
64
+ }
65
+ seen.add(requirement);
66
+ results.push(next);
67
+ queue.push(next);
68
+ }
69
+ }
70
+ return results.sort((left, right) => left.llmdocPath.localeCompare(right.llmdocPath));
71
+ }
72
+ function toPayload(document) {
73
+ return {
74
+ path: `llmdoc/${document.llmdocPath}`,
75
+ kind: document.frontmatter.kind,
76
+ description: document.frontmatter.description
77
+ };
78
+ }
@@ -0,0 +1,78 @@
1
+ import { CliError } from "../lib/errors.js";
2
+ import { analyzeDelta, parseScope } from "../lib/state.js";
3
+ import { loadWorkspace } from "../lib/workspace.js";
4
+ import { formatPaginationSummary } from "../lib/format.js";
5
+ import { paginate, paginationMetadata } from "../lib/pagination.js";
6
+ import { estimateTokens } from "../lib/markdown.js";
7
+ export function runDelta(options) {
8
+ const workspace = loadWorkspace(options.cwd);
9
+ let scope;
10
+ try {
11
+ scope = parseScope(options.scope, workspace);
12
+ }
13
+ catch (error) {
14
+ throw new CliError(error.message);
15
+ }
16
+ const delta = analyzeDelta(workspace, scope);
17
+ const rows = [
18
+ ...delta.impacts.map((impact) => ({ type: "impacted", impact })),
19
+ ...delta.needsReview.map((document) => ({ type: "needs-review", impact: { document, changedCommittedPaths: [], dirtyPaths: [], needsReviewBecauseOf: [] } }))
20
+ ];
21
+ const paginated = paginate({
22
+ items: rows,
23
+ estimate: (row) => estimateTokens(JSON.stringify({
24
+ type: row.type,
25
+ path: `llmdoc/${row.impact.document.llmdocPath}`,
26
+ changedCommittedPaths: row.impact.changedCommittedPaths,
27
+ dirtyPaths: row.impact.dirtyPaths
28
+ })),
29
+ options
30
+ });
31
+ if (options.json) {
32
+ return {
33
+ suggestedMode: delta.suggestedMode,
34
+ reasons: delta.reasons,
35
+ degradedReason: delta.git.degradedReason,
36
+ impacted: paginated.items
37
+ .filter((row) => row.type === "impacted")
38
+ .map((row) => ({
39
+ path: `llmdoc/${row.impact.document.llmdocPath}`,
40
+ changedCommittedPaths: row.impact.changedCommittedPaths,
41
+ dirtyPaths: row.impact.dirtyPaths
42
+ })),
43
+ needsReview: paginated.items
44
+ .filter((row) => row.type === "needs-review")
45
+ .map((row) => `llmdoc/${row.impact.document.llmdocPath}`),
46
+ unmapped: {
47
+ committed: delta.unmappedCommittedPaths,
48
+ dirty: delta.unmappedDirtyPaths
49
+ },
50
+ pagination: paginationMetadata(paginated)
51
+ };
52
+ }
53
+ const lines = [`mode: ${delta.suggestedMode}`, `impacted: ${delta.impacts.length}, needs-review: ${delta.needsReview.length}`, ""];
54
+ for (const row of paginated.items) {
55
+ const prefix = row.type === "needs-review" ? "needs-review" : "impacted";
56
+ lines.push(`${prefix}: llmdoc/${row.impact.document.llmdocPath}`);
57
+ if (row.impact.changedCommittedPaths.length > 0) {
58
+ lines.push(` committed: ${row.impact.changedCommittedPaths.join(", ")}`);
59
+ }
60
+ if (row.impact.dirtyPaths.length > 0) {
61
+ lines.push(` dirty: ${row.impact.dirtyPaths.join(", ")}`);
62
+ }
63
+ }
64
+ if (delta.unmappedCommittedPaths.length > 0 || delta.unmappedDirtyPaths.length > 0) {
65
+ lines.push("");
66
+ if (delta.unmappedCommittedPaths.length > 0) {
67
+ lines.push(`unmapped committed: ${delta.unmappedCommittedPaths.join(", ")}`);
68
+ }
69
+ if (delta.unmappedDirtyPaths.length > 0) {
70
+ lines.push(`unmapped dirty: ${delta.unmappedDirtyPaths.join(", ")}`);
71
+ }
72
+ }
73
+ if (delta.reasons.length > 0) {
74
+ lines.push("", `reasons: ${delta.reasons.join("; ")}`);
75
+ }
76
+ lines.push("", ...formatPaginationSummary(paginated));
77
+ return lines.join("\n");
78
+ }
@@ -0,0 +1,38 @@
1
+ import { CliError } from "../lib/errors.js";
2
+ import { updateMetaRevisions, writeMeta } from "../lib/state.js";
3
+ import { loadWorkspace } from "../lib/workspace.js";
4
+ export function runFingerprint(options) {
5
+ const workspace = loadWorkspace(options.cwd);
6
+ const targetPaths = options.update?.map((value) => (value.startsWith("llmdoc/") ? value.slice("llmdoc/".length) : value)) ?? [];
7
+ if (options.all && targetPaths.length > 0) {
8
+ throw new CliError("fingerprint 不能同时使用 --all 与 --update。");
9
+ }
10
+ if (!options.all && targetPaths.length === 0) {
11
+ throw new CliError("fingerprint 需要 --all 或 --update <path...>。");
12
+ }
13
+ for (const docPath of targetPaths) {
14
+ if (!workspace.documentsByLlmdocPath.has(docPath)) {
15
+ throw new CliError(`文档不存在: ${docPath}`);
16
+ }
17
+ }
18
+ try {
19
+ const result = updateMetaRevisions({
20
+ workspace,
21
+ llmdocPaths: targetPaths,
22
+ updateAll: Boolean(options.all)
23
+ });
24
+ writeMeta(workspace.metaPath, result.meta);
25
+ if (options.json) {
26
+ return {
27
+ status: "success",
28
+ updateAll: Boolean(options.all),
29
+ updated: result.updatedPaths,
30
+ baselineRevision: result.meta.baseline.revision
31
+ };
32
+ }
33
+ return `fingerprint: updated ${result.updatedPaths.length} document(s)${options.all ? ` and baseline -> ${result.meta.baseline.revision}` : ""}`;
34
+ }
35
+ catch (error) {
36
+ throw new CliError(error.message);
37
+ }
38
+ }
@@ -0,0 +1,84 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { analyzeDelta } from "../lib/state.js";
4
+ import { loadWorkspace } from "../lib/workspace.js";
5
+ export function runHook(options) {
6
+ try {
7
+ const hasLlmdoc = fs.existsSync(path.join(options.cwd, "llmdoc"));
8
+ switch (options.mode) {
9
+ case "session-start":
10
+ // 未启用 llmdoc 的项目保持静默,不注入任何内容。
11
+ return hasLlmdoc ? runSessionStart(options.cwd, options.stdin) : "";
12
+ case "stop":
13
+ return JSON.stringify(hasLlmdoc ? runStop(options.cwd) : { continue: true }, null, 2);
14
+ case "compact":
15
+ return JSON.stringify(hasLlmdoc ? runCompact() : { continue: true }, null, 2);
16
+ }
17
+ }
18
+ catch (error) {
19
+ if (options.mode === "session-start") {
20
+ return `llmdoc hook degraded: ${String(error.message || error).slice(0, 120)}`;
21
+ }
22
+ // 降级输出必须仍然满足 hook 输出 schema(continue + 可选 systemMessage),
23
+ // 否则外层 JSON 校验会让 hook 非零退出,击穿 fail-open。
24
+ return JSON.stringify({
25
+ continue: true,
26
+ systemMessage: `llmdoc hook degraded: ${String(error.message || error).slice(0, 200)}`
27
+ }, null, 2);
28
+ }
29
+ }
30
+ function runSessionStart(cwd, stdin) {
31
+ const source = inferSource(stdin);
32
+ try {
33
+ const workspace = loadWorkspace(cwd);
34
+ const delta = analyzeDelta(workspace);
35
+ const lifecycle = source === "compact" ? "compact re-entry" : "cold start";
36
+ const baseline = workspace.meta?.baseline.revision ? workspace.meta.baseline.revision.slice(0, 7) : "missing";
37
+ const stale = delta.git.baselineBehindHead === null ? "unknown" : `${delta.git.baselineBehindHead} behind`;
38
+ return `${lifecycle}; llmdoc yes; baseline ${baseline} (${stale}); impacted ${delta.impacts.length}; needs-review ${delta.needsReview.length}`;
39
+ }
40
+ catch {
41
+ return `${source === "compact" ? "compact re-entry" : "cold start"}; llmdoc unavailable`;
42
+ }
43
+ }
44
+ function runStop(cwd) {
45
+ try {
46
+ const workspace = loadWorkspace(cwd);
47
+ const delta = analyzeDelta(workspace);
48
+ const shouldUpdate = delta.impacts.length > 0 || delta.unmappedCommittedPaths.length > 0 || delta.unmappedDirtyPaths.length > 0;
49
+ return {
50
+ continue: true,
51
+ ...(shouldUpdate ? { systemMessage: `llmdoc: 可能需要 update。${delta.reasons.length > 0 ? ` 信号: ${delta.reasons.join("; ")}` : ""}` } : {})
52
+ };
53
+ }
54
+ catch (error) {
55
+ return {
56
+ continue: true,
57
+ systemMessage: `llmdoc hook degraded: ${error.message}`
58
+ };
59
+ }
60
+ }
61
+ function runCompact() {
62
+ return {
63
+ continue: true,
64
+ systemMessage: "在 compact summary 中保留 active goal、loaded docs、key conclusions、next step,并写入 LLMDOC_STATE。"
65
+ };
66
+ }
67
+ function inferSource(stdin) {
68
+ const text = stdin.trim();
69
+ if (!text) {
70
+ return "cold";
71
+ }
72
+ try {
73
+ const parsed = JSON.parse(text);
74
+ if (parsed.source === "compact") {
75
+ return "compact";
76
+ }
77
+ }
78
+ catch {
79
+ if (/compact/i.test(text)) {
80
+ return "compact";
81
+ }
82
+ }
83
+ return "cold";
84
+ }
@@ -0,0 +1,53 @@
1
+ import { paginate } from "../lib/pagination.js";
2
+ import { assertDocumentKind } from "../lib/doc-shape.js";
3
+ import { loadWorkspace } from "../lib/workspace.js";
4
+ import { formatPaginationSummary } from "../lib/format.js";
5
+ import { paginationMetadata } from "../lib/pagination.js";
6
+ import { estimateTokens } from "../lib/markdown.js";
7
+ export function runIndex(options) {
8
+ const workspace = loadWorkspace(options.cwd);
9
+ const kind = options.kind ? assertDocumentKind(options.kind) : undefined;
10
+ const filtered = workspace.documents.filter((document) => {
11
+ if (options.topic && document.topic !== options.topic) {
12
+ return false;
13
+ }
14
+ if (kind && document.frontmatter.kind !== kind) {
15
+ return false;
16
+ }
17
+ return true;
18
+ });
19
+ const result = paginate({
20
+ items: filtered,
21
+ estimate: (document) => estimateTokens(JSON.stringify(toPayload(document))),
22
+ options
23
+ });
24
+ if (options.json) {
25
+ return {
26
+ documents: result.items.map(toPayload),
27
+ pagination: paginationMetadata(result)
28
+ };
29
+ }
30
+ const lines = [];
31
+ for (const document of result.items) {
32
+ lines.push(`llmdoc/${document.llmdocPath} [${document.frontmatter.kind}]`);
33
+ lines.push(` ${document.frontmatter.description}`);
34
+ if (document.frontmatter.relations?.requires?.length) {
35
+ lines.push(` requires: ${document.frontmatter.relations.requires.join(", ")}`);
36
+ }
37
+ if (document.frontmatter.code?.paths?.length) {
38
+ lines.push(` code.paths: ${document.frontmatter.code.paths.join(", ")}`);
39
+ }
40
+ lines.push("");
41
+ }
42
+ lines.push(...formatPaginationSummary(result));
43
+ return lines.join("\n");
44
+ }
45
+ function toPayload(document) {
46
+ return {
47
+ path: `llmdoc/${document.llmdocPath}`,
48
+ kind: document.frontmatter.kind,
49
+ description: document.frontmatter.description,
50
+ relations: document.frontmatter.relations ?? {},
51
+ code: document.frontmatter.code ?? {}
52
+ };
53
+ }