@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,608 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { BORGES_MIN_DOC_TOKENS, BORGES_RATIO_WARNING_THRESHOLD, DEFAULT_DREAM_HOT_THRESHOLD, DEFAULT_DREAM_MIN_BLIND_SPOT_OCCURRENCES, DEFAULT_DREAM_MIN_UNMAPPED_PROBE_OCCURRENCES, DEFAULT_DREAM_STALE_DAYS, DEFAULT_DREAM_WINDOW_DAYS } from "../lib/constants.js";
4
+ import { computeLocalPreloadBudget } from "../lib/config.js";
5
+ import { CliError } from "../lib/errors.js";
6
+ import { parseYamlFrontmatter } from "../lib/frontmatter.js";
7
+ import { repoPath, resolveInsideRoot } from "../lib/fs.js";
8
+ import { isGitRepository, isShallowRepository, listGitTrackedFiles, readCommitTimestampMs } from "../lib/git.js";
9
+ import { estimateTokens, extractTitle } from "../lib/markdown.js";
10
+ import { getDocumentCodePaths } from "../lib/routing.js";
11
+ import { matchesCodePathPattern, searchDocuments } from "../lib/search.js";
12
+ import { computeGrowthState, isImplementationSurfacePath, loadIgnorePatterns } from "../lib/state.js";
13
+ import { getTelemetryPersistenceStatus, readRegularFileSafely, resolveSafeSubdirectory, summarizeTelemetry } from "../lib/telemetry.js";
14
+ import { loadWorkspace } from "../lib/workspace.js";
15
+ const DAY_MS = 24 * 60 * 60 * 1000;
16
+ const MAX_SOURCE_FILE_BYTES_FOR_FULL_READ = 512 * 1024;
17
+ const SAMPLE_SOURCE_BYTES_FOR_LARGE_FILE = 64 * 1024;
18
+ const BINARY_CHECK_BYTES = 8 * 1024;
19
+ const MAX_MATCHED_FILES_PER_DOC = 200;
20
+ const MAX_FALLBACK_WALK_FILES = 10_000;
21
+ const MAX_REFLECTION_FILE_BYTES = 256 * 1024;
22
+ export function runDream(options) {
23
+ const workspace = loadWorkspace(options.cwd);
24
+ assertDreamInputsHealthy(workspace);
25
+ const windowDays = options.windowDays ?? DEFAULT_DREAM_WINDOW_DAYS;
26
+ const staleDays = options.staleDays ?? DEFAULT_DREAM_STALE_DAYS;
27
+ const hotThreshold = options.hotThreshold ?? DEFAULT_DREAM_HOT_THRESHOLD;
28
+ const nowMs = options.nowMs ?? Date.now();
29
+ const telemetryStatus = getTelemetryPersistenceStatus(workspace.rootDir);
30
+ const telemetry = summarizeTelemetry(workspace.rootDir, { windowDays, nowMs });
31
+ const growth = computeGrowthState(workspace);
32
+ const preloadBudget = computeLocalPreloadBudget(workspace.llmdocConfig, workspace.documentsByLlmdocPath);
33
+ const hotStaleDocs = findHotStaleDocs(workspace, telemetry.byDocument, { staleDays, hotThreshold, nowMs });
34
+ const reflectionClusters = scanReflectionClusters(workspace.rootDir);
35
+ // Re-verify recurring historical blind spots (>= 2x) against current in-memory local documents
36
+ // so one-off typos never wake Harness cron and fixed queries clear immediately.
37
+ const searchBlindSpots = telemetry.searchBlindSpots
38
+ .filter((spot) => {
39
+ if (spot.occurrences < DEFAULT_DREAM_MIN_BLIND_SPOT_OCCURRENCES) {
40
+ return false;
41
+ }
42
+ const probe = searchDocuments(workspace, spot.query, {
43
+ includeSources: false,
44
+ useCache: false
45
+ });
46
+ return probe.results.length === 0 || probe.mode === "cjk-bigram-fallback";
47
+ })
48
+ .slice(0, 20);
49
+ const ignorePatterns = loadIgnorePatterns(workspace.rootDir);
50
+ const unmappedProbes = telemetry.unmappedProbes
51
+ .filter((entry) => {
52
+ if (entry.occurrences < DEFAULT_DREAM_MIN_UNMAPPED_PROBE_OCCURRENCES) {
53
+ return false;
54
+ }
55
+ if (!isImplementationSurfacePath(entry.filePath, ignorePatterns)) {
56
+ return false;
57
+ }
58
+ return !workspace.documents.some((document) => getDocumentCodePaths(document).some((pattern) => matchesCodePathPattern(pattern, entry.filePath)));
59
+ })
60
+ .slice(0, 20);
61
+ const preloadRecommendations = computePreloadRecommendations(workspace, preloadBudget, telemetry.byDocument, telemetry.eventCount, hotThreshold);
62
+ const borgesRiskDocs = findBorgesRiskDocs(workspace);
63
+ const reasons = [];
64
+ if (hotStaleDocs.length > 0) {
65
+ reasons.push(`${hotStaleDocs.length} hot document(s) have not been verified in >= ${staleDays} day(s)`);
66
+ }
67
+ if (reflectionClusters.length > 0) {
68
+ const pendingCount = reflectionClusters.reduce((sum, cluster) => sum + cluster.count, 0);
69
+ reasons.push(`${pendingCount} pending reflection candidate(s) across ${reflectionClusters.length} cluster(s)`);
70
+ }
71
+ if (searchBlindSpots.length > 0) {
72
+ reasons.push(`${searchBlindSpots.length} recurring search blind spot(s) (>= ${DEFAULT_DREAM_MIN_BLIND_SPOT_OCCURRENCES}x zero-hit or CJK bigram fallback)`);
73
+ }
74
+ if (unmappedProbes.length > 0) {
75
+ reasons.push(`${unmappedProbes.length} frequently probed unmapped file(s) (>= ${DEFAULT_DREAM_MIN_UNMAPPED_PROBE_OCCURRENCES}x)`);
76
+ }
77
+ if (preloadBudget.exceedsBudget) {
78
+ reasons.push(`local startup.preload totals ~${preloadBudget.totalEstimatedTokens} tokens (soft budget ${preloadBudget.budgetTokens})`);
79
+ }
80
+ if (borgesRiskDocs.length > 0) {
81
+ reasons.push(`${borgesRiskDocs.length} document(s) show high doc-to-source token ratio`);
82
+ }
83
+ if (growth.exceedsGate) {
84
+ reasons.push("document growth exceeds convergence gate");
85
+ }
86
+ const actionable = reasons.length > 0;
87
+ // In --check mode (for external Harness cron), exit 0 when quiet so the harness skips LLM cost,
88
+ // and exit 2 when actionable consolidation signals exist. Fatal local workspace/meta errors exit 1.
89
+ const exitCode = options.check && actionable ? 2 : 0;
90
+ const payload = {
91
+ status: actionable ? "actionable" : "quiet",
92
+ actionable,
93
+ writable: false,
94
+ windowDays,
95
+ staleDays,
96
+ hotThreshold,
97
+ telemetryEvents: telemetry.eventCount,
98
+ reasons,
99
+ hotStaleDocs,
100
+ reflectionClusters,
101
+ searchBlindSpots,
102
+ unmappedProbes,
103
+ preload: {
104
+ totalEstimatedTokens: preloadBudget.totalEstimatedTokens,
105
+ budgetTokens: preloadBudget.budgetTokens,
106
+ exceedsBudget: preloadBudget.exceedsBudget,
107
+ configured: preloadBudget.documents.map((item) => `llmdoc/${item.llmdocPath}`),
108
+ promoteCandidates: preloadRecommendations.promoteCandidates,
109
+ demoteCandidates: preloadRecommendations.demoteCandidates
110
+ },
111
+ borgesRiskDocs,
112
+ growth
113
+ };
114
+ if (options.json) {
115
+ return {
116
+ exitCode,
117
+ output: payload
118
+ };
119
+ }
120
+ if (options.check && options.quiet && !actionable) {
121
+ return {
122
+ exitCode: 0,
123
+ output: ""
124
+ };
125
+ }
126
+ const lines = [
127
+ actionable
128
+ ? `dream: actionable (${reasons.length} signal group(s); window ${windowDays}d, ${telemetry.eventCount} telemetry event(s))`
129
+ : `dream: quiet (no actionable consolidation signals; window ${windowDays}d, ${telemetry.eventCount} telemetry event(s))`
130
+ ];
131
+ if (!telemetryStatus.enabled) {
132
+ const note = telemetryStatus.reason === "tracked_by_git"
133
+ ? "note: local telemetry persistence is paused because .llmdoc-tmp/telemetry/access.jsonl is tracked by Git; untrack it and ignore .llmdoc-tmp/ to re-enable."
134
+ : "note: local telemetry persistence is paused because .llmdoc-tmp/telemetry/access.jsonl is not ignored by Git; add .llmdoc-tmp/ to .gitignore or .git/info/exclude to record access telemetry.";
135
+ lines.push("", note);
136
+ }
137
+ if (reasons.length > 0) {
138
+ lines.push("", "signals:");
139
+ for (const reason of reasons) {
140
+ lines.push(` - ${reason}`);
141
+ }
142
+ }
143
+ lines.push("", "hot documents due for verification:");
144
+ if (hotStaleDocs.length === 0) {
145
+ lines.push(" none");
146
+ }
147
+ else {
148
+ for (const item of hotStaleDocs) {
149
+ const age = item.daysSinceValidated === null ? "age unknown" : `${item.daysSinceValidated}d since validated`;
150
+ lines.push(` ${item.path} (active reads ${item.activeReads}, preloads ${item.preloadCount}, ${age}) — ${item.reason}`);
151
+ }
152
+ }
153
+ lines.push("", "pending reflection clusters:");
154
+ if (reflectionClusters.length === 0) {
155
+ lines.push(" none");
156
+ }
157
+ else {
158
+ for (const cluster of reflectionClusters) {
159
+ const ownerLabel = cluster.targetDoc ?? `scope:${cluster.scope ?? "general"}`;
160
+ lines.push(` ${ownerLabel} (${cluster.count} candidate(s)):`);
161
+ for (const candidate of cluster.candidates) {
162
+ lines.push(` - ${candidate.path} [${candidate.trigger}/${candidate.confidence}] ${candidate.title}`);
163
+ }
164
+ }
165
+ }
166
+ lines.push("", "search blind spots:");
167
+ if (searchBlindSpots.length === 0) {
168
+ lines.push(" none");
169
+ }
170
+ else {
171
+ for (const spot of searchBlindSpots) {
172
+ lines.push(` "${spot.query}" (${spot.occurrences}x: ${spot.zeroHitCount} zero-hit, ${spot.bigramFallbackCount} bigram fallback)`);
173
+ }
174
+ }
175
+ lines.push("", "frequently probed unmapped files:");
176
+ if (unmappedProbes.length === 0) {
177
+ lines.push(" none");
178
+ }
179
+ else {
180
+ for (const probe of unmappedProbes) {
181
+ lines.push(` ${probe.filePath} (${probe.occurrences}x)`);
182
+ }
183
+ }
184
+ lines.push("", `startup preload budget: ~${preloadBudget.totalEstimatedTokens}/${preloadBudget.budgetTokens} tokens (${preloadBudget.exceedsBudget ? "above budget" : "within budget"})`);
185
+ if (preloadRecommendations.promoteCandidates.length > 0) {
186
+ lines.push(" promote candidates (advisory; does not trigger --check alone):");
187
+ for (const item of preloadRecommendations.promoteCandidates) {
188
+ lines.push(` + ${item.path} (${item.showCount} shows, ~${item.estimatedTokens} tokens) — ${item.reason}`);
189
+ }
190
+ }
191
+ if (preloadRecommendations.demoteCandidates.length > 0) {
192
+ lines.push(preloadBudget.exceedsBudget
193
+ ? " demote candidates (return to progressive description/tree disclosure):"
194
+ : " demote candidates (advisory; return to progressive description/tree disclosure):");
195
+ for (const item of preloadRecommendations.demoteCandidates) {
196
+ lines.push(` - ${item.path} (~${item.estimatedTokens} tokens, ${item.activeReads} active reads) — ${item.reason}`);
197
+ }
198
+ }
199
+ lines.push("", "borges abstraction ratio risks:");
200
+ if (borgesRiskDocs.length === 0) {
201
+ lines.push(" none");
202
+ }
203
+ else {
204
+ for (const item of borgesRiskDocs) {
205
+ lines.push(` ${item.path} (doc ~${item.docTokens} tokens vs ${item.mappedFileCount} mapped file(s) ~${item.mappedSourceTokens} tokens, ratio ${item.ratio.toFixed(2)})`);
206
+ }
207
+ }
208
+ return {
209
+ exitCode,
210
+ output: lines.join("\n")
211
+ };
212
+ }
213
+ function assertDreamInputsHealthy(workspace) {
214
+ const fatalLocalIssues = [
215
+ ...workspace.preloadIssues.filter((issue) => issue.severity === "error"),
216
+ ...workspace.llmdocConfig.issues.filter((issue) => issue.severity === "error")
217
+ ];
218
+ if (fatalLocalIssues.length > 0) {
219
+ throw new CliError(`dream failed due to invalid local workspace state (run \`llmdoc validate\` for details):\n${fatalLocalIssues
220
+ .map((issue) => ` ${issue.code} (${issue.path ?? "llmdoc"}): ${issue.message}`)
221
+ .join("\n")}`, 1);
222
+ }
223
+ if (!workspace.meta) {
224
+ throw new CliError("dream failed because llmdoc/meta.json is missing. Run `llmdoc init-state` and `llmdoc commit --all` first.", 1);
225
+ }
226
+ }
227
+ function findHotStaleDocs(workspace, byDocument, options) {
228
+ const gitAvailable = isGitRepository(workspace.rootDir);
229
+ const shallow = gitAvailable ? isShallowRepository(workspace.rootDir) : false;
230
+ const revisionTimestampCache = new Map();
231
+ const readRevisionTs = (revision) => {
232
+ if (!gitAvailable) {
233
+ return null;
234
+ }
235
+ if (revisionTimestampCache.has(revision)) {
236
+ return revisionTimestampCache.get(revision) ?? null;
237
+ }
238
+ const ts = readCommitTimestampMs(workspace.rootDir, revision);
239
+ revisionTimestampCache.set(revision, ts);
240
+ return ts;
241
+ };
242
+ const results = [];
243
+ for (const document of workspace.documents) {
244
+ const stats = byDocument.get(document.llmdocPath);
245
+ if (!stats) {
246
+ continue;
247
+ }
248
+ const effectiveHeat = stats.activeReads + stats.preloadCount;
249
+ if (effectiveHeat < options.hotThreshold) {
250
+ continue;
251
+ }
252
+ const docMeta = workspace.meta?.documents[document.llmdocPath];
253
+ const validatedRevision = docMeta?.validatedRevision ?? null;
254
+ const explicitVerifiedMs = docMeta?.verifiedAt ? Date.parse(docMeta.verifiedAt) : Number.NaN;
255
+ if (!Number.isNaN(explicitVerifiedMs)) {
256
+ const daysSinceValidated = Math.max(0, Math.floor((options.nowMs - explicitVerifiedMs) / DAY_MS));
257
+ if (daysSinceValidated >= options.staleDays) {
258
+ results.push({
259
+ path: `llmdoc/${document.llmdocPath}`,
260
+ activeReads: stats.activeReads,
261
+ preloadCount: stats.preloadCount,
262
+ totalTouches: stats.totalTouches,
263
+ daysSinceValidated,
264
+ validatedRevision,
265
+ reason: "frequently accessed document has not been verified recently even without source diff"
266
+ });
267
+ }
268
+ continue;
269
+ }
270
+ if (!validatedRevision) {
271
+ results.push({
272
+ path: `llmdoc/${document.llmdocPath}`,
273
+ activeReads: stats.activeReads,
274
+ preloadCount: stats.preloadCount,
275
+ totalTouches: stats.totalTouches,
276
+ daysSinceValidated: null,
277
+ validatedRevision: null,
278
+ reason: "frequently accessed document has no validatedRevision anchor"
279
+ });
280
+ continue;
281
+ }
282
+ if (!gitAvailable) {
283
+ results.push({
284
+ path: `llmdoc/${document.llmdocPath}`,
285
+ activeReads: stats.activeReads,
286
+ preloadCount: stats.preloadCount,
287
+ totalTouches: stats.totalTouches,
288
+ daysSinceValidated: null,
289
+ validatedRevision,
290
+ reason: "frequently accessed document cannot compute verification age because Git is unavailable"
291
+ });
292
+ continue;
293
+ }
294
+ const commitMs = readRevisionTs(validatedRevision);
295
+ if (commitMs === null) {
296
+ results.push({
297
+ path: `llmdoc/${document.llmdocPath}`,
298
+ activeReads: stats.activeReads,
299
+ preloadCount: stats.preloadCount,
300
+ totalTouches: stats.totalTouches,
301
+ daysSinceValidated: null,
302
+ validatedRevision,
303
+ reason: shallow
304
+ ? "frequently accessed document points to a commit outside shallow clone history (fetch full history or re-verify with commit --verified)"
305
+ : "frequently accessed document points to an unreachable validatedRevision"
306
+ });
307
+ continue;
308
+ }
309
+ const daysSinceValidated = Math.max(0, Math.floor((options.nowMs - commitMs) / DAY_MS));
310
+ if (daysSinceValidated >= options.staleDays) {
311
+ results.push({
312
+ path: `llmdoc/${document.llmdocPath}`,
313
+ activeReads: stats.activeReads,
314
+ preloadCount: stats.preloadCount,
315
+ totalTouches: stats.totalTouches,
316
+ daysSinceValidated,
317
+ validatedRevision,
318
+ reason: "frequently accessed document has not been verified recently even without source diff"
319
+ });
320
+ }
321
+ }
322
+ return results.sort((left, right) => right.activeReads +
323
+ right.preloadCount -
324
+ (left.activeReads + left.preloadCount) ||
325
+ (right.daysSinceValidated ?? Number.MAX_SAFE_INTEGER) - (left.daysSinceValidated ?? Number.MAX_SAFE_INTEGER) ||
326
+ left.path.localeCompare(right.path));
327
+ }
328
+ function scanReflectionClusters(rootDir) {
329
+ const pendingDir = resolveSafeSubdirectory(rootDir, [".llmdoc-tmp", "reflections", "pending"], { create: false });
330
+ if (!pendingDir) {
331
+ return [];
332
+ }
333
+ let entries;
334
+ try {
335
+ entries = fs.readdirSync(pendingDir, { withFileTypes: true });
336
+ }
337
+ catch {
338
+ return [];
339
+ }
340
+ const grouped = new Map();
341
+ for (const entry of entries) {
342
+ if (entry.isSymbolicLink() || !entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) {
343
+ continue;
344
+ }
345
+ const absolutePath = path.join(pendingDir, entry.name);
346
+ const raw = readRegularFileSafely(absolutePath, MAX_REFLECTION_FILE_BYTES);
347
+ if (raw === null) {
348
+ continue;
349
+ }
350
+ const relativePath = `.llmdoc-tmp/reflections/pending/${entry.name}`;
351
+ let data = {};
352
+ let body = raw;
353
+ try {
354
+ const parsed = parseYamlFrontmatter(raw);
355
+ data = parsed.data;
356
+ body = parsed.content;
357
+ }
358
+ catch {
359
+ // Unparseable reflection candidate still counts as pending so it is surfaced for manual triage.
360
+ }
361
+ const rawMatch = typeof data.existingDocMatch === "string" ? data.existingDocMatch.trim() : "";
362
+ const targetDoc = rawMatch && rawMatch.toLowerCase() !== "none"
363
+ ? rawMatch.startsWith("llmdoc/")
364
+ ? rawMatch
365
+ : `llmdoc/${rawMatch}`
366
+ : null;
367
+ const scope = typeof data.scope === "string" && data.scope.trim() ? data.scope.trim() : null;
368
+ const trigger = typeof data.trigger === "string" && data.trigger.trim() ? data.trigger.trim() : "unknown";
369
+ const confidence = typeof data.confidence === "string" && data.confidence.trim() ? data.confidence.trim() : "unknown";
370
+ const createdAt = typeof data.createdAt === "string" && data.createdAt.trim() ? data.createdAt.trim() : null;
371
+ const extractedTitle = extractTitle(body)?.trim();
372
+ const title = extractedTitle && extractedTitle.length > 0 ? extractedTitle : entry.name;
373
+ const clusterKey = targetDoc ? `doc:${targetDoc}` : `scope:${(scope ?? "general").toLowerCase()}`;
374
+ const existing = grouped.get(clusterKey);
375
+ const summary = {
376
+ path: relativePath,
377
+ title,
378
+ trigger,
379
+ confidence,
380
+ createdAt
381
+ };
382
+ if (existing) {
383
+ existing.count += 1;
384
+ existing.candidates.push(summary);
385
+ }
386
+ else {
387
+ grouped.set(clusterKey, {
388
+ key: clusterKey,
389
+ targetDoc,
390
+ scope,
391
+ count: 1,
392
+ candidates: [summary]
393
+ });
394
+ }
395
+ }
396
+ const clusters = [...grouped.values()];
397
+ for (const cluster of clusters) {
398
+ cluster.candidates.sort((left, right) => left.path.localeCompare(right.path));
399
+ }
400
+ return clusters.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
401
+ }
402
+ function computePreloadRecommendations(workspace, preloadBudget, byDocument, telemetryEventCount, hotThreshold) {
403
+ const preloadedSet = new Set(preloadBudget.documents.map((item) => item.llmdocPath));
404
+ const promoteCandidates = [];
405
+ const demoteCandidates = [];
406
+ for (const document of workspace.documents) {
407
+ const stats = byDocument.get(document.llmdocPath);
408
+ if (!preloadedSet.has(document.llmdocPath)) {
409
+ if (stats &&
410
+ stats.showCount >= hotThreshold &&
411
+ preloadBudget.totalEstimatedTokens + document.estimatedTokens <= preloadBudget.budgetTokens) {
412
+ promoteCandidates.push({
413
+ path: `llmdoc/${document.llmdocPath}`,
414
+ showCount: stats.showCount,
415
+ estimatedTokens: document.estimatedTokens,
416
+ reason: "frequently fetched with show and fits within startup.preload budget"
417
+ });
418
+ }
419
+ continue;
420
+ }
421
+ const activeReads = stats?.activeReads ?? 0;
422
+ const searchHits = stats?.searchHitCount ?? 0;
423
+ if (preloadBudget.exceedsBudget) {
424
+ demoteCandidates.push({
425
+ path: `llmdoc/${document.llmdocPath}`,
426
+ activeReads,
427
+ estimatedTokens: document.estimatedTokens,
428
+ reason: "startup.preload exceeds soft budget; consider returning lower-frequency docs to description/tree disclosure"
429
+ });
430
+ }
431
+ else if (telemetryEventCount >= 5 && activeReads === 0 && searchHits === 0 && document.estimatedTokens >= 1200) {
432
+ demoteCandidates.push({
433
+ path: `llmdoc/${document.llmdocPath}`,
434
+ activeReads,
435
+ estimatedTokens: document.estimatedTokens,
436
+ reason: "large preloaded doc saw no active reads or search hits in window; description/tree disclosure may suffice"
437
+ });
438
+ }
439
+ }
440
+ promoteCandidates.sort((left, right) => right.showCount - left.showCount || left.estimatedTokens - right.estimatedTokens);
441
+ demoteCandidates.sort((left, right) => left.activeReads - right.activeReads || right.estimatedTokens - left.estimatedTokens);
442
+ return {
443
+ promoteCandidates: promoteCandidates.slice(0, 5),
444
+ demoteCandidates: demoteCandidates.slice(0, 5)
445
+ };
446
+ }
447
+ function findBorgesRiskDocs(workspace) {
448
+ const candidateDocs = workspace.documents.filter((document) => document.estimatedTokens >= BORGES_MIN_DOC_TOKENS && getDocumentCodePaths(document).length > 0);
449
+ if (candidateDocs.length === 0) {
450
+ return [];
451
+ }
452
+ const fileTokenCache = new Map();
453
+ const repoFiles = collectImplementationFiles(workspace.rootDir);
454
+ const risks = [];
455
+ for (const document of candidateDocs) {
456
+ const patterns = getDocumentCodePaths(document);
457
+ // Because mappedSourceTokens only grows as more matched files are added, once mappedSourceTokens
458
+ // exceeds docTokens / threshold, the ratio is guaranteed strictly below the warning threshold.
459
+ const safeSourceTokenFloor = document.estimatedTokens / BORGES_RATIO_WARNING_THRESHOLD;
460
+ let mappedSourceTokens = 0;
461
+ let matchedFileCount = 0;
462
+ let countedTextFileCount = 0;
463
+ let provenSafe = false;
464
+ let truncated = false;
465
+ for (const relPath of repoFiles) {
466
+ if (!patterns.some((pattern) => matchesCodePathPattern(pattern, relPath))) {
467
+ continue;
468
+ }
469
+ matchedFileCount += 1;
470
+ const fileTokens = readEstimatedSourceTokens(workspace.rootDir, relPath, fileTokenCache);
471
+ if (fileTokens > 0) {
472
+ countedTextFileCount += 1;
473
+ mappedSourceTokens += fileTokens;
474
+ if (mappedSourceTokens > safeSourceTokenFloor) {
475
+ provenSafe = true;
476
+ break;
477
+ }
478
+ }
479
+ if (matchedFileCount >= MAX_MATCHED_FILES_PER_DOC) {
480
+ truncated = true;
481
+ break;
482
+ }
483
+ }
484
+ // Never raise a Borges warning when the denominator was truncated at the file cap.
485
+ if (provenSafe || truncated || countedTextFileCount === 0 || mappedSourceTokens <= 0) {
486
+ continue;
487
+ }
488
+ const rawRatio = document.estimatedTokens / mappedSourceTokens;
489
+ if (rawRatio >= BORGES_RATIO_WARNING_THRESHOLD) {
490
+ risks.push({
491
+ path: `llmdoc/${document.llmdocPath}`,
492
+ docTokens: document.estimatedTokens,
493
+ mappedSourceTokens,
494
+ mappedFileCount: countedTextFileCount,
495
+ ratio: Number(rawRatio.toFixed(2))
496
+ });
497
+ }
498
+ }
499
+ return risks.sort((left, right) => right.ratio - left.ratio || right.docTokens - left.docTokens);
500
+ }
501
+ function collectImplementationFiles(rootDir) {
502
+ const ignorePatterns = loadIgnorePatterns(rootDir);
503
+ const tracked = listGitTrackedFiles(rootDir);
504
+ if (tracked !== null) {
505
+ return tracked.filter((rel) => isImplementationSurfacePath(rel, ignorePatterns));
506
+ }
507
+ // Bounded non-Git fallback.
508
+ const files = [];
509
+ const stack = [rootDir];
510
+ while (stack.length > 0 && files.length < MAX_FALLBACK_WALK_FILES) {
511
+ const current = stack.pop();
512
+ let entries;
513
+ try {
514
+ entries = fs.readdirSync(current, { withFileTypes: true });
515
+ }
516
+ catch {
517
+ continue;
518
+ }
519
+ entries.sort((left, right) => left.name.localeCompare(right.name));
520
+ for (const entry of entries) {
521
+ if (entry.isSymbolicLink()) {
522
+ continue;
523
+ }
524
+ if (entry.isDirectory()) {
525
+ if ([".git", ".llmdoc-tmp", "node_modules", "llmdoc", "dist", "build", "coverage", ".next", "out"].includes(entry.name)) {
526
+ continue;
527
+ }
528
+ stack.push(path.join(current, entry.name));
529
+ continue;
530
+ }
531
+ if (!entry.isFile()) {
532
+ continue;
533
+ }
534
+ const absolutePath = path.join(current, entry.name);
535
+ const rel = repoPath(rootDir, absolutePath);
536
+ if (isImplementationSurfacePath(rel, ignorePatterns)) {
537
+ files.push(rel);
538
+ if (files.length >= MAX_FALLBACK_WALK_FILES) {
539
+ break;
540
+ }
541
+ }
542
+ }
543
+ }
544
+ return files.sort();
545
+ }
546
+ function readEstimatedSourceTokens(rootDir, repoRelativePath, cache) {
547
+ const cached = cache.get(repoRelativePath);
548
+ if (cached !== undefined) {
549
+ return cached;
550
+ }
551
+ let tokens = 0;
552
+ try {
553
+ const safePath = resolveInsideRoot(rootDir, repoRelativePath);
554
+ const stat = fs.lstatSync(safePath);
555
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0) {
556
+ cache.set(repoRelativePath, 0);
557
+ return 0;
558
+ }
559
+ const noFollow = fs.constants.O_NOFOLLOW ?? 0;
560
+ const fd = fs.openSync(safePath, fs.constants.O_RDONLY | noFollow);
561
+ try {
562
+ const probeLen = Math.min(stat.size, BINARY_CHECK_BYTES);
563
+ const probeBuf = Buffer.alloc(probeLen);
564
+ const probeRead = fs.readSync(fd, probeBuf, 0, probeLen, 0);
565
+ if (probeBuf.subarray(0, probeRead).includes(0)) {
566
+ cache.set(repoRelativePath, 0);
567
+ return 0;
568
+ }
569
+ if (stat.size <= MAX_SOURCE_FILE_BYTES_FOR_FULL_READ) {
570
+ const fullBuf = Buffer.alloc(stat.size);
571
+ let offset = 0;
572
+ while (offset < stat.size) {
573
+ const read = fs.readSync(fd, fullBuf, offset, stat.size - offset, offset);
574
+ if (read <= 0) {
575
+ break;
576
+ }
577
+ offset += read;
578
+ }
579
+ tokens = estimateTokens(fullBuf.subarray(0, offset).toString("utf8"));
580
+ }
581
+ else {
582
+ // Estimate character length from a UTF-8 sample so CJK and ASCII files stay on one continuous scale across the threshold.
583
+ const sampleLen = Math.min(stat.size, SAMPLE_SOURCE_BYTES_FOR_LARGE_FILE);
584
+ const sampleBuf = Buffer.alloc(sampleLen);
585
+ let offset = 0;
586
+ while (offset < sampleLen) {
587
+ const read = fs.readSync(fd, sampleBuf, offset, sampleLen - offset, offset);
588
+ if (read <= 0) {
589
+ break;
590
+ }
591
+ offset += read;
592
+ }
593
+ const sampleText = sampleBuf.subarray(0, offset).toString("utf8");
594
+ const charsPerByte = offset > 0 ? sampleText.length / offset : 1;
595
+ const estimatedChars = Math.max(1, Math.round(stat.size * charsPerByte));
596
+ tokens = Math.max(1, Math.ceil(estimatedChars / 4));
597
+ }
598
+ }
599
+ finally {
600
+ fs.closeSync(fd);
601
+ }
602
+ }
603
+ catch {
604
+ tokens = 0;
605
+ }
606
+ cache.set(repoRelativePath, tokens);
607
+ return tokens;
608
+ }