@tokenroll/llmdoc 3.5.3 → 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.
Files changed (48) hide show
  1. package/assets/viewer-app.js +11 -11
  2. package/assets/viewer-detail.js +4 -4
  3. package/assets/viewer-graph.js +3 -3
  4. package/assets/viewer.html +19 -19
  5. package/dist/cli.js +147 -71
  6. package/dist/commands/adopt.js +10 -6
  7. package/dist/commands/commit.js +232 -80
  8. package/dist/commands/context.js +85 -45
  9. package/dist/commands/dream.js +608 -0
  10. package/dist/commands/eval.js +379 -0
  11. package/dist/commands/fingerprint.js +9 -3
  12. package/dist/commands/hook.js +135 -28
  13. package/dist/commands/index.js +52 -7
  14. package/dist/commands/init-state.js +5 -5
  15. package/dist/commands/mv.js +33 -12
  16. package/dist/commands/new.js +12 -5
  17. package/dist/commands/prune.js +14 -3
  18. package/dist/commands/search.js +67 -4
  19. package/dist/commands/serve.js +1 -1
  20. package/dist/commands/show.js +40 -6
  21. package/dist/commands/status.js +46 -18
  22. package/dist/commands/tree.js +94 -6
  23. package/dist/commands/upgrade.js +15 -15
  24. package/dist/lib/config.js +502 -0
  25. package/dist/lib/constants.js +23 -0
  26. package/dist/lib/doc-shape.js +5 -5
  27. package/dist/lib/frontmatter.js +47 -0
  28. package/dist/lib/fs.js +8 -8
  29. package/dist/lib/git.js +147 -42
  30. package/dist/lib/markdown.js +8 -7
  31. package/dist/lib/output-schema.js +3 -3
  32. package/dist/lib/package-root.js +1 -1
  33. package/dist/lib/pagination.js +2 -2
  34. package/dist/lib/rewrite.js +9 -3
  35. package/dist/lib/routing.js +152 -0
  36. package/dist/lib/schema.js +16 -0
  37. package/dist/lib/search.js +35 -16
  38. package/dist/lib/source-id.js +49 -0
  39. package/dist/lib/sources.js +760 -0
  40. package/dist/lib/state.js +74 -25
  41. package/dist/lib/telemetry.js +726 -0
  42. package/dist/lib/viewer-http.js +2 -2
  43. package/dist/lib/workspace.js +187 -43
  44. package/package.json +1 -1
  45. package/schemas/config.schema.json +116 -0
  46. package/schemas/meta.schema.json +5 -1
  47. package/schemas/output.schema.json +442 -0
  48. package/schemas/probes.schema.json +90 -0
