@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,12 +1,50 @@
1
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
6
  import { searchDocuments } from "../lib/search.js";
6
7
  import { estimateTokens } from "../lib/markdown.js";
8
+ import { formatDocumentPath, isSourceRef, parseSourceTopicFilter } from "../lib/source-id.js";
9
+ import { ensureSourcesForRead } from "../lib/sources.js";
10
+ import { recordTelemetryEvent } from "../lib/telemetry.js";
7
11
  export function runSearch(options) {
8
12
  const workspace = loadWorkspace(options.cwd);
9
13
  const kind = options.kind ? assertDocumentKind(options.kind) : undefined;
14
+ const warnings = [];
15
+ const warnedAliases = new Set();
16
+ if (options.topic && isSourceRef(options.topic)) {
17
+ const parsedTopic = parseSourceTopicFilter(options.topic);
18
+ if (!workspace.sourcesByName.has(parsedTopic.alias)) {
19
+ throw new CliError(`Unknown source: @${parsedTopic.alias}`);
20
+ }
21
+ const cold = ensureSourcesForRead(workspace, [parsedTopic.alias]);
22
+ warnings.push(...cold.warnings);
23
+ if (cold.warnings.length > 0) {
24
+ warnedAliases.add(parsedTopic.alias);
25
+ }
26
+ const source = workspace.sourcesByName.get(parsedTopic.alias);
27
+ if (source && source.status !== "ready" && !warnedAliases.has(source.name)) {
28
+ warnedAliases.add(source.name);
29
+ warnings.push(`Source @${source.name} is unavailable: ${source.error ?? "no local snapshot"}.${source.remedy ? ` ${source.remedy}` : ""}`);
30
+ }
31
+ }
32
+ else if (!options.topic && workspace.sources.length > 0) {
33
+ const cold = ensureSourcesForRead(workspace);
34
+ warnings.push(...cold.warnings);
35
+ for (const fetchedAlias of cold.fetched) {
36
+ const source = workspace.sourcesByName.get(fetchedAlias);
37
+ if (source && source.status !== "ready") {
38
+ warnedAliases.add(fetchedAlias);
39
+ }
40
+ }
41
+ for (const source of workspace.sources) {
42
+ if (source.status !== "ready" && !warnedAliases.has(source.name)) {
43
+ warnedAliases.add(source.name);
44
+ warnings.push(`Source @${source.name} is unavailable: ${source.error ?? "no local snapshot"}.${source.remedy ? ` ${source.remedy}` : ""}`);
45
+ }
46
+ }
47
+ }
10
48
  const search = searchDocuments(workspace, options.query, {
11
49
  topic: options.topic,
12
50
  kind
@@ -16,20 +54,44 @@ export function runSearch(options) {
16
54
  estimate: (entry) => estimateTokens(JSON.stringify(toPayload(entry))),
17
55
  options
18
56
  });
57
+ const isExternalScopedSearch = Boolean(options.topic && isSourceRef(options.topic));
58
+ if (!isExternalScopedSearch) {
59
+ const localSearch = workspace.sourceDocuments.length > 0 && !options.topic
60
+ ? searchDocuments(workspace, options.query, {
61
+ kind,
62
+ includeSources: false,
63
+ useCache: false
64
+ })
65
+ : search;
66
+ recordTelemetryEvent(workspace.rootDir, {
67
+ type: "search",
68
+ query: options.query,
69
+ mode: localSearch.mode,
70
+ hitCount: localSearch.results.length,
71
+ docs: localSearch.results.slice(0, 10).map((entry) => entry.document.llmdocPath)
72
+ });
73
+ }
19
74
  if (options.json) {
20
75
  return {
21
76
  query: options.query,
22
77
  searchMode: search.mode,
23
78
  results: paginated.items.map(toPayload),
79
+ ...(warnings.length > 0 ? { warnings } : {}),
24
80
  pagination: paginationMetadata(paginated)
25
81
  };
26
82
  }
27
83
  const lines = [];
84
+ for (const warning of warnings) {
85
+ lines.push(`warning: ${warning}`);
86
+ }
87
+ if (warnings.length > 0) {
88
+ lines.push("");
89
+ }
28
90
  if (search.mode === "cjk-bigram-fallback") {
29
91
  lines.push("note: Chinese segmentation returned no matches; CJK bigram fallback was used.", "");
30
92
  }
31
93
  for (const entry of paginated.items) {
32
- lines.push(`llmdoc/${entry.document.llmdocPath} [${entry.document.frontmatter.kind}]`);
94
+ lines.push(`${formatDocumentPath(entry.document)} [${entry.document.frontmatter.kind}]`);
33
95
  lines.push(` ${entry.document.frontmatter.description}`);
34
96
  lines.push(` ${entry.snippet}`);
35
97
  lines.push("");
@@ -39,10 +101,11 @@ export function runSearch(options) {
39
101
  }
40
102
  function toPayload(entry) {
41
103
  return {
42
- path: `llmdoc/${entry.document.llmdocPath}`,
104
+ path: formatDocumentPath(entry.document),
43
105
  kind: entry.document.frontmatter.kind,
44
106
  description: entry.document.frontmatter.description,
45
107
  snippet: entry.snippet,
46
- score: entry.score
108
+ score: entry.score,
109
+ ...(entry.document.sourceName ? { source: entry.document.sourceName } : {})
47
110
  };
48
111
  }
@@ -4,13 +4,42 @@ import { CliError } from "../lib/errors.js";
4
4
  import { DEFAULT_SHOW_BUDGET } from "../lib/constants.js";
5
5
  import { formatPaginationSummary } from "../lib/format.js";
6
6
  import { estimateTokens } from "../lib/markdown.js";
7
+ import { formatDocumentPath, isSourceRef, parseSourceDocId } from "../lib/source-id.js";
8
+ import { ensureSourcesForRead } from "../lib/sources.js";
9
+ import { recordTelemetryEvent } from "../lib/telemetry.js";
7
10
  export function runShow(options) {
8
11
  const workspace = loadWorkspace(options.cwd);
9
- const documents = options.paths.map((rawPath) => {
10
- const normalized = rawPath.startsWith("llmdoc/") ? rawPath.slice("llmdoc/".length) : rawPath;
12
+ const requestedSourceAliases = new Set();
13
+ const parsedRequests = options.paths.map((rawPath) => {
14
+ if (isSourceRef(rawPath)) {
15
+ const parsed = parseSourceDocId(rawPath);
16
+ if (!workspace.sourcesByName.has(parsed.alias)) {
17
+ throw new CliError(`Unknown source: @${parsed.alias}`);
18
+ }
19
+ requestedSourceAliases.add(parsed.alias);
20
+ return { kind: "source", rawPath, parsed };
21
+ }
22
+ return { kind: "local", rawPath };
23
+ });
24
+ if (requestedSourceAliases.size > 0) {
25
+ ensureSourcesForRead(workspace, [...requestedSourceAliases]);
26
+ }
27
+ const documents = parsedRequests.map((request) => {
28
+ if (request.kind === "source") {
29
+ const source = workspace.sourcesByName.get(request.parsed.alias);
30
+ if (!source || source.status !== "ready") {
31
+ throw new CliError(`Source @${request.parsed.alias} is unavailable: ${source?.error ?? "no local snapshot"}.${source?.remedy ? ` ${source.remedy}` : ""}`);
32
+ }
33
+ const document = workspace.sourceDocumentsById.get(request.parsed.canonicalId);
34
+ if (!document) {
35
+ throw new CliError(`Document does not exist in @${request.parsed.alias}: ${request.parsed.canonicalId}`);
36
+ }
37
+ return document;
38
+ }
39
+ const normalized = request.rawPath.startsWith("llmdoc/") ? request.rawPath.slice("llmdoc/".length) : request.rawPath;
11
40
  const document = workspace.documentsByLlmdocPath.get(normalized);
12
41
  if (!document) {
13
- throw new CliError(`Document does not exist: ${rawPath}`);
42
+ throw new CliError(`Document does not exist: ${request.rawPath}`);
14
43
  }
15
44
  return document;
16
45
  });
@@ -22,6 +51,10 @@ export function runShow(options) {
22
51
  budget: options.budget ?? DEFAULT_SHOW_BUDGET
23
52
  }
24
53
  });
54
+ recordTelemetryEvent(workspace.rootDir, {
55
+ type: "show",
56
+ docs: result.items.filter((document) => !document.sourceName).map((document) => document.llmdocPath)
57
+ });
25
58
  if (options.json) {
26
59
  return {
27
60
  documents: result.items.map(toDocumentPayload),
@@ -30,7 +63,7 @@ export function runShow(options) {
30
63
  }
31
64
  const lines = [];
32
65
  for (const document of result.items) {
33
- lines.push(`=== llmdoc/${document.llmdocPath} [${document.frontmatter.kind}] ===`);
66
+ lines.push(`=== ${formatDocumentPath(document)} [${document.frontmatter.kind}] ===`);
34
67
  lines.push(document.body);
35
68
  lines.push("");
36
69
  }
@@ -39,9 +72,10 @@ export function runShow(options) {
39
72
  }
40
73
  function toDocumentPayload(document) {
41
74
  return {
42
- path: `llmdoc/${document.llmdocPath}`,
75
+ path: formatDocumentPath(document),
43
76
  kind: document.frontmatter.kind,
44
77
  description: document.frontmatter.description,
45
- body: document.body
78
+ body: document.body,
79
+ ...(document.sourceName ? { source: document.sourceName } : {})
46
80
  };
47
81
  }
@@ -1,29 +1,44 @@
1
1
  import { readRepositoryRevisionHealth } from "../lib/repository-health.js";
2
2
  import { computeGrowthState, analyzeDelta } from "../lib/state.js";
3
+ import { refreshGitSources, toSourceSummary, triggerBackgroundRefreshIfNeeded } from "../lib/sources.js";
3
4
  import { loadWorkspace } from "../lib/workspace.js";
5
+ import { formatSourcesSection } from "./tree.js";
4
6
  export function runStatus(options) {
5
7
  const workspace = loadWorkspace(options.cwd);
8
+ let refreshFailed = [];
9
+ if (options.refresh && workspace.sources.length > 0) {
10
+ refreshFailed = refreshGitSources(workspace, { force: true }).failed;
11
+ }
12
+ else if (workspace.sources.length > 0) {
13
+ triggerBackgroundRefreshIfNeeded(workspace);
14
+ }
6
15
  const delta = analyzeDelta(workspace);
7
16
  const growth = computeGrowthState(workspace);
8
17
  const relevantCommitsBehindHead = readRepositoryRevisionHealth(workspace.rootDir, workspace.meta?.baseline.revision ?? null, delta.git).relevantCommitsBehindHead;
18
+ const sourceSummaries = workspace.sources.map(toSourceSummary);
19
+ const exitCode = options.refresh && refreshFailed.length > 0 ? 1 : 0;
9
20
  if (options.json) {
10
21
  return {
11
- baseline: workspace.meta?.baseline.revision ?? null,
12
- head: delta.git.headRevision,
13
- commitsBehindHead: delta.git.baselineBehindHead,
14
- relevantCommitsBehindHead,
15
- degradedReason: delta.git.degradedReason,
16
- documents: {
17
- total: workspace.documents.length,
18
- impacted: delta.impacts.length,
19
- needsReview: delta.needsReview.length,
20
- dirty: delta.dirtyDocuments.length
21
- },
22
- unmapped: {
23
- committed: delta.unmappedCommittedPaths,
24
- dirty: delta.unmappedDirtyPaths
25
- },
26
- growth
22
+ exitCode,
23
+ output: {
24
+ baseline: workspace.meta?.baseline.revision ?? null,
25
+ head: delta.git.headRevision,
26
+ commitsBehindHead: delta.git.baselineBehindHead,
27
+ relevantCommitsBehindHead,
28
+ degradedReason: delta.git.degradedReason,
29
+ documents: {
30
+ total: workspace.documents.length,
31
+ impacted: delta.impacts.length,
32
+ needsReview: delta.needsReview.length,
33
+ dirty: delta.dirtyDocuments.length
34
+ },
35
+ unmapped: {
36
+ committed: delta.unmappedCommittedPaths,
37
+ dirty: delta.unmappedDirtyPaths
38
+ },
39
+ growth,
40
+ ...(sourceSummaries.length > 0 ? { sources: sourceSummaries } : {})
41
+ }
27
42
  };
28
43
  }
29
44
  const baseline = workspace.meta?.baseline.revision ?? "missing";
@@ -36,16 +51,29 @@ export function runStatus(options) {
36
51
  `baseline: ${baseline} (${behind})`,
37
52
  `documents: ${workspace.documents.length} total / ${delta.impacts.length} impacted / ${delta.needsReview.length} needs-review / ${delta.dirtyDocuments.length} dirty`
38
53
  ];
54
+ const unparsedCount = workspace.unparsedDocPaths?.size ?? 0;
55
+ if (unparsedCount > 0) {
56
+ lines.push(`warning: ${unparsedCount} local document(s) failed to parse and were omitted; run \`npx -y @tokenroll/llmdoc validate\` for details`);
57
+ }
39
58
  if (unmapped.length > 0) {
40
59
  const shown = unmapped.slice(0, 5);
41
60
  const rest = unmapped.length - shown.length;
42
61
  lines.push(`unmapped changes (${unmapped.length}): ${shown.join(", ")}${rest > 0 ? ` … +${rest} more (use --json for all)` : ""}`);
43
62
  }
44
63
  lines.push(growthLabel);
64
+ if (workspace.sources.length > 0) {
65
+ lines.push("", ...formatSourcesSection(workspace.sources));
66
+ }
67
+ if (refreshFailed.length > 0) {
68
+ lines.push("", `refresh failed (${refreshFailed.length}): ${refreshFailed.map((entry) => `@${entry.name} (${entry.error})`).join("; ")}`);
69
+ }
45
70
  if (delta.git.degradedReason) {
46
71
  lines.push(`degraded: ${delta.git.degradedReason}`);
47
72
  }
48
- return lines.join("\n");
73
+ return {
74
+ exitCode,
75
+ output: lines.join("\n")
76
+ };
49
77
  }
50
78
  function formatBehindLabel(commitsBehindHead, relevantCommitsBehindHead) {
51
79
  if (commitsBehindHead === null) {
@@ -2,11 +2,15 @@ import { paginate, paginationMetadata } from "../lib/pagination.js";
2
2
  import { loadWorkspace } from "../lib/workspace.js";
3
3
  import { formatPaginationSummary } from "../lib/format.js";
4
4
  import { estimateTokens } from "../lib/markdown.js";
5
+ import { formatDocumentPath } from "../lib/source-id.js";
6
+ import { toSourceSummary } from "../lib/sources.js";
5
7
  export function runTree(options) {
6
8
  const workspace = loadWorkspace(options.cwd);
9
+ const sourceSummaries = workspace.sources.map(toSourceSummary);
7
10
  if (options.docs) {
11
+ const allDocuments = [...workspace.documents, ...workspace.sourceDocuments];
8
12
  const result = paginate({
9
- items: workspace.documents,
13
+ items: allDocuments,
10
14
  estimate: (document) => estimateTokens(JSON.stringify(toDocumentSummary(document))),
11
15
  options
12
16
  });
@@ -14,14 +18,28 @@ export function runTree(options) {
14
18
  return {
15
19
  root: "llmdoc",
16
20
  documents: result.items.map(toDocumentSummary),
21
+ ...(sourceSummaries.length > 0 ? { sources: sourceSummaries } : {}),
17
22
  pagination: paginationMetadata(result)
18
23
  };
19
24
  }
20
25
  const lines = [`llmdoc/ (${workspace.documents.length} docs, ~${workspace.documents.reduce((sum, document) => sum + document.estimatedTokens, 0)} tokens)`, ""];
21
- for (const document of result.items) {
26
+ const localItems = result.items.filter((document) => !document.sourceName);
27
+ const sourceItems = result.items.filter((document) => Boolean(document.sourceName));
28
+ for (const document of localItems) {
22
29
  lines.push(` ${document.llmdocPath} [${document.frontmatter.kind}]`);
23
30
  lines.push(` ${document.frontmatter.description}`);
24
31
  }
32
+ if (sourceItems.length > 0) {
33
+ const sourceTokens = sourceItems.reduce((sum, document) => sum + document.estimatedTokens, 0);
34
+ lines.push("", `external sources/ (${sourceItems.length} shown of ${workspace.sourceDocuments.length} docs, ~${sourceTokens} tokens)`, "");
35
+ for (const document of sourceItems) {
36
+ lines.push(` ${document.llmdocPath} [${document.frontmatter.kind}]`);
37
+ lines.push(` ${document.frontmatter.description}`);
38
+ }
39
+ }
40
+ if (workspace.sources.length > 0) {
41
+ lines.push("", ...formatSourcesSection(workspace.sources));
42
+ }
25
43
  lines.push("", ...formatPaginationSummary(result));
26
44
  return lines.join("\n");
27
45
  }
@@ -53,6 +71,7 @@ export function runTree(options) {
53
71
  .filter((entry) => entry.type === "rootSingleton")
54
72
  .map((entry) => toRootSingletonSummary(entry.document)),
55
73
  topics: result.items.filter((entry) => entry.type === "topic").map((entry) => toTopicSummary(entry.topic)),
74
+ ...(sourceSummaries.length > 0 ? { sources: sourceSummaries } : {}),
56
75
  pagination: paginationMetadata(result)
57
76
  };
58
77
  }
@@ -67,21 +86,90 @@ export function runTree(options) {
67
86
  lines.push(` ${entry.topic.topic}/ (${entry.topic.docs.length} docs, ~${entry.topic.estimatedTokens} tokens)`);
68
87
  lines.push(` ${entry.topic.summary}`);
69
88
  }
89
+ if (workspace.sources.length > 0) {
90
+ lines.push("", ...formatSourcesSection(workspace.sources));
91
+ }
70
92
  lines.push("", ...formatPaginationSummary(result));
71
- lines.push("hint: use `npx @tokenroll/llmdoc tree --docs` to expand documents; use `... index --topic <t>` for metadata");
93
+ if (workspace.sources.length > 0) {
94
+ const firstSource = workspace.sources[0].name;
95
+ lines.push(`hint: use \`npx -y @tokenroll/llmdoc tree --docs\` to expand documents; \`... index --topic @${firstSource}\` to inspect a source; \`... status --refresh\` to sync git sources`);
96
+ }
97
+ else {
98
+ lines.push("hint: use `npx -y @tokenroll/llmdoc tree --docs` to expand documents; use `... index --topic <t>` for metadata");
99
+ }
72
100
  return lines.join("\n");
73
101
  }
102
+ export function formatSourcesSection(sources) {
103
+ const lines = [`sources (${sources.length} configured)`];
104
+ for (const source of sources) {
105
+ const spec = source.kind === "git"
106
+ ? `git ${source.target}${source.ref ? `#${source.ref}` : ""}${source.dir ? `:${source.dir}` : ""}`
107
+ : `path ${source.target}${source.dir ? `:${source.dir}` : ""}`;
108
+ if (source.status === "ready") {
109
+ const details = [`${source.documents.length} doc(s)`];
110
+ if (source.kind === "git") {
111
+ if (source.lastSyncedAt) {
112
+ details.push(`synced ${formatRelativeAge(source.lastSyncedAt)}`);
113
+ }
114
+ if (source.stale) {
115
+ details.push("stale");
116
+ }
117
+ }
118
+ else if (source.isSubmodule) {
119
+ details.push("submodule");
120
+ }
121
+ if (source.revision) {
122
+ details.push(source.pinned ? `pinned at ${source.revision.slice(0, 7)}` : `at ${source.revision.slice(0, 7)}`);
123
+ }
124
+ lines.push(` @${source.name} ${spec} (${details.join(", ")})`);
125
+ if (source.error) {
126
+ lines.push(` warning: last refresh failed: ${source.error}`);
127
+ }
128
+ }
129
+ else {
130
+ lines.push(` @${source.name} ${spec} [${source.status}]`);
131
+ if (source.error) {
132
+ lines.push(` reason: ${source.error}`);
133
+ }
134
+ if (source.remedy) {
135
+ lines.push(` remedy: ${source.remedy}`);
136
+ }
137
+ }
138
+ }
139
+ return lines;
140
+ }
141
+ function formatRelativeAge(isoTimestamp) {
142
+ const timestamp = Date.parse(isoTimestamp);
143
+ if (Number.isNaN(timestamp)) {
144
+ return isoTimestamp;
145
+ }
146
+ const diffMs = Math.max(0, Date.now() - timestamp);
147
+ const diffMinutes = Math.floor(diffMs / 60_000);
148
+ if (diffMinutes < 1) {
149
+ return "just now";
150
+ }
151
+ if (diffMinutes < 60) {
152
+ return `${diffMinutes}m ago`;
153
+ }
154
+ const diffHours = Math.floor(diffMinutes / 60);
155
+ if (diffHours < 48) {
156
+ return `${diffHours}h ago`;
157
+ }
158
+ const diffDays = Math.floor(diffHours / 24);
159
+ return `${diffDays}d ago`;
160
+ }
74
161
  function toDocumentSummary(document) {
75
162
  return {
76
- path: `llmdoc/${document.llmdocPath}`,
163
+ path: formatDocumentPath(document),
77
164
  kind: document.frontmatter.kind,
78
165
  description: document.frontmatter.description,
79
- topic: document.topic
166
+ topic: document.topic,
167
+ ...(document.sourceName ? { source: document.sourceName } : {})
80
168
  };
81
169
  }
82
170
  function toRootSingletonSummary(document) {
83
171
  return {
84
- path: `llmdoc/${document.llmdocPath}`,
172
+ path: formatDocumentPath(document),
85
173
  kind: document.frontmatter.kind,
86
174
  description: document.frontmatter.description
87
175
  };