@mrclrchtr/supi-code-intelligence 9.1.1 → 10.0.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 (94) hide show
  1. package/README.md +24 -8
  2. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  3. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  4. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  5. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  6. package/node_modules/@mrclrchtr/supi-lsp/package.json +3 -3
  7. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager-workspace-symbol.ts +29 -0
  8. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager.ts +25 -22
  9. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  10. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  11. package/node_modules/@mrclrchtr/supi-tree-sitter/package.json +3 -3
  12. package/node_modules/ignore/LICENSE-MIT +21 -0
  13. package/node_modules/ignore/README.md +501 -0
  14. package/node_modules/ignore/index.d.ts +81 -0
  15. package/node_modules/ignore/index.js +1566 -0
  16. package/node_modules/ignore/legacy.js +1346 -0
  17. package/node_modules/ignore/package.json +93 -0
  18. package/node_modules/smol-toml/LICENSE +24 -0
  19. package/node_modules/smol-toml/README.md +605 -0
  20. package/node_modules/smol-toml/dist/date.d.ts +41 -0
  21. package/node_modules/smol-toml/dist/date.js +156 -0
  22. package/node_modules/smol-toml/dist/error.d.ts +37 -0
  23. package/node_modules/smol-toml/dist/error.js +67 -0
  24. package/node_modules/smol-toml/dist/extract.js +293 -0
  25. package/node_modules/smol-toml/dist/index.cjs +771 -0
  26. package/node_modules/smol-toml/dist/index.d.ts +44 -0
  27. package/node_modules/smol-toml/dist/index.js +34 -0
  28. package/node_modules/smol-toml/dist/parse.d.ts +73 -0
  29. package/node_modules/smol-toml/dist/parse.js +164 -0
  30. package/node_modules/smol-toml/dist/primitive.js +151 -0
  31. package/node_modules/smol-toml/dist/stringify.d.ts +32 -0
  32. package/node_modules/smol-toml/dist/stringify.js +219 -0
  33. package/node_modules/smol-toml/dist/struct.js +156 -0
  34. package/node_modules/smol-toml/dist/util.d.ts +43 -0
  35. package/node_modules/smol-toml/dist/util.js +57 -0
  36. package/node_modules/smol-toml/package.json +68 -0
  37. package/package.json +9 -5
  38. package/src/analysis/evidence.ts +2 -0
  39. package/src/analysis/target/symbol.ts +19 -8
  40. package/src/analysis/target/types.ts +2 -0
  41. package/src/analysis/workspace/exclusions.ts +35 -0
  42. package/src/analysis/workspace/git.ts +130 -0
  43. package/src/analysis/workspace/go-parser.ts +330 -0
  44. package/src/analysis/workspace/go.ts +154 -0
  45. package/src/analysis/workspace/index.ts +28 -0
  46. package/src/analysis/workspace/inventory.ts +316 -0
  47. package/src/analysis/workspace/membership.ts +223 -0
  48. package/src/analysis/workspace/metadata-types.ts +56 -0
  49. package/src/analysis/workspace/metadata-utils.ts +60 -0
  50. package/src/analysis/workspace/metadata.ts +148 -0
  51. package/src/analysis/workspace/node.ts +214 -0
  52. package/src/analysis/workspace/observe.ts +161 -0
  53. package/src/analysis/workspace/paths.ts +65 -0
  54. package/src/analysis/workspace/python.ts +158 -0
  55. package/src/analysis/workspace/relationships.ts +87 -0
  56. package/src/analysis/workspace/rust.ts +238 -0
  57. package/src/analysis/workspace/safe-path.ts +20 -0
  58. package/src/analysis/workspace/types.ts +245 -0
  59. package/src/app/app.ts +1 -0
  60. package/src/config.ts +4 -4
  61. package/src/extension.ts +16 -49
  62. package/src/overview/budget.ts +23 -0
  63. package/src/overview/collect.ts +22 -0
  64. package/src/session/orientation/workspace-context.ts +166 -0
  65. package/src/session/orientation-types.ts +8 -1
  66. package/src/session/orientation-workflow.ts +16 -3
  67. package/src/session/session.ts +2 -3
  68. package/src/session/target-workflow.ts +2 -0
  69. package/src/tool/code_find/execute.ts +1 -1
  70. package/src/tool/code_find/result.ts +10 -3
  71. package/src/tool/code_graph/result.ts +7 -2
  72. package/src/tool/code_orientation/execute.ts +8 -1
  73. package/src/tool/code_orientation/markdown.ts +58 -8
  74. package/src/tool/code_orientation/result.ts +17 -5
  75. package/src/tool/code_orientation/workspace-format.ts +74 -0
  76. package/src/tool/code_orientation/workspace-instructions.ts +105 -0
  77. package/src/tool/code_orientation/workspace-output.ts +118 -0
  78. package/src/tool/code_orientation/workspace-projects.ts +177 -0
  79. package/src/tool/code_orientation/workspace-sections.ts +217 -0
  80. package/src/tool/code_resolve/execute.ts +1 -1
  81. package/src/tool/code_resolve/markdown.ts +4 -1
  82. package/src/tool/code_resolve/result.ts +14 -2
  83. package/src/tool/register.ts +2 -0
  84. package/src/tool/result/candidate-row.ts +22 -0
  85. package/src/tool/result/display.ts +6 -0
  86. package/src/tool/result/errors.ts +12 -0
  87. package/src/tool/result/types.ts +2 -0
  88. package/src/types/execution.ts +2 -0
  89. package/src/ui/tui/candidate-disclosure.ts +43 -0
  90. package/src/ui/tui/candidate-selection.ts +24 -5
  91. package/src/ui/tui/common.ts +3 -0
  92. package/src/overview/overview-data.ts +0 -154
  93. package/src/overview/overview.ts +0 -91
  94. package/src/overview/types.ts +0 -23