@@ -0,0 +1,379 @@
1
+ import fs from "node:fs";
2
+ import { LLMDOC_PROBES_FILENAME } from "../lib/constants.js";
3
+ import { CliError } from "../lib/errors.js";
4
+ import { normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
5
+ import { resolveContextFileInput, resolveContextFiles } from "../lib/routing.js";
6
+ import { validateProbesConfig } from "../lib/schema.js";
7
+ import { searchDocuments } from "../lib/search.js";
8
+ import { formatDocumentPath, isSourceRef, parseSourceDocId } from "../lib/source-id.js";
9
+ import { loadWorkspace } from "../lib/workspace.js";
10
+ export function runEval(options) {
11
+ const workspace = loadWorkspace(options.cwd);
12
+ const relativeFile = options.file ? normalizeRepoRelativePath(options.file) : LLMDOC_PROBES_FILENAME;
13
+ let safeFilePath;
14
+ try {
15
+ safeFilePath = resolveInsideRoot(workspace.rootDir, relativeFile, { allowMissing: true });
16
+ }
17
+ catch (error) {
18
+ throw new CliError(`Invalid probes file path: ${error.message}`);
19
+ }
20
+ if (!fs.existsSync(safeFilePath)) {
21
+ if (options.file) {
22
+ throw new CliError(`Probes file does not exist: ${relativeFile}`);
23
+ }
24
+ const payload = {
25
+ status: "no_probes",
26
+ ok: true,
27
+ file: relativeFile,
28
+ total: 0,
29
+ passed: 0,
30
+ failed: 0,
31
+ results: []
32
+ };
33
+ return {
34
+ exitCode: 0,
35
+ output: options.json
36
+ ? payload
37
+ : `eval: no probes file found (${relativeFile}). Add optional declarative concept/file/negative probes to enable automated Context Floor regression checks.`
38
+ };
39
+ }
40
+ let parsed;
41
+ try {
42
+ parsed = JSON.parse(fs.readFileSync(safeFilePath, "utf8"));
43
+ }
44
+ catch (error) {
45
+ throw new CliError(`Failed to parse ${relativeFile}: ${error.message}`);
46
+ }
47
+ const schemaErrors = validateProbesConfig(parsed);
48
+ if (schemaErrors.length > 0) {
49
+ throw new CliError(`Invalid probes file ${relativeFile}: ${schemaErrors.join("; ")}`);
50
+ }
51
+ const probes = parsed;
52
+ const results = [];
53
+ for (const probe of probes.concept ?? []) {
54
+ results.push(evaluateConceptProbe(workspace, probe));
55
+ }
56
+ for (const probe of probes.file ?? []) {
57
+ results.push(evaluateFileProbe(workspace, probe));
58
+ }
59
+ for (const probe of probes.negative ?? []) {
60
+ results.push(evaluateNegativeProbe(workspace, probe));
61
+ }
62
+ if (results.length === 0) {
63
+ const payload = {
64
+ status: "no_probes",
65
+ ok: true,
66
+ file: relativeFile,
67
+ total: 0,
68
+ passed: 0,
69
+ failed: 0,
70
+ results: []
71
+ };
72
+ return {
73
+ exitCode: 0,
74
+ output: options.json
75
+ ? payload
76
+ : `eval: no probes defined in ${relativeFile}. Add concept, file, or negative probes before relying on automated routing checks.`
77
+ };
78
+ }
79
+ const passed = results.filter((item) => item.passed).length;
80
+ const failed = results.length - passed;
81
+ const ok = failed === 0;
82
+ const payload = {
83
+ status: ok ? "pass" : "fail",
84
+ ok,
85
+ file: relativeFile,
86
+ total: results.length,
87
+ passed,
88
+ failed,
89
+ results
90
+ };
91
+ if (options.json) {
92
+ return {
93
+ exitCode: ok ? 0 : 1,
94
+ output: payload
95
+ };
96
+ }
97
+ const lines = [`eval: ${ok ? "pass" : "fail"} (${passed}/${results.length} probes passed; ${relativeFile})`];
98
+ for (const item of results) {
99
+ const marker = item.passed ? "PASS" : "FAIL";
100
+ lines.push(` [${marker}] (${item.kind}) ${item.target} -> expected ${item.expected}; actual ${item.actual}`);
101
+ if (item.reason) {
102
+ lines.push(` reason: ${item.reason}`);
103
+ }
104
+ }
105
+ return {
106
+ exitCode: ok ? 0 : 1,
107
+ output: lines.join("\n")
108
+ };
109
+ }
110
+ function evaluateConceptProbe(workspace, probe) {
111
+ const expectedId = normalizeExpectedDocId(probe.expectOwner);
112
+ const maxRank = probe.maxRank ?? 1;
113
+ const allowFallback = probe.allowFallback ?? false;
114
+ const expectsExternal = isSourceRef(expectedId);
115
+ if (expectsExternal) {
116
+ const sourceCheck = checkExternalTargetAvailability(workspace, expectedId);
117
+ if (!sourceCheck.ok) {
118
+ return {
119
+ kind: "concept",
120
+ target: `"${probe.query}"`,
121
+ expected: `${formatExpectedLabel(expectedId)} (rank <= ${maxRank})`,
122
+ passed: false,
123
+ actual: sourceCheck.actual,
124
+ reason: sourceCheck.reason
125
+ };
126
+ }
127
+ }
128
+ // Always run cache-free against current in-memory documents; local concept probes exclude ambient external snapshots.
129
+ const search = searchDocuments(workspace, probe.query, {
130
+ includeSources: expectsExternal,
131
+ useCache: false
132
+ });
133
+ const rankIndex = search.results.findIndex((entry) => entry.document.llmdocPath === expectedId);
134
+ const rank = rankIndex >= 0 ? rankIndex + 1 : null;
135
+ const topActual = search.results.length === 0
136
+ ? "no results"
137
+ : `${search.results
138
+ .slice(0, 3)
139
+ .map((entry, idx) => `#${idx + 1} ${formatDocLabel(entry.document)}`)
140
+ .join(", ")} (${search.mode})`;
141
+ if (rank === null) {
142
+ return {
143
+ kind: "concept",
144
+ target: `"${probe.query}"`,
145
+ expected: `${formatExpectedLabel(expectedId)} (rank <= ${maxRank})`,
146
+ passed: false,
147
+ actual: topActual,
148
+ reason: "expected owner did not appear in search results"
149
+ };
150
+ }
151
+ if (!allowFallback && search.mode === "cjk-bigram-fallback") {
152
+ return {
153
+ kind: "concept",
154
+ target: `"${probe.query}"`,
155
+ expected: `${formatExpectedLabel(expectedId)} (rank <= ${maxRank}, lexical)`,
156
+ passed: false,
157
+ actual: `#${rank} ${formatExpectedLabel(expectedId)} (${search.mode})`,
158
+ reason: "search degraded to cjk-bigram-fallback"
159
+ };
160
+ }
161
+ if (rank > maxRank) {
162
+ return {
163
+ kind: "concept",
164
+ target: `"${probe.query}"`,
165
+ expected: `${formatExpectedLabel(expectedId)} (rank <= ${maxRank})`,
166
+ passed: false,
167
+ actual: `#${rank} (${topActual})`,
168
+ reason: `owner ranked #${rank}, exceeding maxRank ${maxRank}`
169
+ };
170
+ }
171
+ return {
172
+ kind: "concept",
173
+ target: `"${probe.query}"`,
174
+ expected: `${formatExpectedLabel(expectedId)} (rank <= ${maxRank})`,
175
+ passed: true,
176
+ actual: `#${rank} ${formatExpectedLabel(expectedId)} (${search.mode})`
177
+ };
178
+ }
179
+ function evaluateFileProbe(workspace, probe) {
180
+ let resolvedFile;
181
+ try {
182
+ resolvedFile = resolveContextFileInput(workspace.rootDir, probe.path);
183
+ }
184
+ catch (error) {
185
+ return {
186
+ kind: "file",
187
+ target: probe.path,
188
+ expected: probe.expectOwner,
189
+ passed: false,
190
+ actual: "invalid path",
191
+ reason: error.message
192
+ };
193
+ }
194
+ const expectedId = normalizeExpectedDocId(probe.expectOwner);
195
+ const requiredExpectations = (probe.expectRequires ?? []).map(normalizeExpectedDocId);
196
+ const expectsExternalOwner = isSourceRef(expectedId);
197
+ const needsExternal = expectsExternalOwner || requiredExpectations.some(isSourceRef);
198
+ if (expectsExternalOwner) {
199
+ const sourceCheck = checkExternalTargetAvailability(workspace, expectedId);
200
+ if (!sourceCheck.ok) {
201
+ return {
202
+ kind: "file",
203
+ target: resolvedFile.normalized,
204
+ expected: formatExpectedLabel(expectedId),
205
+ passed: false,
206
+ actual: sourceCheck.actual,
207
+ reason: sourceCheck.reason
208
+ };
209
+ }
210
+ }
211
+ const context = resolveContextFiles(workspace, [resolvedFile], { includeSources: needsExternal });
212
+ const matchedOwners = expectsExternalOwner ? context.sourceImpacted : context.localImpacted;
213
+ const ownerIds = new Set(matchedOwners.map((document) => document.llmdocPath));
214
+ const allMatchedSummary = context.impacted.length === 0 ? "unmapped" : context.impacted.map(formatDocLabel).join(", ");
215
+ if (!ownerIds.has(expectedId)) {
216
+ return {
217
+ kind: "file",
218
+ target: resolvedFile.normalized,
219
+ expected: formatExpectedLabel(expectedId),
220
+ passed: false,
221
+ actual: allMatchedSummary,
222
+ reason: expectsExternalOwner
223
+ ? "expected external owner did not match file in context"
224
+ : "expected local owner did not match file via code.paths"
225
+ };
226
+ }
227
+ if (requiredExpectations.length > 0) {
228
+ const resolvedPrereqIds = new Set(context.prerequisites.map((document) => document.llmdocPath));
229
+ const impactedIds = new Set(context.impacted.map((document) => document.llmdocPath));
230
+ const missingDetails = [];
231
+ const missingLabels = [];
232
+ for (const req of requiredExpectations) {
233
+ if (resolvedPrereqIds.has(req)) {
234
+ continue;
235
+ }
236
+ const reqLabel = formatExpectedLabel(req);
237
+ missingLabels.push(reqLabel);
238
+ if (impactedIds.has(req)) {
239
+ missingDetails.push(`${reqLabel} matched directly as an owner rather than a prerequisite`);
240
+ continue;
241
+ }
242
+ const externalMissing = context.missingPrerequisites.find((entry) => entry.path === reqLabel);
243
+ if (externalMissing) {
244
+ missingDetails.push(`${reqLabel} (${externalMissing.reason})`);
245
+ continue;
246
+ }
247
+ const localMissing = context.missingLocalPrerequisites.find((entry) => entry.path === reqLabel);
248
+ if (localMissing) {
249
+ missingDetails.push(`${reqLabel} (${localMissing.reason})`);
250
+ continue;
251
+ }
252
+ missingDetails.push(`${reqLabel} was not returned in resolved prerequisites`);
253
+ }
254
+ if (missingLabels.length > 0) {
255
+ return {
256
+ kind: "file",
257
+ target: resolvedFile.normalized,
258
+ expected: `${formatExpectedLabel(expectedId)} + requires [${requiredExpectations.map(formatExpectedLabel).join(", ")}]`,
259
+ passed: false,
260
+ actual: `${allMatchedSummary} (missing requires: ${missingLabels.join(", ")})`,
261
+ reason: missingDetails.join("; ")
262
+ };
263
+ }
264
+ }
265
+ return {
266
+ kind: "file",
267
+ target: resolvedFile.normalized,
268
+ expected: requiredExpectations.length > 0
269
+ ? `${formatExpectedLabel(expectedId)} + requires [${requiredExpectations.map(formatExpectedLabel).join(", ")}]`
270
+ : formatExpectedLabel(expectedId),
271
+ passed: true,
272
+ actual: allMatchedSummary
273
+ };
274
+ }
275
+ function evaluateNegativeProbe(workspace, probe) {
276
+ let resolvedFile;
277
+ try {
278
+ resolvedFile = resolveContextFileInput(workspace.rootDir, probe.path);
279
+ }
280
+ catch (error) {
281
+ return {
282
+ kind: "negative",
283
+ target: probe.path,
284
+ expected: `not ${probe.forbidOwner}`,
285
+ passed: false,
286
+ actual: "invalid path",
287
+ reason: error.message
288
+ };
289
+ }
290
+ const forbidId = normalizeExpectedDocId(probe.forbidOwner);
291
+ const forbidsExternal = isSourceRef(forbidId);
292
+ if (forbidsExternal) {
293
+ const sourceCheck = checkExternalTargetAvailability(workspace, forbidId);
294
+ if (!sourceCheck.ok) {
295
+ return {
296
+ kind: "negative",
297
+ target: resolvedFile.normalized,
298
+ expected: `not ${formatExpectedLabel(forbidId)}`,
299
+ passed: false,
300
+ actual: sourceCheck.actual,
301
+ reason: sourceCheck.reason
302
+ };
303
+ }
304
+ }
305
+ else if (!workspace.documentsByLlmdocPath.has(forbidId)) {
306
+ return {
307
+ kind: "negative",
308
+ target: resolvedFile.normalized,
309
+ expected: `not ${formatExpectedLabel(forbidId)}`,
310
+ passed: false,
311
+ actual: "missing document",
312
+ reason: `forbidOwner does not exist: ${formatExpectedLabel(forbidId)}`
313
+ };
314
+ }
315
+ const context = resolveContextFiles(workspace, [resolvedFile], { includeSources: forbidsExternal });
316
+ const candidatePool = forbidsExternal ? context.sourceImpacted : context.localImpacted;
317
+ if (candidatePool.some((doc) => doc.llmdocPath === forbidId)) {
318
+ return {
319
+ kind: "negative",
320
+ target: resolvedFile.normalized,
321
+ expected: `not ${formatExpectedLabel(forbidId)}`,
322
+ passed: false,
323
+ actual: `matched ${formatExpectedLabel(forbidId)}`,
324
+ reason: "unrelated file spuriously matched broad code.paths glob"
325
+ };
326
+ }
327
+ return {
328
+ kind: "negative",
329
+ target: resolvedFile.normalized,
330
+ expected: `not ${formatExpectedLabel(forbidId)}`,
331
+ passed: true,
332
+ actual: "not matched"
333
+ };
334
+ }
335
+ function checkExternalTargetAvailability(workspace, externalId) {
336
+ let parsed;
337
+ try {
338
+ parsed = parseSourceDocId(externalId);
339
+ }
340
+ catch (error) {
341
+ return { ok: false, actual: "invalid external reference", reason: error.message };
342
+ }
343
+ const source = workspace.sourcesByName.get(parsed.alias);
344
+ if (!source) {
345
+ return {
346
+ ok: false,
347
+ actual: "unconfigured source",
348
+ reason: `external source @${parsed.alias} is not configured`
349
+ };
350
+ }
351
+ if (source.status !== "ready") {
352
+ return {
353
+ ok: false,
354
+ actual: "source unavailable",
355
+ reason: `external source @${parsed.alias} is unavailable: ${source.error ?? "no local snapshot"}${source.remedy ? ` (${source.remedy})` : ""}`
356
+ };
357
+ }
358
+ if (!workspace.sourceDocumentsById.has(parsed.canonicalId)) {
359
+ return {
360
+ ok: false,
361
+ actual: "missing external document",
362
+ reason: `document not found in @${parsed.alias}${source.revision ? ` (${source.revision.slice(0, 7)})` : ""}: ${parsed.canonicalId}`
363
+ };
364
+ }
365
+ return { ok: true };
366
+ }
367
+ function normalizeExpectedDocId(raw) {
368
+ const trimmed = raw.trim().replaceAll("\\", "/");
369
+ if (isSourceRef(trimmed)) {
370
+ return trimmed;
371
+ }
372
+ return trimmed.startsWith("llmdoc/") ? trimmed.slice("llmdoc/".length) : trimmed;
373
+ }
374
+ function formatExpectedLabel(id) {
375
+ return isSourceRef(id) ? id : `llmdoc/${id}`;
376
+ }
377
+ function formatDocLabel(document) {
378
+ return formatDocumentPath(document);
379
+ }
@@ -1,18 +1,24 @@
1
1
  import { CliError } from "../lib/errors.js";
