@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.
@@ -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,7 +1,13 @@
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) {
@@ -2,7 +2,9 @@ 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 { formatCompactPreloadIndex, formatStartupPreloadDocuments, loadLlmdocConfig } from "../lib/config.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";
6
8
  // Minimal SessionStart guidance; the complete protocol remains in the llmdoc skill.
7
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.";
8
10
  export function runHook(options) {
@@ -35,6 +37,14 @@ function runSessionStart(cwd, stdin) {
35
37
  const lifecycle = source === "compact" ? "compact re-entry" : "cold start";
36
38
  try {
37
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
+ }
38
48
  const delta = analyzeDelta(workspace);
39
49
  const signal = summarizeHookDelta(delta);
40
50
  const pendingLessonCandidates = countPendingLessonCandidates(cwd);
@@ -69,9 +79,15 @@ function runSessionStart(cwd, stdin) {
69
79
  context.push(SESSION_START_GUIDANCE);
70
80
  }
71
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
+ }
72
88
  const preloaded = source === "compact"
73
89
  ? formatCompactPreloadIndex(startupConfig.preloadPaths)
74
- : formatStartupPreloadDocuments(startupConfig.preloadPaths.map((preloadPath) => workspace.documentsByLlmdocPath.get(preloadPath)));
90
+ : formatColdStartupPreload(workspace);
75
91
  if (preloaded) {
76
92
  context.push(preloaded);
77
93
  }
@@ -87,17 +103,74 @@ function runSessionStart(cwd, stdin) {
87
103
  return context.join("\n\n");
88
104
  }
89
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
+ }
90
149
  function appendStartupConfigIssues(context, startupConfig) {
91
150
  const errors = startupConfig.issues.filter((issue) => issue.severity === "error");
92
151
  const warnings = startupConfig.issues.filter((issue) => issue.severity === "warning");
93
152
  if (errors.length > 0) {
94
- context.push(startupConfig.config
95
- ? "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."
96
- : "llmdoc.config.json could not be applied; preload was skipped and the default skill reminder remains active. Run npx @tokenroll/llmdoc validate for details.");
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
+ }
97
165
  }
98
- if (warnings.length > 0) {
166
+ const duplicateWarnings = warnings.filter((issue) => issue.code === "config.startup.preload.duplicate");
167
+ if (duplicateWarnings.length > 0) {
99
168
  context.push("llmdoc.config.json has warnings; normalized duplicate startup.preload entries were ignored. Run npx @tokenroll/llmdoc validate for details.");
100
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.`);
173
+ }
101
174
  }
102
175
  function runStop(cwd) {
103
176
  try {
@@ -1,14 +1,51 @@
1
- import { paginate } from "../lib/pagination.js";
1
+ import { paginate, paginationMetadata } from "../lib/pagination.js";
2
2
  import { assertDocumentKind } from "../lib/doc-shape.js";
3
+ import { CliError } from "../lib/errors.js";
3
4
  import { loadWorkspace } from "../lib/workspace.js";
4
5
  import { formatPaginationSummary } from "../lib/format.js";
5
- import { paginationMetadata } from "../lib/pagination.js";
6
6
  import { estimateTokens } from "../lib/markdown.js";
7
+ import { formatDocumentPath, isSourceRef, matchesDocumentTopic, parseSourceTopicFilter } from "../lib/source-id.js";
8
+ import { ensureSourcesForRead } from "../lib/sources.js";
7
9
  export function runIndex(options) {
8
10
  const workspace = loadWorkspace(options.cwd);
9
11
  const kind = options.kind ? assertDocumentKind(options.kind) : undefined;
10
- const filtered = workspace.documents.filter((document) => {
11
- if (options.topic && document.topic !== options.topic) {
12
+ const warnings = [];
13
+ const warnedAliases = new Set();
14
+ if (options.topic && isSourceRef(options.topic)) {
15
+ const parsedTopic = parseSourceTopicFilter(options.topic);
16
+ if (!workspace.sourcesByName.has(parsedTopic.alias)) {
17
+ throw new CliError(`Unknown source: @${parsedTopic.alias}`);
18
+ }
19
+ const cold = ensureSourcesForRead(workspace, [parsedTopic.alias]);
20
+ warnings.push(...cold.warnings);
21
+ if (cold.warnings.length > 0) {
22
+ warnedAliases.add(parsedTopic.alias);
23
+ }
24
+ const source = workspace.sourcesByName.get(parsedTopic.alias);
25
+ if (source && source.status !== "ready" && !warnedAliases.has(source.name)) {
26
+ warnedAliases.add(source.name);
27
+ warnings.push(`Source @${source.name} is unavailable: ${source.error ?? "no local snapshot"}.${source.remedy ? ` ${source.remedy}` : ""}`);
28
+ }
29
+ }
30
+ else if (!options.topic && workspace.sources.length > 0) {
31
+ const cold = ensureSourcesForRead(workspace);
32
+ warnings.push(...cold.warnings);
33
+ for (const fetchedAlias of cold.fetched) {
34
+ const source = workspace.sourcesByName.get(fetchedAlias);
35
+ if (source && source.status !== "ready") {
36
+ warnedAliases.add(fetchedAlias);
37
+ }
38
+ }
39
+ for (const source of workspace.sources) {
40
+ if (source.status !== "ready" && !warnedAliases.has(source.name)) {
41
+ warnedAliases.add(source.name);
42
+ warnings.push(`Source @${source.name} is unavailable: ${source.error ?? "no local snapshot"}.${source.remedy ? ` ${source.remedy}` : ""}`);
43
+ }
44
+ }
45
+ }
46
+ const allDocuments = [...workspace.documents, ...workspace.sourceDocuments];
47
+ const filtered = allDocuments.filter((document) => {
48
+ if (options.topic && !matchesDocumentTopic(document, options.topic)) {
12
49
  return false;
13
50
  }
14
51
  if (kind && document.frontmatter.kind !== kind) {
@@ -24,12 +61,19 @@ export function runIndex(options) {
24
61
  if (options.json) {
25
62
  return {
26
63
  documents: result.items.map(toPayload),
64
+ ...(warnings.length > 0 ? { warnings } : {}),
27
65
  pagination: paginationMetadata(result)
28
66
  };
29
67
  }
30
68
  const lines = [];
69
+ for (const warning of warnings) {
70
+ lines.push(`warning: ${warning}`);
71
+ }
72
+ if (warnings.length > 0 && result.items.length > 0) {
73
+ lines.push("");
74
+ }
31
75
  for (const document of result.items) {
32
- lines.push(`llmdoc/${document.llmdocPath} [${document.frontmatter.kind}]`);
76
+ lines.push(`${formatDocumentPath(document)} [${document.frontmatter.kind}]`);
33
77
  lines.push(` ${document.frontmatter.description}`);
34
78
  if (document.frontmatter.relations?.requires?.length) {
35
79
  lines.push(` requires: ${document.frontmatter.relations.requires.join(", ")}`);
@@ -44,10 +88,11 @@ export function runIndex(options) {
44
88
  }
45
89
  function toPayload(document) {
46
90
  return {
47
- path: `llmdoc/${document.llmdocPath}`,
91
+ path: formatDocumentPath(document),
48
92
  kind: document.frontmatter.kind,
49
93
  description: document.frontmatter.description,
50
94
  relations: document.frontmatter.relations ?? {},
51
- code: document.frontmatter.code ?? {}
95
+ code: document.frontmatter.code ?? {},
96
+ ...(document.sourceName ? { source: document.sourceName } : {})
52
97
  };
53
98
  }
@@ -7,10 +7,18 @@ import { gitMove, gitRestorePaths } from "../lib/git.js";
7
7
  import { updateDocumentForMove, writeFileIfChanged } from "../lib/rewrite.js";
8
8
  import { loadWorkspace } from "../lib/workspace.js";
9
9
  import { LLMDOC_CONFIG_FILENAME, rewriteStartupPreloadForMove } from "../lib/config.js";
10
+ import { isSourceRef } from "../lib/source-id.js";
10
11
  export function runMove(options) {
12
+ if (isSourceRef(options.from) || isSourceRef(options.to)) {
13
+ throw new CliError("External source documents (@...) are read-only and cannot be moved with mv.");
14
+ }
11
15
  const rootDir = findProjectRoot(options.cwd);
12
16
  const fromRepoPath = normalizeRepoRelativePath(options.from.startsWith("llmdoc/") ? options.from : `llmdoc/${options.from}`);
13
17
  const toRepoPath = normalizeRepoRelativePath(options.to.startsWith("llmdoc/") ? options.to : `llmdoc/${options.to}`);
18
+ const toFirstSegment = toRepoPath.startsWith("llmdoc/") ? toRepoPath.slice("llmdoc/".length).split("/")[0] : "";
19
+ if (toFirstSegment?.startsWith("@")) {
20
+ throw new CliError(`Local topic names cannot start with "@", which is reserved for external sources: ${toFirstSegment}`);
21
+ }
14
22
  const fromAbsolutePath = resolveInsideRoot(rootDir, fromRepoPath);
15
23
  if (!fromRepoPath.startsWith("llmdoc/") || !toRepoPath.startsWith("llmdoc/")) {
16
24
  throw new CliError("mv supports moves only within llmdoc/.");
@@ -4,12 +4,19 @@ import { parseDocTargetShape, assertDocKindMatchesShape, assertDocumentKind } fr
4
4
  import { CliError } from "../lib/errors.js";
5
5
  import { ensureDirectory, findProjectRootForNew, normalizeRepoRelativePath, resolveInsideRoot } from "../lib/fs.js";
6
6
  import { packageRootFromImport } from "../lib/package-root.js";
7
+ import { isSourceRef } from "../lib/source-id.js";
7
8
  import { loadWorkspace } from "../lib/workspace.js";
8
9
  export function runNew(options) {
10
+ if (isSourceRef(options.path)) {
11
+ throw new CliError(`External source documents (@...) are read-only and cannot be created with new: ${options.path}`);
12
+ }
9
13
  const rootDir = findProjectRootForNew(options.cwd);
10
14
  const repoRelativePath = normalizeDocDestination(options.path);
11
15
  const kind = assertDocumentKind(options.kind);
12
16
  const shape = parseDocTargetShape(repoRelativePath);
17
+ if (shape.topic?.startsWith("@")) {
18
+ throw new CliError(`Local topic names cannot start with "@", which is reserved for external sources: ${shape.topic}`);
19
+ }
13
20
  assertDocKindMatchesShape(shape);
14
21
  const absolutePath = resolveInsideRoot(rootDir, repoRelativePath, { allowMissing: true });
15
22
  if (fs.existsSync(absolutePath)) {
@@ -1,4 +1,5 @@
1
1
  import { FRAGMENT_TOKEN_THRESHOLD } from "../lib/constants.js";
2
+ import { isSourceRef } from "../lib/source-id.js";
2
3
  import { computeGrowthState } from "../lib/state.js";
3
4
  import { loadWorkspace } from "../lib/workspace.js";
4
5
  export function runPrune(options) {
@@ -11,7 +12,7 @@ export function runPrune(options) {
11
12
  const growth = computeGrowthState(workspace);
12
13
  const duplicateCandidates = findDuplicateCandidates(workspace.documents);
13
14
  const mergeCandidates = findMergeCandidates(workspace.documents);
14
- const startupPreloads = workspace.llmdocConfig.preloadPaths.map((preloadPath) => `llmdoc/${preloadPath}`);
15
+ const startupPreloads = workspace.llmdocConfig.preloadPaths.map((preloadPath) => isSourceRef(preloadPath) ? preloadPath : `llmdoc/${preloadPath}`);
15
16
  if (options.json) {
16
17
  return {
17
18
  status: "dry_run",