@@ -0,0 +1,148 @@
1
+ /** Metadata document reading and format-specific parsing. */
2
+
3
+ import { constants, promises as fs } from "node:fs";
4
+ import * as path from "node:path";
5
+ import type { CodeRequestControl } from "@mrclrchtr/supi-code-runtime/api";
6
+ import { parse as parseToml } from "smol-toml";
7
+ import { parseDocument } from "yaml";
8
+ import type { MetadataReadResult, ParsedDocument } from "./metadata-types.ts";
9
+ import { isRecord, issue } from "./metadata-utils.ts";
10
+ import { errorMessage, relativeDirectory } from "./paths.ts";
11
+ import { assertUnlinkedPath } from "./safe-path.ts";
12
+ import type {
13
+ InventoryEntry,
14
+ MetadataDocument,
15
+ MetadataDocumentKind,
16
+ MetadataIssue,
17
+ } from "./types.ts";
18
+
19
+ const MAX_METADATA_BYTES = 1024 * 1024;
20
+
21
+ const KIND_BY_BASENAME = new Map<string, MetadataDocumentKind>([
22
+ ["package.json", "package-json"],
23
+ ["pnpm-workspace.yaml", "pnpm-workspace"],
24
+ ["pyproject.toml", "pyproject"],
25
+ ["Cargo.toml", "cargo"],
26
+ ["go.mod", "go-mod"],
27
+ ["go.work", "go-work"],
28
+ ]);
29
+
30
+ interface ReadOutcome {
31
+ readonly document: MetadataDocument;
32
+ readonly parsed: ParsedDocument | null;
33
+ readonly issue: MetadataIssue | null;
34
+ }
35
+
36
+ /** Read every eligible metadata file in inventory order without following links. */
37
+ export async function readMetadataDocuments(
38
+ root: string,
39
+ entries: readonly InventoryEntry[],
40
+ control: CodeRequestControl | undefined,
41
+ ): Promise<MetadataReadResult> {
42
+ const documents: MetadataDocument[] = [];
43
+ const parsed: ParsedDocument[] = [];
44
+ const issues: MetadataIssue[] = [];
45
+ let deadlineReached = false;
46
+ for (const entry of entries) {
47
+ const kind = KIND_BY_BASENAME.get(path.posix.basename(entry.path));
48
+ if (!kind) continue;
49
+ if (deadlineReachedAt(control)) {
50
+ deadlineReached = true;
51
+ break;
52
+ }
53
+ const outcome = await readEntry(root, entry, kind);
54
+ documents.push(outcome.document);
55
+ if (outcome.parsed) parsed.push(outcome.parsed);
56
+ if (outcome.issue) issues.push(outcome.issue);
57
+ }
58
+ return { documents, parsed, issues, deadlineReached };
59
+ }
60
+
61
+ async function readEntry(
62
+ root: string,
63
+ entry: InventoryEntry,
64
+ kind: MetadataDocumentKind,
65
+ ): Promise<ReadOutcome> {
66
+ if (entry.kind === "symlink")
67
+ return skipped(entry.path, kind, "Symbolic-link metadata is not read.");
68
+ const absolutePath = path.join(root, ...entry.path.split("/"));
69
+ try {
70
+ await assertUnlinkedPath(root, entry.path);
71
+ const stats = await fs.lstat(absolutePath);
72
+ if (stats.isSymbolicLink()) {
73
+ return skipped(entry.path, kind, "Symbolic-link metadata is not read.");
74
+ }
75
+ if (!stats.isFile()) return skipped(entry.path, kind, "Metadata path is not a regular file.");
76
+ if (stats.size > MAX_METADATA_BYTES)
77
+ return failed(entry.path, kind, "Metadata exceeds the 1 MiB file-size limit.");
78
+ const file = await fs.open(absolutePath, constants.O_RDONLY | constants.O_NOFOLLOW);
79
+ try {
80
+ const buffer = Buffer.alloc(MAX_METADATA_BYTES + 1);
81
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
82
+ if (bytesRead > MAX_METADATA_BYTES)
83
+ return failed(entry.path, kind, "Metadata exceeds the 1 MiB file-size limit.");
84
+ return parseText(entry.path, kind, buffer.toString("utf8", 0, bytesRead));
85
+ } finally {
86
+ await file.close();
87
+ }
88
+ } catch (error) {
89
+ return failed(entry.path, kind, `Could not read metadata: ${errorMessage(error)}`);
90
+ }
91
+ }
92
+
93
+ function parseText(relativePath: string, kind: MetadataDocumentKind, text: string): ReadOutcome {
94
+ try {
95
+ if (kind === "package-json") {
96
+ const value: unknown = JSON.parse(text);
97
+ if (!isRecord(value))
98
+ return failed(relativePath, kind, "package.json must contain an object.");
99
+ return complete(relativePath, kind, value);
100
+ }
101
+ if (kind === "pnpm-workspace") {
102
+ const document = parseDocument(text);
103
+ if (document.errors.length > 0) {
104
+ return failed(relativePath, kind, `Could not parse YAML: ${document.errors[0]?.message}`);
105
+ }
106
+ return complete(relativePath, kind, document.toJS());
107
+ }
108
+ if (kind === "go-mod" || kind === "go-work") return complete(relativePath, kind, text);
109
+ return complete(relativePath, kind, parseToml(text));
110
+ } catch (error) {
111
+ return failed(relativePath, kind, `Could not parse metadata: ${errorMessage(error)}`);
112
+ }
113
+ }
114
+
115
+ function complete(relativePath: string, kind: MetadataDocumentKind, data: unknown): ReadOutcome {
116
+ return {
117
+ document: { path: relativePath, kind, status: "parsed", reason: null },
118
+ parsed: { path: relativePath, kind, directory: relativeDirectory(relativePath), data },
119
+ issue: null,
120
+ };
121
+ }
122
+
123
+ function failed(relativePath: string, kind: MetadataDocumentKind, reason: string): ReadOutcome {
124
+ return {
125
+ document: { path: relativePath, kind, status: "failed", reason },
126
+ parsed: null,
127
+ issue: issue(relativePath, null, "malformed", reason),
128
+ };
129
+ }
130
+
131
+ function skipped(relativePath: string, kind: MetadataDocumentKind, reason: string): ReadOutcome {
132
+ return {
133
+ document: { path: relativePath, kind, status: "skipped", reason },
134
+ parsed: null,
135
+ issue: issue(
136
+ relativePath,
137
+ null,
138
+ reason.includes("Symbolic-link") ? "symlink" : "unsupported",
139
+ reason,
140
+ ),
141
+ };
142
+ }
143
+
144
+ function deadlineReachedAt(control: CodeRequestControl | undefined): boolean {
145
+ control?.signal?.throwIfAborted();
146
+ const deadline = control?.deadline;
147
+ return typeof deadline === "number" && Number.isFinite(deadline) && Date.now() >= deadline;
148
+ }
@@ -0,0 +1,214 @@
1
+ /** package.json and Node workspace declaration readers. */
2
+
3
+ import type { DocumentContribution, ParsedDocument, WorkspaceConfig } from "./metadata-types.ts";
4
+ import {
5
+ baseProject,
6
+ childField,
7
+ isRecord,
8
+ issue,
9
+ stringArray,
10
+ stringValue,
11
+ } from "./metadata-utils.ts";
12
+ import type { DeclaredDependency, DeclaredPath, MetadataIssue } from "./types.ts";
13
+
14
+ const DEPENDENCY_FIELDS = [
15
+ "dependencies",
16
+ "devDependencies",
17
+ "optionalDependencies",
18
+ "peerDependencies",
19
+ ] as const;
20
+
21
+ /** Read one package.json or pnpm-workspace.yaml document. */
22
+ export function readNodeDocument(document: ParsedDocument): DocumentContribution {
23
+ if (document.kind === "pnpm-workspace") return readPnpmWorkspace(document);
24
+ if (!isRecord(document.data)) {
25
+ return {
26
+ project: null,
27
+ workspace: null,
28
+ issues: [issue(document.path, null, "malformed", "package.json must contain an object.")],
29
+ };
30
+ }
31
+ const issues: MetadataIssue[] = [];
32
+ const project = baseProject({
33
+ manifestPath: document.path,
34
+ kind: "node-package",
35
+ directory: document.directory,
36
+ name: stringValue(document.data.name),
37
+ nameField: stringValue(document.data.name) === null ? null : "name",
38
+ description: stringValue(document.data.description),
39
+ descriptionField: stringValue(document.data.description) === null ? null : "description",
40
+ });
41
+ return {
42
+ project: {
43
+ ...project,
44
+ declaredPaths: collectNodePaths(document.data, document.path, issues),
45
+ dependencies: collectNodeDependencies(document.data, document.path, issues),
46
+ },
47
+ workspace: readPackageWorkspaces(document, issues),
48
+ issues,
49
+ };
50
+ }
51
+
52
+ function readPnpmWorkspace(document: ParsedDocument): DocumentContribution {
53
+ if (!isRecord(document.data)) {
54
+ return {
55
+ project: null,
56
+ workspace: null,
57
+ issues: [
58
+ issue(document.path, null, "malformed", "pnpm-workspace.yaml must contain a mapping."),
59
+ ],
60
+ };
61
+ }
62
+ if (!Object.hasOwn(document.data, "packages")) {
63
+ return { project: null, workspace: null, issues: [] };
64
+ }
65
+ const patterns = stringArray(document.data.packages);
66
+ if (!patterns) {
67
+ return {
68
+ project: null,
69
+ workspace: null,
70
+ issues: [
71
+ issue(
72
+ document.path,
73
+ "packages",
74
+ "unsupported",
75
+ "pnpm-workspace.yaml#packages must be a string array.",
76
+ ),
77
+ ],
78
+ };
79
+ }
80
+ return {
81
+ project: null,
82
+ workspace: {
83
+ kind: "node-workspace",
84
+ manifestPath: document.path,
85
+ directory: document.directory,
86
+ field: "packages",
87
+ patterns,
88
+ excludeField: null,
89
+ excludes: [],
90
+ },
91
+ issues: [],
92
+ };
93
+ }
94
+
95
+ function readPackageWorkspaces(
96
+ document: ParsedDocument,
97
+ issues: MetadataIssue[],
98
+ ): WorkspaceConfig | null {
99
+ if (!isRecord(document.data) || !Object.hasOwn(document.data, "workspaces")) return null;
100
+ const workspaces = document.data.workspaces;
101
+ const patterns = Array.isArray(workspaces)
102
+ ? stringArray(workspaces)
103
+ : isRecord(workspaces) && Array.isArray(workspaces.packages)
104
+ ? stringArray(workspaces.packages)
105
+ : null;
106
+ if (!patterns) {
107
+ issues.push(
108
+ issue(
109
+ document.path,
110
+ Array.isArray(workspaces) ? "workspaces" : "workspaces.packages",
111
+ "unsupported",
112
+ "Workspace membership must be a string array or an object with a string packages array.",
113
+ ),
114
+ );
115
+ return null;
116
+ }
117
+ return {
118
+ kind: "node-workspace",
119
+ manifestPath: document.path,
120
+ directory: document.directory,
121
+ field: Array.isArray(workspaces) ? "workspaces" : "workspaces.packages",
122
+ patterns,
123
+ excludeField: null,
124
+ excludes: [],
125
+ };
126
+ }
127
+
128
+ function collectNodeDependencies(
129
+ manifest: Record<string, unknown>,
130
+ manifestPath: string,
131
+ issues: MetadataIssue[],
132
+ ): DeclaredDependency[] {
133
+ const dependencies: DeclaredDependency[] = [];
134
+ for (const field of DEPENDENCY_FIELDS) {
135
+ if (!Object.hasOwn(manifest, field)) continue;
136
+ const value = manifest[field];
137
+ if (!isRecord(value)) {
138
+ issues.push(issue(manifestPath, field, "unsupported", `${field} must be an object.`));
139
+ continue;
140
+ }
141
+ for (const name of Object.keys(value).sort((left, right) => left.localeCompare(right))) {
142
+ dependencies.push({ field, name, value: value[name] });
143
+ }
144
+ }
145
+ return dependencies;
146
+ }
147
+
148
+ function collectNodePaths(
149
+ manifest: Record<string, unknown>,
150
+ manifestPath: string,
151
+ issues: MetadataIssue[],
152
+ ): DeclaredPath[] {
153
+ const paths: DeclaredPath[] = [];
154
+ for (const field of ["main", "module", "browser", "types", "typings"] as const) {
155
+ const value = stringValue(manifest[field]);
156
+ if (value !== null) paths.push({ field, path: value });
157
+ }
158
+ if (Object.hasOwn(manifest, "exports")) {
159
+ appendExportPaths(manifest.exports, "exports", paths);
160
+ }
161
+ appendBinPaths(manifest.bin, paths);
162
+ appendPiExtensionPaths(manifest.pi, manifestPath, paths, issues);
163
+ return paths;
164
+ }
165
+
166
+ function appendExportPaths(value: unknown, field: string, paths: DeclaredPath[]): void {
167
+ const direct = stringValue(value);
168
+ if (direct !== null) {
169
+ paths.push({ field, path: direct });
170
+ return;
171
+ }
172
+ if (Array.isArray(value)) {
173
+ for (const [index, entry] of value.entries()) {
174
+ appendExportPaths(entry, `${field}[${index}]`, paths);
175
+ }
176
+ return;
177
+ }
178
+ if (!isRecord(value)) return;
179
+ for (const key of Object.keys(value)) {
180
+ appendExportPaths(value[key], childField(field, key), paths);
181
+ }
182
+ }
183
+
184
+ function appendBinPaths(value: unknown, paths: DeclaredPath[]): void {
185
+ const direct = stringValue(value);
186
+ if (direct !== null) {
187
+ paths.push({ field: "bin", path: direct });
188
+ return;
189
+ }
190
+ if (!isRecord(value)) return;
191
+ for (const key of Object.keys(value)) {
192
+ const entry = stringValue(value[key]);
193
+ if (entry !== null) paths.push({ field: childField("bin", key), path: entry });
194
+ }
195
+ }
196
+
197
+ function appendPiExtensionPaths(
198
+ value: unknown,
199
+ manifestPath: string,
200
+ paths: DeclaredPath[],
201
+ issues: MetadataIssue[],
202
+ ): void {
203
+ if (!isRecord(value) || !Object.hasOwn(value, "extensions")) return;
204
+ const replacements = stringArray(value.extensions);
205
+ if (!replacements) {
206
+ issues.push(
207
+ issue(manifestPath, "pi.extensions", "unsupported", "pi.extensions must be a string array."),
208
+ );
209
+ return;
210
+ }
211
+ for (const [index, entry] of replacements.entries()) {
212
+ paths.push({ field: `pi.extensions[${index}]`, path: entry });
213
+ }
214
+ }
@@ -0,0 +1,161 @@
1
+ /** Shared bounded workspace observation used by overview and Orientation surfaces. */
2
+
3
+ import * as path from "node:path";
4
+ import { readGoDocument } from "./go.ts";
5
+ import { collectInventory, DEFAULT_MAX_INVENTORY_ENTRIES } from "./inventory.ts";
6
+ import { applyMemberships } from "./membership.ts";
7
+ import { readMetadataDocuments } from "./metadata.ts";
8
+ import type { DocumentContribution, ParsedDocument } from "./metadata-types.ts";
9
+ import { readNodeDocument } from "./node.ts";
10
+ import { compareObservationPaths, isWithinRoot, relativeToRoot } from "./paths.ts";
11
+ import { readPythonDocument } from "./python.ts";
12
+ import { buildRelationships } from "./relationships.ts";
13
+ import { readRustDocument } from "./rust.ts";
14
+ import type {
15
+ ObserveWorkspaceOptions,
16
+ ProjectDeclaration,
17
+ WorkspaceObservation,
18
+ WorkspaceObservationError,
19
+ } from "./types.ts";
20
+
21
+ /**
22
+ * Observe one exact working directory with bounded filesystem and metadata collection.
23
+ *
24
+ * The root is never widened to a Git or workspace ancestor. Git-ignored paths
25
+ * stay excluded unless `includeIgnored` is true. Symbolic links are returned
26
+ * as inventory entries but are never traversed or read through. Cancellation
27
+ * throws the abort reason; an expired deadline produces a partial result.
28
+ */
29
+ export async function observeWorkspace(
30
+ cwd: string,
31
+ options: ObserveWorkspaceOptions = {},
32
+ ): Promise<WorkspaceObservation> {
33
+ const root = path.resolve(cwd);
34
+ const control = options.control;
35
+ control?.signal?.throwIfAborted();
36
+ const exclude = options.exclude ? [...options.exclude] : [];
37
+ const includeIgnored = options.includeIgnored === true;
38
+ const maxEntries = effectiveLimit(options.maxEntries);
39
+ const prioritizedDirectory = priorityDirectory(root, options.prioritizeDirectory);
40
+ const inventory = await collectInventory(root, {
41
+ exclude,
42
+ includeIgnored,
43
+ maxEntries,
44
+ prioritizedDirectory,
45
+ control,
46
+ });
47
+ control?.signal?.throwIfAborted();
48
+ const metadataEntries = [...inventory.entries].sort((left, right) =>
49
+ compareObservationPaths(left.path, right.path, prioritizedDirectory),
50
+ );
51
+ const metadata = await readMetadataDocuments(root, metadataEntries, control);
52
+ control?.signal?.throwIfAborted();
53
+ const contribution = collectContributions(metadata.parsed);
54
+ const issues = [...metadata.issues, ...contribution.issues];
55
+ const projects = applyMemberships(
56
+ [...contribution.projects].sort((left, right) =>
57
+ left.manifestPath.localeCompare(right.manifestPath),
58
+ ),
59
+ contribution.workspaces,
60
+ issues,
61
+ );
62
+ const errors = [...inventory.errors, ...metadataErrors(issues)];
63
+ if (metadata.deadlineReached) {
64
+ errors.push({
65
+ stage: "metadata",
66
+ path: null,
67
+ reason: "Metadata collection deadline reached.",
68
+ });
69
+ }
70
+ const result: WorkspaceObservation = {
71
+ root,
72
+ inventory: { source: inventory.source, entries: inventory.entries },
73
+ inclusion: {
74
+ source: inventory.source,
75
+ exclude,
76
+ includeIgnored,
77
+ symlinks: "not-followed",
78
+ directoryNamesExcluded: false,
79
+ },
80
+ collection: {
81
+ status:
82
+ inventory.stopReason === "complete" && errors.length === 0 && issues.length === 0
83
+ ? "complete"
84
+ : "partial",
85
+ stopReason: metadata.deadlineReached ? "deadline" : inventory.stopReason,
86
+ prioritizedDirectory,
87
+ limits: { maxEntries, deadline: finiteDeadline(control?.deadline) },
88
+ errors,
89
+ },
90
+ metadata: { documents: metadata.documents, issues },
91
+ projects,
92
+ workspaces: contribution.workspaces,
93
+ relationships: buildRelationships(projects),
94
+ };
95
+ return deepFreeze(result);
96
+ }
97
+
98
+ function priorityDirectory(root: string, value: string | undefined): string | null {
99
+ if (value === undefined) return null;
100
+ const target = path.resolve(root, value);
101
+ if (!isWithinRoot(root, target))
102
+ throw new Error("The prioritized directory must stay inside the observation root.");
103
+ const relative = relativeToRoot(root, target);
104
+ return relative === "." ? null : relative;
105
+ }
106
+
107
+ function collectContributions(documents: readonly ParsedDocument[]): {
108
+ projects: ProjectDeclaration[];
109
+ workspaces: NonNullable<DocumentContribution["workspace"]>[];
110
+ issues: DocumentContribution["issues"][number][];
111
+ } {
112
+ const projects: ProjectDeclaration[] = [];
113
+ const workspaces: NonNullable<DocumentContribution["workspace"]>[] = [];
114
+ const issues: DocumentContribution["issues"][number][] = [];
115
+ for (const document of documents) {
116
+ const contribution = readDocument(document);
117
+ if (contribution.project) projects.push(contribution.project);
118
+ if (contribution.workspace) workspaces.push(contribution.workspace);
119
+ issues.push(...contribution.issues);
120
+ }
121
+ return { projects, workspaces, issues };
122
+ }
123
+
124
+ function readDocument(document: ParsedDocument): DocumentContribution {
125
+ switch (document.kind) {
126
+ case "package-json":
127
+ case "pnpm-workspace":
128
+ return readNodeDocument(document);
129
+ case "pyproject":
130
+ return readPythonDocument(document);
131
+ case "cargo":
132
+ return readRustDocument(document);
133
+ case "go-mod":
134
+ case "go-work":
135
+ return readGoDocument(document);
136
+ }
137
+ }
138
+
139
+ function metadataErrors(
140
+ issues: WorkspaceObservation["metadata"]["issues"],
141
+ ): WorkspaceObservationError[] {
142
+ return issues
143
+ .filter((entry) => entry.kind === "malformed" || entry.kind === "unreadable")
144
+ .map((entry) => ({ stage: "metadata", path: entry.path, reason: entry.reason }));
145
+ }
146
+
147
+ function effectiveLimit(value: number | undefined): number {
148
+ const requested = value ?? DEFAULT_MAX_INVENTORY_ENTRIES;
149
+ if (!Number.isFinite(requested)) return Number.MAX_SAFE_INTEGER;
150
+ return Math.max(0, Math.floor(requested));
151
+ }
152
+
153
+ function finiteDeadline(value: number | undefined): number | null {
154
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
155
+ }
156
+
157
+ function deepFreeze<T>(value: T): T {
158
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
159
+ for (const entry of Object.values(value)) deepFreeze(entry);
160
+ return Object.freeze(value);
161
+ }
@@ -0,0 +1,65 @@
1
+ /** Path helpers shared by workspace observation collection. */
2
+
3
+ import * as path from "node:path";
4
+
5
+ /** Convert an absolute path inside `root` into a root-relative POSIX path. */
6
+ export function relativeToRoot(root: string, absolutePath: string): string {
7
+ const relative = path.relative(root, absolutePath);
8
+ return relative === "" ? "." : relative.split(path.sep).join("/");
9
+ }
10
+
11
+ /** Return true when `candidate` is inside `root` or equal to it. */
12
+ export function isWithinRoot(root: string, candidate: string): boolean {
13
+ const relative = path.relative(root, candidate);
14
+ return (
15
+ relative === "" ||
16
+ (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
17
+ );
18
+ }
19
+
20
+ /** Validate and normalize a path that came from an external inventory command. */
21
+ export function normalizeInventoryPath(root: string, rawPath: string): string | null {
22
+ const normalized = rawPath.replaceAll(path.sep, "/");
23
+ if (!normalized || normalized.startsWith("/") || normalized.endsWith("/")) return null;
24
+ if (normalized.split("/").some((segment) => segment === "" || segment === "..")) return null;
25
+ const absolute = path.resolve(root, ...normalized.split("/"));
26
+ return isWithinRoot(root, absolute) ? relativeToRoot(root, absolute) : null;
27
+ }
28
+
29
+ /** Return the root-relative directory of a root-relative file path. */
30
+ export function relativeDirectory(relativePath: string): string {
31
+ const directory = path.posix.dirname(relativePath);
32
+ return directory === "" ? "." : directory;
33
+ }
34
+
35
+ /** Join a root-relative base and child path with POSIX separators. */
36
+ export function joinRelative(base: string, child: string): string {
37
+ if (base === "." || base === "") return child;
38
+ return `${base}/${child}`;
39
+ }
40
+
41
+ /** Normalize one caller path to a root-relative POSIX spelling. */
42
+ export function normalizeRelativePath(value: string): string | null {
43
+ const normalized = value.replaceAll(path.sep, "/").replace(/^\.\//, "").replace(/\/+$/, "");
44
+ if (!normalized) return ".";
45
+ if (normalized.startsWith("/") || normalized.split("/").some((segment) => segment === "..")) {
46
+ return null;
47
+ }
48
+ return normalized;
49
+ }
50
+
51
+ /** Keep an explicit subtree ahead of unrelated paths, then use the normal path order. */
52
+ export function compareObservationPaths(
53
+ left: string,
54
+ right: string,
55
+ priority: string | null,
56
+ ): number {
57
+ const rank = (value: string) =>
58
+ priority && (value === priority || value.startsWith(`${priority}/`)) ? 0 : 1;
59
+ return rank(left) - rank(right) || left.localeCompare(right);
60
+ }
61
+
62
+ /** Read an unknown error as a stable message. */
63
+ export function errorMessage(error: unknown): string {
64
+ return error instanceof Error ? error.message : String(error);
65
+ }