2
+ import { isSourceRef } from "../lib/source-id.js";
2
3
  import { updateMetaRevisions, writeMeta } from "../lib/state.js";
3
4
  import { loadWorkspace } from "../lib/workspace.js";
4
5
  export function runFingerprint(options) {
6
+ for (const value of options.update ?? []) {
7
+ if (isSourceRef(value)) {
8
+ throw new CliError(`External source documents (@...) are read-only and cannot be fingerprinted: ${value}`);
9
+ }
10
+ }
5
11
  const workspace = loadWorkspace(options.cwd);
6
12
  const targetPaths = options.update?.map((value) => (value.startsWith("llmdoc/") ? value.slice("llmdoc/".length) : value)) ?? [];
7
13
  if (options.all && targetPaths.length > 0) {
8
- throw new CliError("fingerprint 不能同时使用 --all 与 --update。");
14
+ throw new CliError("fingerprint cannot use --all and --update together.");
9
15
  }
10
16
  if (!options.all && targetPaths.length === 0) {
11
- throw new CliError("fingerprint 需要 --all 或 --update <path...>。");
17
+ throw new CliError("fingerprint requires --all or --update <path...>.");
12
18
  }
13
19
  for (const docPath of targetPaths) {
14
20
  if (!workspace.documentsByLlmdocPath.has(docPath)) {
15
- throw new CliError(`文档不存在: ${docPath}`);
21
+ throw new CliError(`Document does not exist: ${docPath}`);
16
22
  }
17
23
  }
18
24
  try {
@@ -2,6 +2,11 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { analyzeDelta } from "../lib/state.js";
4
4
  import { loadWorkspace } from "../lib/workspace.js";
5
+ import { computeLocalPreloadBudget, formatCompactPreloadIndex, formatStartupPreloadDocuments, loadLlmdocConfig } from "../lib/config.js";
6
+ import { triggerBackgroundRefreshIfNeeded } from "../lib/sources.js";
7
+ import { recordTelemetryEvent } from "../lib/telemetry.js";
8
+ // Minimal SessionStart guidance; the complete protocol remains in the llmdoc skill.
9
+ const SESSION_START_GUIDANCE = "Operating guidance: Before broad exploration, planning, or documentation work, load the llmdoc skill and retrieve through the CLI instead of crawling the whole repository; align with the user before non-trivial plans or edits; proactively delegate to subagents (investigator for current-state and unfamiliar subsystems, recorder exclusively for stable llmdoc/ writes, reflector for workflow lessons); when a task produces durable knowledge, finish with /llmdoc:update.";
5
10
  export function runHook(options) {
6
11
  try {
7
12
  const hasLlmdoc = fs.existsSync(path.join(options.cwd, "llmdoc"));
@@ -32,6 +37,14 @@ function runSessionStart(cwd, stdin) {
32
37
  const lifecycle = source === "compact" ? "compact re-entry" : "cold start";
33
38
  try {
34
39
  const workspace = loadWorkspace(cwd);
40
+ if (source === "cold" && workspace.sources.length > 0) {
41
+ try {
42
+ triggerBackgroundRefreshIfNeeded(workspace);
43
+ }
44
+ catch {
45
+ // Background refresh must stay fail-open and never degrade SessionStart.
46
+ }
47
+ }
35
48
  const delta = analyzeDelta(workspace);
36
49
  const signal = summarizeHookDelta(delta);
37
50
  const pendingLessonCandidates = countPendingLessonCandidates(cwd);
@@ -39,30 +52,124 @@ function runSessionStart(cwd, stdin) {
39
52
  // fingerprint/commit 正常收尾会让 HEAD 前进到仅修改 llmdoc/meta.json 的 follow-up commit。
40
53
  // 没有可执行影响时不展示 raw baseline 落后数,避免把知识面自身更新误报成需要再次 update。
41
54
  if (!signal.shouldUpdate) {
42
- parts.push("文档无待处理影响");
55
+ parts.push("documents have no actionable impacts");
43
56
  if (pendingLessonCandidates > 0) {
44
- parts.push(`待处理反思候选 ${pendingLessonCandidates} 个`);
57
+ parts.push(`${pendingLessonCandidates} pending reflection candidate(s)`);
45
58
  }
46
- return parts.join("; ");
47
59
  }
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} 个`);
60
+ else {
61
+ const baseline = workspace.meta?.baseline.revision ? workspace.meta.baseline.revision.slice(0, 7) : "missing";
62
+ const freshness = delta.git.baselineBehindHead === null ? "distance unknown" : delta.git.baselineBehindHead === 0 ? "at HEAD" : `${delta.git.baselineBehindHead} commit(s) behind HEAD`;
63
+ parts.push(`baseline ${baseline}(${freshness})`);
64
+ const summary = [
65
+ signal.impactedCount > 0 ? `${signal.impactedCount} impacted document(s)` : null,
66
+ signal.needsReviewCount > 0 ? `${signal.needsReviewCount} document(s) need review` : null,
67
+ signal.unmappedCount > 0 ? `${signal.unmappedCount} unmapped code path(s)` : null
68
+ ]
69
+ .filter(Boolean)
70
+ .join(", ");
71
+ parts.push(`${summary} → inspect npx @tokenroll/llmdoc delta first`);
72
+ if (pendingLessonCandidates > 0) {
73
+ parts.push(`${pendingLessonCandidates} pending reflection candidate(s)`);
74
+ }
61
75
  }
62
- return parts.join("; ");
76
+ const context = [parts.join("; ")];
77
+ const startupConfig = workspace.llmdocConfig;
78
+ if (startupConfig.config?.startup?.remindSkill ?? true) {
79
+ context.push(SESSION_START_GUIDANCE);
80
+ }
81
+ appendStartupConfigIssues(context, startupConfig);
82
+ if (source === "cold") {
83
+ const localPreloadBudget = computeLocalPreloadBudget(startupConfig, workspace.documentsByLlmdocPath);
84
+ if (localPreloadBudget.exceedsBudget) {
85
+ context.push(`llmdoc startup.preload warning: local preload totals ~${localPreloadBudget.totalEstimatedTokens} tokens (soft budget ${localPreloadBudget.budgetTokens}). Consider keeping only the most frequently needed docs in startup.preload and leaving others on progressive description/tree disclosure.`);
86
+ }
87
+ }
88
+ const preloaded = source === "compact"
89
+ ? formatCompactPreloadIndex(startupConfig.preloadPaths)
90
+ : formatColdStartupPreload(workspace);
91
+ if (preloaded) {
92
+ context.push(preloaded);
93
+ }
94
+ return context.join("\n\n");
63
95
  }
64
96
  catch {
65
- return `llmdoc ${lifecycle}; 状态读取失败,检索不受影响`;
97
+ const context = [`llmdoc ${lifecycle}; status read failed, retrieval remains available`];
98
+ const startupConfig = loadLlmdocConfig(cwd);
99
+ if (startupConfig.config?.startup?.remindSkill ?? true) {
100
+ context.push(SESSION_START_GUIDANCE);
101
+ }
102
+ appendStartupConfigIssues(context, startupConfig);
103
+ return context.join("\n\n");
104
+ }
105
+ }
106
+ function formatColdStartupPreload(workspace) {
107
+ const resolved = [];
108
+ const skipped = [];
109
+ for (const entry of workspace.llmdocConfig.preloadEntries) {
110
+ if (entry.kind === "local") {
111
+ const doc = workspace.documentsByLlmdocPath.get(entry.normalized);
112
+ if (doc) {
113
+ resolved.push(doc);
114
+ }
115
+ continue;
116
+ }
117
+ const source = entry.sourceName ? workspace.sourcesByName.get(entry.sourceName) : undefined;
118
+ if (!source || source.status !== "ready") {
119
+ const detail = source?.error ?? "no local cache yet";
120
+ const remedy = source?.remedy ?? `run npx -y @tokenroll/llmdoc show ${entry.normalized} or npx -y @tokenroll/llmdoc status --refresh`;
121
+ skipped.push({
122
+ id: entry.normalized,
123
+ reason: `source @${entry.sourceName} is unavailable (${detail}; ${remedy})`
124
+ });
125
+ continue;
126
+ }
127
+ const doc = workspace.sourceDocumentsById.get(entry.normalized);
128
+ if (!doc) {
129
+ skipped.push({
130
+ id: entry.normalized,
131
+ reason: `document not found in @${entry.sourceName}${source.revision ? ` (${source.revision.slice(0, 7)})` : ""}`
132
+ });
133
+ continue;
134
+ }
135
+ resolved.push(doc);
136
+ }
137
+ const localDocs = resolved.filter((doc) => !doc.sourceName).map((doc) => doc.llmdocPath);
138
+ if (localDocs.length > 0) {
139
+ recordTelemetryEvent(workspace.rootDir, {
140
+ type: "preload",
141
+ docs: localDocs
142
+ });
143
+ }
144
+ return formatStartupPreloadDocuments(resolved, {
145
+ skipped,
146
+ sourcesByName: workspace.sourcesByName
147
+ });
148
+ }
149
+ function appendStartupConfigIssues(context, startupConfig) {
150
+ const errors = startupConfig.issues.filter((issue) => issue.severity === "error");
151
+ const warnings = startupConfig.issues.filter((issue) => issue.severity === "warning");
152
+ if (errors.length > 0) {
153
+ if (!startupConfig.config) {
154
+ const unsupported = errors.find((issue) => issue.code === "config.schema.unsupported");
155
+ context.push(unsupported
156
+ ? `${unsupported.message} Preload was skipped and the default skill reminder remains active.`
157
+ : "llmdoc.config.json could not be applied; preload was skipped and the default skill reminder remains active. Run npx @tokenroll/llmdoc validate for details.");
158
+ }
159
+ else if (startupConfig.hasLocalPreloadErrors) {
160
+ context.push("llmdoc.config.json has invalid startup.preload entries; preload was skipped while the valid remindSkill preference remained applied. Run npx @tokenroll/llmdoc validate for details.");
161
+ }
162
+ else {
163
+ context.push("llmdoc.config.json has invalid source configuration entries; affected sources were skipped while valid startup settings remained applied. Run npx @tokenroll/llmdoc validate for details.");
164
+ }
165
+ }
166
+ const duplicateWarnings = warnings.filter((issue) => issue.code === "config.startup.preload.duplicate");
167
+ if (duplicateWarnings.length > 0) {
168
+ context.push("llmdoc.config.json has warnings; normalized duplicate startup.preload entries were ignored. Run npx @tokenroll/llmdoc validate for details.");
169
+ }
170
+ const otherWarnings = warnings.filter((issue) => issue.code !== "config.startup.preload.duplicate");
171
+ if (otherWarnings.length > 0) {
172
+ context.push(`llmdoc.config.json reported ${otherWarnings.length} warning(s). Run npx @tokenroll/llmdoc validate for details.`);
66
173
  }
67
174
  }
68
175
  function runStop(cwd) {
@@ -75,23 +182,23 @@ function runStop(cwd) {
75
182
  return { continue: true };
76
183
  }
77
184
  const summary = [
78
- signal.impactedCount > 0 ? `${signal.impactedCount} 篇文档受代码变更影响` : null,
79
- signal.needsReviewCount > 0 ? `${signal.needsReviewCount} 篇文档需要复核` : null,
80
- signal.unmappedCount > 0 ? `${signal.unmappedCount} 个代码路径未映射到任何文档` : null,
81
- pendingLessonCandidates > 0 ? `${pendingLessonCandidates} 个反思候选待处理` : null
185
+ signal.impactedCount > 0 ? `${signal.impactedCount} document(s) impacted by code changes` : null,
186
+ signal.needsReviewCount > 0 ? `${signal.needsReviewCount} document(s) need review` : null,
187
+ signal.unmappedCount > 0 ? `${signal.unmappedCount} code path(s) are not mapped to any document` : null,
188
+ pendingLessonCandidates > 0 ? `${pendingLessonCandidates} reflection candidate(s) pending` : null
82
189
  ]
83
190
  .filter(Boolean)
84
191
  .join(", ");
85
- const reasons = delta.reasons.length > 0 ? `信号: ${delta.reasons.join("; ")}` : "";
192
+ const reasons = delta.reasons.length > 0 ? `Signals: ${delta.reasons.join("; ")}` : "";
86
193
  const updateCommand = pendingLessonCandidates > 0 ? "/llmdoc:update --reflection" : "/llmdoc:update";
87
194
  const guidance = pendingLessonCandidates > 0
88
195
  ? signal.shouldUpdate
89
- ? "workflow 会读取 pending 候选;代码影响面可先用 npx @tokenroll/llmdoc delta 查看"
90
- : "workflow 会读取 pending 候选"
91
- : "先用 npx @tokenroll/llmdoc delta 查看影响面";
196
+ ? "the workflow will read pending candidates; inspect code impact with npx @tokenroll/llmdoc delta first"
197
+ : "the workflow will read pending candidates"
198
+ : "inspect impact with npx @tokenroll/llmdoc delta first";
92
199
  return {
93
200
  continue: true,
94
- systemMessage: `llmdoc: ${summary},建议运行 ${updateCommand}(${guidance})。${reasons}`
201
+ systemMessage: `llmdoc: ${summary}. Consider running ${updateCommand} (${guidance}). ${reasons}`.trim()
95
202
  };
96
203
  }
97
204
  catch (error) {
@@ -115,7 +222,7 @@ function summarizeHookDelta(delta) {
115
222
  function runCompact() {
116
223
  return {
117
224
  continue: true,
118
- systemMessage: "即将 compact:请在 summary 中写入 LLMDOC_STATE(active goal、已读 llmdoc 文档、关键结论与不变量、用户决策、lesson_candidates、next step、open risks)。恢复后若该状态仍充分,直接继续,不要重放 tree/show。"
225
+ systemMessage: "Compaction is imminent. Preserve LLMDOC_STATE in the summary (active goal, llmdoc documents already read, key conclusions and invariants, user decisions, lesson_candidates, next step, open risks). After resuming, continue directly when that state is sufficient; do not replay tree/show."
119
226
  };
120
227
  }
121
228
  function countPendingLessonCandidates(cwd) {