@tokenroll/llmdoc 3.6.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,77 +1,424 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { DEFAULT_LOCAL_PRELOAD_BUDGET_TOKENS, MAX_EXTERNAL_PRELOAD_BYTES } from "./constants.js";
3
4
  import { normalizeRepoRelativePath, resolveInsideRoot } from "./fs.js";
4
5
  import { validateLlmdocConfig } from "./schema.js";
6
+ import { formatDocumentPath, isSourceRef, isValidSourceAlias, normalizeSourceSubdir, parseSourceDocId } from "./source-id.js";
7
+ import { parseRefreshDurationMs, validateGitRef, validateGitSourceUrl } from "./sources.js";
5
8
  export const LLMDOC_CONFIG_FILENAME = "llmdoc.config.json";
9
+ export const LLMDOC_LOCAL_CONFIG_FILENAME = "llmdoc.config.local.json";
6
10
  export function loadLlmdocConfig(rootDir, documentsByLlmdocPath) {
7
- const configPath = path.join(rootDir, LLMDOC_CONFIG_FILENAME);
11
+ const shared = parseSingleConfigFile(rootDir, LLMDOC_CONFIG_FILENAME, false);
12
+ const local = parseSingleConfigFile(rootDir, LLMDOC_LOCAL_CONFIG_FILENAME, true);
13
+ if (!shared.exists && !local.exists) {
14
+ return {
15
+ exists: false,
16
+ sharedConfigExists: false,
17
+ localConfigExists: false,
18
+ schemaVersion: null,
19
+ config: null,
20
+ preloadPaths: [],
21
+ preloadEntries: [],
22
+ sources: {},
23
+ issues: [],
24
+ hasLocalPreloadErrors: false
25
+ };
26
+ }
27
+ const issues = [...shared.issues, ...local.issues];
28
+ const mergedSources = {
29
+ ...shared.sources,
30
+ ...local.sources
31
+ };
32
+ const declaredSourceAliases = new Set([
33
+ ...shared.declaredSourceAliases,
34
+ ...local.declaredSourceAliases
35
+ ]);
36
+ const effectiveConfig = mergeEffectiveConfig(shared.config, local.config, mergedSources);
37
+ if (!effectiveConfig) {
38
+ return {
39
+ exists: true,
40
+ sharedConfigExists: shared.exists,
41
+ localConfigExists: local.exists,
42
+ schemaVersion: null,
43
+ config: null,
44
+ preloadPaths: [],
45
+ preloadEntries: [],
46
+ sources: {},
47
+ issues,
48
+ hasLocalPreloadErrors: false
49
+ };
50
+ }
51
+ const schemaVersion = effectiveConfig.schema === "llmdoc.config/v2" ? 2 : 1;
52
+ const preloadEntries = [];
53
+ const preloadPaths = [];
54
+ const seen = new Set();
55
+ let hasLocalPreloadErrors = false;
56
+ const preloadInputs = [
57
+ ...(shared.config?.startup?.preload ?? []).map((rawPath) => ({ rawPath, fileName: LLMDOC_CONFIG_FILENAME })),
58
+ ...(local.config?.startup?.preload ?? []).map((rawPath) => ({ rawPath, fileName: LLMDOC_LOCAL_CONFIG_FILENAME }))
59
+ ];
60
+ for (const { rawPath, fileName } of preloadInputs) {
61
+ if (isSourceRef(rawPath)) {
62
+ if (schemaVersion < 2) {
63
+ hasLocalPreloadErrors = true;
64
+ issues.push(configIssue(fileName, "config.startup.preload.path", `External source preload requires schema llmdoc.config/v2 with configured sources: ${rawPath}`));
65
+ continue;
66
+ }
67
+ let parsedSourceId;
68
+ try {
69
+ parsedSourceId = parseSourceDocId(rawPath);
70
+ }
71
+ catch (error) {
72
+ hasLocalPreloadErrors = true;
73
+ issues.push(configIssue(fileName, "config.startup.preload.path", error.message));
74
+ continue;
75
+ }
76
+ if (!declaredSourceAliases.has(parsedSourceId.alias)) {
77
+ hasLocalPreloadErrors = true;
78
+ issues.push(configIssue(fileName, "config.startup.preload.undeclared-source", `startup.preload references an undeclared source: @${parsedSourceId.alias} (${rawPath})`));
79
+ continue;
80
+ }
81
+ if (seen.has(parsedSourceId.canonicalId)) {
82
+ issues.push(configIssue(fileName, "config.startup.preload.duplicate", `startup.preload contains the same normalized document more than once; duplicate ignored: ${parsedSourceId.canonicalId}`, "warning"));
83
+ continue;
84
+ }
85
+ seen.add(parsedSourceId.canonicalId);
86
+ preloadPaths.push(parsedSourceId.canonicalId);
87
+ preloadEntries.push({
88
+ raw: rawPath,
89
+ normalized: parsedSourceId.canonicalId,
90
+ kind: "source",
91
+ sourceName: parsedSourceId.alias
92
+ });
93
+ continue;
94
+ }
95
+ let normalized;
96
+ try {
97
+ normalized = normalizePreloadPath(rawPath);
98
+ }
99
+ catch (error) {
100
+ hasLocalPreloadErrors = true;
101
+ issues.push(configIssue(fileName, "config.startup.preload.path", error.message));
102
+ continue;
103
+ }
104
+ if (seen.has(normalized)) {
105
+ issues.push(configIssue(fileName, "config.startup.preload.duplicate", `startup.preload contains the same normalized document more than once; duplicate ignored: llmdoc/${normalized}`, "warning"));
106
+ continue;
107
+ }
108
+ seen.add(normalized);
109
+ if (documentsByLlmdocPath && !documentsByLlmdocPath.has(normalized)) {
110
+ hasLocalPreloadErrors = true;
111
+ issues.push(configIssue(fileName, "config.startup.preload.missing", `startup.preload document does not exist: llmdoc/${normalized}`));
112
+ continue;
113
+ }
114
+ preloadPaths.push(normalized);
115
+ preloadEntries.push({
116
+ raw: rawPath,
117
+ normalized,
118
+ kind: "local",
119
+ sourceName: null
120
+ });
121
+ }
122
+ const preloadBudgetSourceFile = !shared.exists
123
+ ? LLMDOC_LOCAL_CONFIG_FILENAME
124
+ : local.config?.startup?.preloadBudgetTokens !== undefined
125
+ ? LLMDOC_LOCAL_CONFIG_FILENAME
126
+ : (shared.config?.startup?.preload?.length ?? 0) === 0 && (local.config?.startup?.preload?.length ?? 0) > 0
127
+ ? LLMDOC_LOCAL_CONFIG_FILENAME
128
+ : LLMDOC_CONFIG_FILENAME;
129
+ return {
130
+ exists: true,
131
+ sharedConfigExists: shared.exists,
132
+ localConfigExists: local.exists,
133
+ preloadBudgetSourceFile,
134
+ schemaVersion,
135
+ config: effectiveConfig,
136
+ preloadPaths: hasLocalPreloadErrors ? [] : preloadPaths,
137
+ preloadEntries: hasLocalPreloadErrors ? [] : preloadEntries,
138
+ sources: mergedSources,
139
+ issues,
140
+ hasLocalPreloadErrors
141
+ };
142
+ }
143
+ function parseSingleConfigFile(rootDir, fileName, allowOutsideRootPaths) {
144
+ const configPath = path.join(rootDir, fileName);
8
145
  if (!fs.existsSync(configPath)) {
9
- return { exists: false, config: null, preloadPaths: [], issues: [] };
146
+ return {
147
+ exists: false,
148
+ fileName,
149
+ schemaVersion: null,
150
+ config: null,
151
+ sources: {},
152
+ declaredSourceAliases: new Set(),
153
+ issues: []
154
+ };
10
155
  }
11
156
  let safeConfigPath;
12
157
  try {
13
- safeConfigPath = resolveInsideRoot(rootDir, LLMDOC_CONFIG_FILENAME);
158
+ safeConfigPath = resolveInsideRoot(rootDir, fileName);
14
159
  }
15
160
  catch (error) {
16
- return invalidConfig(`The config file must remain inside the repository: ${error.message}`);
161
+ return {
162
+ exists: true,
163
+ fileName,
164
+ schemaVersion: null,
165
+ config: null,
166
+ sources: {},
167
+ declaredSourceAliases: new Set(),
168
+ issues: [configIssue(fileName, "config.read", `The config file must remain inside the repository: ${error.message}`)]
169
+ };
17
170
  }
18
171
  let input;
19
172
  try {
20
173
  input = JSON.parse(fs.readFileSync(safeConfigPath, "utf8"));
21
174
  }
22
175
  catch (error) {
23
- return invalidConfig(`JSON parse failed: ${error.message}`);
176
+ return {
177
+ exists: true,
178
+ fileName,
179
+ schemaVersion: null,
180
+ config: null,
181
+ sources: {},
182
+ declaredSourceAliases: new Set(),
183
+ issues: [configIssue(fileName, "config.read", `JSON parse failed: ${error.message}`)]
184
+ };
185
+ }
186
+ const unsupportedFutureVersion = detectUnsupportedFutureSchemaVersion(input);
187
+ if (unsupportedFutureVersion) {
188
+ return {
189
+ exists: true,
190
+ fileName,
191
+ schemaVersion: null,
192
+ config: null,
193
+ sources: {},
194
+ declaredSourceAliases: new Set(),
195
+ issues: [
196
+ configIssue(fileName, "config.schema.unsupported", `${fileName} uses schema ${unsupportedFutureVersion}, which is newer than this CLI supports (up to llmdoc.config/v2). Upgrade @tokenroll/llmdoc.`)
197
+ ]
198
+ };
24
199
  }
25
200
  const schemaErrors = validateLlmdocConfig(input);
26
201
  if (schemaErrors.length > 0) {
27
202
  return {
28
203
  exists: true,
204
+ fileName,
205
+ schemaVersion: null,
29
206
  config: null,
30
- preloadPaths: [],
31
- issues: schemaErrors.map((message) => configIssue("config.invalid", `Invalid config: ${message}`))
207
+ sources: {},
208
+ declaredSourceAliases: new Set(),
209
+ issues: schemaErrors.map((message) => configIssue(fileName, "config.invalid", `Invalid config: ${message}`))
32
210
  };
33
211
  }
34
212
  const config = input;
35
- const preloadPaths = [];
213
+ const schemaVersion = config.schema === "llmdoc.config/v2" ? 2 : 1;
36
214
  const issues = [];
37
- const seen = new Set();
38
- for (const rawPath of config.startup?.preload ?? []) {
39
- let normalized;
40
- try {
41
- normalized = normalizePreloadPath(rawPath);
42
- }
43
- catch (error) {
44
- issues.push(configIssue("config.startup.preload.path", error.message));
45
- continue;
46
- }
47
- if (seen.has(normalized)) {
48
- issues.push(configIssue("config.startup.preload.duplicate", `startup.preload contains the same normalized document more than once; duplicate ignored: llmdoc/${normalized}`, "warning"));
49
- continue;
50
- }
51
- seen.add(normalized);
52
- preloadPaths.push(normalized);
53
- if (documentsByLlmdocPath && !documentsByLlmdocPath.has(normalized)) {
54
- issues.push(configIssue("config.startup.preload.missing", `startup.preload document does not exist: llmdoc/${normalized}`));
215
+ const validSources = {};
216
+ const declaredSourceAliases = new Set(Object.keys(config.sources ?? {}));
217
+ if (schemaVersion === 2 && config.sources) {
218
+ for (const [alias, rawSource] of Object.entries(config.sources)) {
219
+ if (!isValidSourceAlias(alias)) {
220
+ issues.push(configIssue(fileName, "config.sources.alias.invalid", `Invalid source alias "${alias}". Source aliases must match ^[a-z0-9][a-z0-9._-]{0,63}$.`));
221
+ continue;
222
+ }
223
+ if ("git" in rawSource) {
224
+ const urlValidation = validateGitSourceUrl(rawSource.git);
225
+ let sourceHasError = false;
226
+ if (!urlValidation.ok) {
227
+ issues.push(configIssue(fileName, "config.sources.git.invalid", `Source @${alias}: ${urlValidation.message}`));
228
+ sourceHasError = true;
229
+ }
230
+ let normalizedRef;
231
+ if (rawSource.ref !== undefined) {
232
+ const refValidation = validateGitRef(rawSource.ref);
233
+ if (!refValidation.ok) {
234
+ issues.push(configIssue(fileName, "config.sources.ref.invalid", `Source @${alias}: ${refValidation.message}`));
235
+ sourceHasError = true;
236
+ }
237
+ else {
238
+ normalizedRef = refValidation.normalized;
239
+ }
240
+ }
241
+ let normalizedDir;
242
+ if (rawSource.dir !== undefined) {
243
+ try {
244
+ normalizedDir = normalizeSourceSubdir(rawSource.dir);
245
+ }
246
+ catch (error) {
247
+ issues.push(configIssue(fileName, "config.sources.dir.invalid", `Source @${alias}: ${error.message}`));
248
+ sourceHasError = true;
249
+ }
250
+ }
251
+ if (rawSource.refresh !== undefined) {
252
+ try {
253
+ parseRefreshDurationMs(rawSource.refresh);
254
+ }
255
+ catch (error) {
256
+ issues.push(configIssue(fileName, "config.sources.refresh.invalid", `Source @${alias}: ${error.message}`));
257
+ sourceHasError = true;
258
+ }
259
+ }
260
+ if (!sourceHasError && urlValidation.ok) {
261
+ validSources[alias] = {
262
+ git: urlValidation.normalized,
263
+ ...(normalizedRef !== undefined ? { ref: normalizedRef } : {}),
264
+ ...(normalizedDir !== undefined ? { dir: normalizedDir } : {}),
265
+ ...(rawSource.refresh !== undefined ? { refresh: rawSource.refresh } : {})
266
+ };
267
+ }
268
+ }
269
+ else {
270
+ let sourceHasError = false;
271
+ let normalizedPath = rawSource.path.trim();
272
+ if (allowOutsideRootPaths) {
273
+ if (!normalizedPath || normalizedPath.includes("\0")) {
274
+ issues.push(configIssue(fileName, "config.sources.path.invalid", `Source @${alias}: Invalid local path: ${rawSource.path}`));
275
+ sourceHasError = true;
276
+ }
277
+ }
278
+ else {
279
+ try {
280
+ normalizedPath = normalizeRepoRelativePath(rawSource.path);
281
+ resolveInsideRoot(rootDir, normalizedPath, { allowMissing: true });
282
+ }
283
+ catch (error) {
284
+ issues.push(configIssue(fileName, "config.sources.path.invalid", `Source @${alias}: ${error.message}`));
285
+ sourceHasError = true;
286
+ }
287
+ }
288
+ let normalizedDir;
289
+ if (rawSource.dir !== undefined) {
290
+ try {
291
+ normalizedDir = normalizeSourceSubdir(rawSource.dir);
292
+ }
293
+ catch (error) {
294
+ issues.push(configIssue(fileName, "config.sources.dir.invalid", `Source @${alias}: ${error.message}`));
295
+ sourceHasError = true;
296
+ }
297
+ }
298
+ if (!sourceHasError) {
299
+ validSources[alias] = {
300
+ path: normalizedPath,
301
+ ...(normalizedDir !== undefined ? { dir: normalizedDir } : {}),
302
+ ...(allowOutsideRootPaths ? { allowOutsideRoot: true } : {})
303
+ };
304
+ }
305
+ }
55
306
  }
56
307
  }
57
308
  return {
58
309
  exists: true,
310
+ fileName,
311
+ schemaVersion,
59
312
  config,
60
- preloadPaths: issues.some((issue) => issue.severity === "error") ? [] : preloadPaths,
313
+ sources: validSources,
314
+ declaredSourceAliases,
61
315
  issues
62
316
  };
63
317
  }
64
- export function formatStartupPreloadDocuments(documents) {
65
- if (documents.length === 0) {
66
- return "";
318
+ function mergeEffectiveConfig(shared, local, mergedSources) {
319
+ if (!shared && !local) {
320
+ return null;
67
321
  }
68
- const lines = [
69
- `llmdoc startup preload begins (${documents.length} document(s)). The configured bodies are provided directly below. If the final completion marker is visible, these bodies are complete and do not need another search/show; otherwise retrieve any missing document with npx @tokenroll/llmdoc show.`
322
+ const schema = shared?.schema === "llmdoc.config/v2" || local?.schema === "llmdoc.config/v2"
323
+ ? "llmdoc.config/v2"
324
+ : "llmdoc.config/v1";
325
+ const remindSkill = local?.startup?.remindSkill !== undefined
326
+ ? local.startup.remindSkill
327
+ : shared?.startup?.remindSkill;
328
+ const preloadBudgetTokens = local?.startup?.preloadBudgetTokens !== undefined
329
+ ? local.startup.preloadBudgetTokens
330
+ : shared?.startup?.preloadBudgetTokens;
331
+ const preload = [
332
+ ...(shared?.startup?.preload ?? []),
333
+ ...(local?.startup?.preload ?? [])
70
334
  ];
335
+ const hasStartup = Boolean(shared?.startup || local?.startup);
336
+ return {
337
+ schema,
338
+ ...(schema === "llmdoc.config/v2" && Object.keys(mergedSources).length > 0 ? { sources: mergedSources } : {}),
339
+ ...(hasStartup
340
+ ? {
341
+ startup: {
342
+ ...(remindSkill !== undefined ? { remindSkill } : {}),
343
+ ...(preload.length > 0 ? { preload } : {}),
344
+ ...(preloadBudgetTokens !== undefined ? { preloadBudgetTokens } : {})
345
+ }
346
+ }
347
+ : {})
348
+ };
349
+ }
350
+ export function computeLocalPreloadBudget(llmdocConfig, documentsByLlmdocPath) {
351
+ const budgetTokens = llmdocConfig.config?.startup?.preloadBudgetTokens ?? DEFAULT_LOCAL_PRELOAD_BUDGET_TOKENS;
352
+ const documents = [];
353
+ let totalEstimatedTokens = 0;
354
+ for (const entry of llmdocConfig.preloadEntries) {
355
+ if (entry.kind !== "local") {
356
+ continue;
357
+ }
358
+ const doc = documentsByLlmdocPath.get(entry.normalized);
359
+ if (!doc) {
360
+ continue;
361
+ }
362
+ documents.push({
363
+ llmdocPath: doc.llmdocPath,
364
+ estimatedTokens: doc.estimatedTokens
365
+ });
366
+ totalEstimatedTokens += doc.estimatedTokens;
367
+ }
368
+ return {
369
+ totalEstimatedTokens,
370
+ budgetTokens,
371
+ exceedsBudget: documents.length > 0 && totalEstimatedTokens > budgetTokens,
372
+ documents
373
+ };
374
+ }
375
+ export function formatStartupPreloadDocuments(documents, options) {
376
+ const skipped = [...(options?.skipped ?? [])];
377
+ const emitted = [];
378
+ let externalBytesUsed = 0;
71
379
  for (const document of documents) {
72
- lines.push("", `=== llmdoc/${document.llmdocPath} [${document.frontmatter.kind}] (startup preload) ===`, document.body);
380
+ if (document.sourceName) {
381
+ const bodyBytes = Buffer.byteLength(document.body, "utf8");
382
+ if (externalBytesUsed + bodyBytes > MAX_EXTERNAL_PRELOAD_BYTES) {
383
+ skipped.push({
384
+ id: formatDocumentPath(document),
385
+ reason: `exceeded external preload size limit (${Math.round(MAX_EXTERNAL_PRELOAD_BYTES / 1024)} KiB); retrieve explicitly with npx -y @tokenroll/llmdoc show ${formatDocumentPath(document)}`
386
+ });
387
+ continue;
388
+ }
389
+ externalBytesUsed += bodyBytes;
390
+ }
391
+ emitted.push(document);
392
+ }
393
+ const lines = [];
394
+ if (emitted.length > 0) {
395
+ lines.push(`llmdoc startup preload begins (${emitted.length} document(s)). The configured bodies are provided directly below. If the final completion marker is visible, these bodies are complete and do not need another search/show; otherwise retrieve any missing document with npx -y @tokenroll/llmdoc show.`);
396
+ for (const document of emitted) {
397
+ const displayPath = formatDocumentPath(document);
398
+ if (document.sourceName) {
399
+ const source = options?.sourcesByName?.get(document.sourceName);
400
+ const rev = source?.revision ? ` @ ${source.revision.slice(0, 7)}` : "";
401
+ lines.push("", `=== ${displayPath} [${document.frontmatter.kind}] (startup preload; external source @${document.sourceName}${rev}, read-only reference) ===`, document.body);
402
+ }
403
+ else {
404
+ lines.push("", `=== ${displayPath} [${document.frontmatter.kind}] (startup preload) ===`, document.body);
405
+ }
406
+ }
407
+ }
408
+ if (skipped.length > 0) {
409
+ if (lines.length > 0) {
410
+ lines.push("");
411
+ }
412
+ lines.push("Skipped startup preload external document(s):");
413
+ for (const entry of skipped) {
414
+ lines.push(`- ${entry.id}: ${entry.reason}`);
415
+ }
416
+ }
417
+ if (emitted.length > 0) {
418
+ lines.push("", skipped.length > 0
419
+ ? `=== llmdoc startup preload complete (partial: ${skipped.length} external document(s) skipped) ===`
420
+ : "=== llmdoc startup preload complete ===");
73
421
  }
74
- lines.push("", "=== llmdoc startup preload complete ===");
75
422
  return lines.join("\n");
76
423
  }
77
424
  export function formatCompactPreloadIndex(preloadPaths) {
@@ -79,8 +426,8 @@ export function formatCompactPreloadIndex(preloadPaths) {
79
426
  return "";
80
427
  }
81
428
  return `Configured startup preload bodies were not re-injected after compaction. Document IDs: ${preloadPaths
82
- .map((preloadPath) => `llmdoc/${preloadPath}`)
83
- .join(", ")}. Retrieve a body with npx @tokenroll/llmdoc show only when the compacted context no longer contains what the task needs.`;
429
+ .map((preloadPath) => (isSourceRef(preloadPath) ? preloadPath : `llmdoc/${preloadPath}`))
430
+ .join(", ")}. Retrieve a body with npx -y @tokenroll/llmdoc show only when the compacted context no longer contains what the task needs.`;
84
431
  }
85
432
  export function rewriteStartupPreloadForMove(config, mapping) {
86
433
  const preload = config.startup?.preload;
@@ -90,6 +437,9 @@ export function rewriteStartupPreloadForMove(config, mapping) {
90
437
  const moveByPath = new Map(mapping.map((item) => [item.oldLlmdocPath, item.newLlmdocPath]));
91
438
  let changed = false;
92
439
  const rewritten = preload.map((rawPath) => {
440
+ if (isSourceRef(rawPath)) {
441
+ return rawPath;
442
+ }
93
443
  let normalized;
94
444
  try {
95
445
  normalized = normalizePreloadPath(rawPath);
@@ -118,6 +468,21 @@ export function rewriteStartupPreloadForMove(config, mapping) {
118
468
  : config
119
469
  };
120
470
  }
471
+ function detectUnsupportedFutureSchemaVersion(input) {
472
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
473
+ return null;
474
+ }
475
+ const schema = input.schema;
476
+ if (typeof schema !== "string") {
477
+ return null;
478
+ }
479
+ const match = schema.match(/^llmdoc\.config\/v(\d+)$/);
480
+ if (!match) {
481
+ return null;
482
+ }
483
+ const version = Number.parseInt(match[1], 10);
484
+ return Number.isInteger(version) && version > 2 ? schema : null;
485
+ }
121
486
  function normalizePreloadPath(rawPath) {
122
487
  const trimmed = rawPath.trim().replaceAll("\\", "/");
123
488
  const withoutPrefix = trimmed.startsWith("llmdoc/") ? trimmed.slice("llmdoc/".length) : trimmed;
@@ -127,19 +492,11 @@ function normalizePreloadPath(rawPath) {
127
492
  }
128
493
  return normalized;
129
494
  }
130
- function invalidConfig(message) {
131
- return {
132
- exists: true,
133
- config: null,
134
- preloadPaths: [],
135
- issues: [configIssue("config.read", message)]
136
- };
137
- }
138
- function configIssue(code, message, severity = "error") {
495
+ function configIssue(fileName, code, message, severity = "error") {
139
496
  return {
140
497
  severity,
141
498
  code,
142
- path: LLMDOC_CONFIG_FILENAME,
499
+ path: fileName,
143
500
  message
144
501
  };
145
502
  }
@@ -4,5 +4,28 @@ export const DEFAULT_LIMIT = 50;
4
4
  export const DOC_LINE_WARNING_LIMIT = 150;
5
5
  export const CACHE_DIR = ".llmdoc-tmp/cache";
6
6
  export const SEARCH_CACHE_FILE = "search-index.json";
7
+ export const TELEMETRY_DIR = ".llmdoc-tmp/telemetry";
8
+ export const TELEMETRY_ACCESS_FILE = "access.jsonl";
9
+ export const TELEMETRY_MAX_BYTES = 512 * 1024;
10
+ export const TELEMETRY_KEEP_RECORDS = 2000;
7
11
  export const FRAGMENT_TOKEN_THRESHOLD = 180;
8
12
  export const DUPLICATE_SIMILARITY_THRESHOLD = 0.72;
13
+ export const DEFAULT_LOCAL_PRELOAD_BUDGET_TOKENS = 4000;
14
+ export const DEFAULT_DREAM_WINDOW_DAYS = 14;
15
+ export const DEFAULT_DREAM_STALE_DAYS = 14;
16
+ export const DEFAULT_DREAM_HOT_THRESHOLD = 3;
17
+ export const DEFAULT_DREAM_MIN_BLIND_SPOT_OCCURRENCES = 2;
18
+ export const DEFAULT_DREAM_MIN_UNMAPPED_PROBE_OCCURRENCES = 2;
19
+ export const BORGES_RATIO_WARNING_THRESHOLD = 0.6;
20
+ export const BORGES_MIN_DOC_TOKENS = 250;
21
+ export const LLMDOC_PROBES_FILENAME = "llmdoc.probes.json";
22
+ export const DEFAULT_SOURCE_REFRESH = "24h";
23
+ export const DEFAULT_SOURCE_REFRESH_MS = 24 * 60 * 60 * 1000;
24
+ export const DEFAULT_SOURCE_GIT_TIMEOUT_MS = 15_000;
25
+ export const DEFAULT_SOURCE_COLD_WALL_TIMEOUT_MS = 25_000;
26
+ export const DEFAULT_SOURCE_MAX_RETRIES = 3;
27
+ export const DEFAULT_SOURCE_COOLDOWN_MS = 5 * 60 * 1000;
28
+ export const DEFAULT_SOURCE_LOCK_STALE_MS = 120_000;
29
+ export const MAX_SOURCE_DOCUMENTS = 500;
30
+ export const MAX_SOURCE_DOCUMENT_BYTES = 256 * 1024;
31
+ export const MAX_EXTERNAL_PRELOAD_BYTES = 128 * 1024;
@@ -0,0 +1,47 @@
1
+ import { createRequire } from "node:module";
2
+ import { CliError } from "./errors.js";
3
+ // Resolve the YAML reader/writer owned by gray-matter even with an unhoisted install.
4
+ // Calling it directly keeps input and rewrite output completely out of gray-matter's language dispatch.
5
+ const require = createRequire(import.meta.url);
6
+ const yaml = createRequire(require.resolve("gray-matter"))("js-yaml");
7
+ export function parseYamlFrontmatter(raw) {
8
+ const text = raw.replace(/^\uFEFF/u, "");
9
+ if (/^---[ \t]*[a-zA-Z][^\r\n]*(?:\r?\n|$)/u.test(text)) {
10
+ throw new CliError("Unsupported front matter engine; only plain YAML front matter is allowed.");
11
+ }
12
+ const opening = /^---\r?\n/u.exec(text);
13
+ if (opening) {
14
+ const rest = text.slice(opening[0].length);
15
+ const closing = /(?:^|\n)---(?:\r?\n|$)/u.exec(rest);
16
+ if (closing) {
17
+ const yamlBlock = rest.slice(0, closing.index);
18
+ let data;
19
+ try {
20
+ data = yaml.safeLoad(yamlBlock, { schema: yaml.JSON_SCHEMA }) ?? {};
21
+ }
22
+ catch (error) {
23
+ const message = error.message;
24
+ if (/(?:^|\n)\s*(?:-\s+|[A-Za-z0-9_-]+:\s+)@/u.test(yamlBlock)) {
25
+ throw new CliError(`${message} (Hint: YAML values starting with "@" must be quoted, e.g. "@team/doc.md")`);
26
+ }
27
+ throw error;
28
+ }
29
+ if (typeof data !== "object" ||
30
+ data === null ||
31
+ (Object.getPrototypeOf(data) !== Object.prototype && Object.getPrototypeOf(data) !== null)) {
32
+ throw new CliError("YAML front matter must be a mapping.");
33
+ }
34
+ return {
35
+ hasFrontmatter: true,
36
+ data: data,
37
+ content: rest.slice(closing.index + closing[0].length)
38
+ };
39
+ }
40
+ }
41
+ return { hasFrontmatter: false, data: {}, content: raw };
42
+ }
43
+ export function stringifyYamlFrontmatter(data, body) {
44
+ const dumped = yaml.safeDump(data, { lineWidth: -1, noRefs: true, skipInvalid: true }).trimEnd();
45
+ const normalizedBody = body.replace(/^\r?\n+/, "");
46
+ return normalizedBody ? `---\n${dumped}\n---\n\n${normalizedBody.replace(/\r?\n?$/, "\n")}` : `---\n${dumped}\n---\n`;
47
+ }