@mrclrchtr/supi-code-intelligence 11.0.0 → 11.1.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 (100) hide show
  1. package/README.md +41 -4
  2. package/gradle-helper/README.md +48 -0
  3. package/gradle-helper/build.sh +73 -0
  4. package/gradle-helper/lib/gradle-tooling-api-9.4.0.jar +0 -0
  5. package/gradle-helper/lib/slf4j-api-2.0.17.jar +0 -0
  6. package/gradle-helper/lib/slf4j-simple-2.0.17.jar +0 -0
  7. package/gradle-helper/lib/supi-gradle-observation.jar +0 -0
  8. package/gradle-helper/licenses/DEPENDENCIES.md +11 -0
  9. package/gradle-helper/licenses/LICENSE-gradle-tooling-api.txt +422 -0
  10. package/gradle-helper/licenses/LICENSE-slf4j.txt +21 -0
  11. package/gradle-helper/licenses/NOTICE-gradle.txt +21 -0
  12. package/gradle-helper/src/GradleObservation.java +597 -0
  13. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  14. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  15. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +41 -1
  16. package/node_modules/@mrclrchtr/supi-lsp/README.md +1 -1
  17. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  18. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  19. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +41 -1
  20. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/README.md +5 -0
  21. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/browser/ril.js +8 -0
  22. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/common/connection.js +7 -2
  23. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/common/ral.d.ts +8 -0
  24. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/main.d.ts +14 -0
  25. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/main.js +6 -4
  26. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/ril.js +5 -1
  27. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/package.json +4 -2
  28. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/package.json +4 -3
  29. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-types/lib/esm/main.js +2 -2
  30. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-types/lib/umd/main.js +2 -2
  31. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-types/package.json +2 -1
  32. package/node_modules/@mrclrchtr/supi-lsp/package.json +6 -6
  33. package/node_modules/@mrclrchtr/supi-lsp/src/client/client.ts +21 -0
  34. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager.ts +1 -1
  35. package/node_modules/@mrclrchtr/supi-tree-sitter/README.md +1 -0
  36. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  37. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  38. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +41 -1
  39. package/node_modules/@mrclrchtr/supi-tree-sitter/package.json +5 -3
  40. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/LICENSE +21 -0
  41. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm +0 -0
  42. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm.json +19 -2
  43. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/LICENSE +21 -0
  44. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm +0 -0
  45. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm.json +19 -2
  46. package/node_modules/ignore/README.md +95 -14
  47. package/node_modules/ignore/index.d.ts +56 -20
  48. package/node_modules/ignore/index.js +150 -120
  49. package/node_modules/ignore/legacy.js +159 -131
  50. package/node_modules/ignore/package.json +1 -1
  51. package/package.json +11 -6
  52. package/src/analysis/gradle/query.ts +273 -0
  53. package/src/analysis/gradle/runtime.ts +173 -0
  54. package/src/analysis/gradle/types.ts +65 -0
  55. package/src/analysis/read-next.ts +1 -4
  56. package/src/analysis/refactor/apply.ts +2 -2
  57. package/src/analysis/refactor/mutation-authority.ts +4 -1
  58. package/src/analysis/search/ast-scan.ts +143 -18
  59. package/src/analysis/workspace/safe-path.ts +14 -2
  60. package/src/analysis/workspace/types.ts +2 -0
  61. package/src/extension.ts +10 -1
  62. package/src/gradle/consent.ts +279 -0
  63. package/src/headless.ts +3 -0
  64. package/src/overview/collect.ts +11 -3
  65. package/src/session/orientation/workspace-context.ts +49 -28
  66. package/src/session/orientation-types.ts +11 -1
  67. package/src/session/orientation-workflow.ts +2 -0
  68. package/src/session/session.ts +8 -0
  69. package/src/tool/code_find/execute.ts +1 -1
  70. package/src/tool/code_find/markdown.ts +24 -17
  71. package/src/tool/code_find/result.ts +18 -5
  72. package/src/tool/code_find/spec.ts +2 -0
  73. package/src/tool/code_find/structured.ts +161 -0
  74. package/src/tool/code_graph/result.ts +32 -15
  75. package/src/tool/code_graph/spec.ts +2 -0
  76. package/src/tool/code_graph/structured.ts +142 -0
  77. package/src/tool/code_health/markdown.ts +5 -15
  78. package/src/tool/code_inspect/markdown.ts +19 -11
  79. package/src/tool/code_inspect/result.ts +1 -0
  80. package/src/tool/code_orientation/directory-navigation.ts +66 -0
  81. package/src/tool/code_orientation/gradle-sections.ts +68 -0
  82. package/src/tool/code_orientation/markdown.ts +19 -8
  83. package/src/tool/code_orientation/result.ts +89 -11
  84. package/src/tool/code_orientation/workspace-format.ts +2 -1
  85. package/src/tool/code_orientation/workspace-output.ts +40 -13
  86. package/src/tool/code_orientation/workspace-projects.ts +170 -50
  87. package/src/tool/code_orientation/workspace-sections.ts +3 -1
  88. package/src/tool/code_resolve/markdown.ts +4 -10
  89. package/src/tool/code_resolve/result.ts +2 -0
  90. package/src/tool/code_resolve/spec.ts +2 -0
  91. package/src/tool/code_resolve/structured.ts +103 -0
  92. package/src/tool/infra/truncate.ts +12 -4
  93. package/src/tool/register.ts +10 -6
  94. package/src/tool/result/display.ts +17 -0
  95. package/src/tool/result/model-budget.ts +195 -0
  96. package/src/tool/result/structured.ts +62 -0
  97. package/src/tool/result/types.ts +10 -2
  98. package/src/tool/specs.ts +2 -0
  99. package/src/types/execution.ts +5 -1
  100. package/src/ui/tui/display.ts +10 -4
@@ -7,6 +7,7 @@ import {
7
7
  getSupportedExtensions,
8
8
  type StructuralSearchOperation,
9
9
  } from "@mrclrchtr/supi-tree-sitter/api";
10
+ import ignore from "ignore";
10
11
  import { type DeadlineOutcome, type ScheduleDeadline, settleByDeadline } from "./deadline.ts";
11
12
  import { relativeDisplayPath } from "./paths.ts";
12
13
 
@@ -37,6 +38,7 @@ export type AstScanExclusionReason =
37
38
  | "hidden-entry"
38
39
  | "excluded-directory"
39
40
  | "configured-exclusion"
41
+ | "gitignore"
40
42
  | "unsupported-extension"
41
43
  | "unsupported-operation"
42
44
  | "symlink"
@@ -44,9 +46,12 @@ export type AstScanExclusionReason =
44
46
 
45
47
  export type AstScanLimitationReason = "timeout" | "safety-limit" | "unreadable-path";
46
48
 
47
- /** Bounded examples and exact encountered-path count for one policy exclusion. */
49
+ /** Bounded examples and exact skip-decision count for one scope root and policy reason. */
48
50
  export interface AstScanExclusion {
51
+ /** Canonical requested scan root, relative to cwd when inside it. */
52
+ readonly scopeRoot: string;
49
53
  readonly reason: AstScanExclusionReason;
54
+ /** Encountered skips, not distinct files absent from the combined result. */
50
55
  readonly pathCount: number;
51
56
  readonly examples: readonly string[];
52
57
  }
@@ -66,7 +71,8 @@ export interface AstScanPolicy {
66
71
  /** Patterns captured from code-intelligence.exclude for this scan. */
67
72
  readonly configuredExclusions: readonly string[];
68
73
  readonly hiddenEntries: "excluded";
69
- readonly ignoreFiles: false;
74
+ /** Root and nested regular, non-symlink .gitignore files apply below directory roots. */
75
+ readonly ignoreFiles: true;
70
76
  readonly symlinks: "explicit-roots-only";
71
77
  readonly maxFiles: number;
72
78
  readonly timeoutMs: number;
@@ -77,6 +83,8 @@ export interface AstScanOperations {
77
83
  readonly realpath: (filePath: string) => Promise<string>;
78
84
  readonly stat: (filePath: string) => Promise<Stats>;
79
85
  readonly readDirectory: (directory: string) => Promise<Dirent[]>;
86
+ readonly readFile?: (filePath: string) => Promise<string>;
87
+ readonly lstat?: (filePath: string) => Promise<Stats>;
80
88
  }
81
89
 
82
90
  export interface EnumerateAstFilesOptions {
@@ -124,7 +132,7 @@ export function astScanPolicy(
124
132
  excludedDirectories: [...AST_SCAN_EXCLUDED_DIRECTORIES],
125
133
  configuredExclusions: [...(automaticPathPolicy?.configuredPatterns ?? [])],
126
134
  hiddenEntries: "excluded",
127
- ignoreFiles: false,
135
+ ignoreFiles: true,
128
136
  symlinks: "explicit-roots-only",
129
137
  maxFiles,
130
138
  timeoutMs,
@@ -137,6 +145,18 @@ const DEFAULT_OPERATIONS: AstScanOperations = {
137
145
  readDirectory: (directory) => fs.readdir(directory, { withFileTypes: true }),
138
146
  };
139
147
 
148
+ interface RepositoryIgnoreRule {
149
+ readonly directory: string;
150
+ readonly matcher: ReturnType<typeof ignore>;
151
+ }
152
+
153
+ interface DirectoryScanPolicy {
154
+ readonly scopeRoot: string;
155
+ readonly bypassConfiguredExclusions: boolean;
156
+ readonly ignoreRoot: string;
157
+ readonly rules: readonly RepositoryIgnoreRule[];
158
+ }
159
+
140
160
  interface MutableObservation<T extends string> {
141
161
  reason: T;
142
162
  pathCount: number;
@@ -164,8 +184,8 @@ class AstFileEnumerator {
164
184
  readonly #files = new Set<string>();
165
185
  readonly #visitedDirectories = new Set<string>();
166
186
  readonly #exclusions = new Map<
167
- AstScanExclusionReason,
168
- MutableObservation<AstScanExclusionReason>
187
+ string,
188
+ Map<AstScanExclusionReason, MutableObservation<AstScanExclusionReason>>
169
189
  >();
170
190
  readonly #limitations = new Map<
171
191
  AstScanLimitationReason,
@@ -227,7 +247,8 @@ class AstFileEnumerator {
227
247
  const bypassConfiguredExclusions =
228
248
  this.options.automaticPathPolicy?.isConfiguredExcluded?.(canonicalRoot, "directory") ??
229
249
  false;
230
- await this.#walk(canonicalRoot, bypassConfiguredExclusions);
250
+ const policy = await this.#rootDirectoryPolicy(canonicalRoot, bypassConfiguredExclusions);
251
+ await this.#walk(canonicalRoot, policy);
231
252
  return null;
232
253
  }
233
254
  return {
@@ -255,16 +276,112 @@ class AstFileEnumerator {
255
276
  };
256
277
  }
257
278
 
258
- async #walk(directory: string, bypassConfiguredExclusions = false): Promise<void> {
259
- if (!this.#checkControl() || this.#visitedDirectories.has(directory)) return;
260
- this.#visitedDirectories.add(directory);
279
+ async #walk(directory: string, policy: DirectoryScanPolicy): Promise<void> {
280
+ // An overlapping explicit root may revisit this directory with different overrides.
281
+ const visitKey = JSON.stringify([
282
+ directory,
283
+ policy.ignoreRoot,
284
+ policy.bypassConfiguredExclusions,
285
+ ]);
286
+ if (!this.#checkControl() || this.#visitedDirectories.has(visitKey)) return;
287
+ this.#visitedDirectories.add(visitKey);
288
+ const inheritedRules = this.#allowDirectory(directory, policy.rules);
289
+ const rules = await this.#readIgnoreRules(directory, inheritedRules);
261
290
  const entries = await this.#readDirectory(directory);
262
291
  if (!entries) return;
263
292
  entries.sort((a, b) => a.name.localeCompare(b.name));
264
293
  for (const entry of entries) {
265
294
  if (!this.#checkControl()) return;
266
- await this.#processEntry(directory, entry, bypassConfiguredExclusions);
295
+ await this.#processEntry(directory, entry, { ...policy, rules });
296
+ }
297
+ }
298
+
299
+ /** Explicit ignored roots override ancestor rules, but keep their own nested rules. */
300
+ async #rootDirectoryPolicy(
301
+ root: string,
302
+ bypassConfiguredExclusions: boolean,
303
+ ): Promise<DirectoryScanPolicy> {
304
+ const explicitPolicy = {
305
+ scopeRoot: relativeDisplayPath(this.#displayBase, root),
306
+ bypassConfiguredExclusions,
307
+ ignoreRoot: root,
308
+ rules: [],
309
+ };
310
+ const relative = path.relative(this.#displayBase, root);
311
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`))
312
+ return explicitPolicy;
313
+ let directory = this.#displayBase;
314
+ let rules: readonly RepositoryIgnoreRule[] = [];
315
+ for (const segment of relative.split(path.sep)) {
316
+ if (!this.#checkControl()) break;
317
+ rules = await this.#readIgnoreRules(directory, this.#allowDirectory(directory, rules));
318
+ directory = path.join(directory, segment);
319
+ if (this.#isRepositoryIgnored(directory, true, rules)) return explicitPolicy;
320
+ }
321
+ return { ...explicitPolicy, ignoreRoot: this.#displayBase, rules };
322
+ }
323
+
324
+ /**
325
+ * Each matcher recursively tests parents. Carry the combined policy's already
326
+ * established directory eligibility into every ancestor matcher, so a nested
327
+ * directory negation also restores its contents without erasing file rules.
328
+ */
329
+ #allowDirectory(
330
+ directory: string,
331
+ rules: readonly RepositoryIgnoreRule[],
332
+ ): readonly RepositoryIgnoreRule[] {
333
+ return rules.map((rule) => {
334
+ const localPath = path.relative(rule.directory, directory).split(path.sep).join("/");
335
+ const literalPath = localPath.replace(/[\\*?[\]]/g, "\\$&");
336
+ return {
337
+ directory: rule.directory,
338
+ matcher: ignore({ ignorecase: false }).add(rule.matcher).add(`!/${literalPath}/`),
339
+ };
340
+ });
341
+ }
342
+
343
+ async #readIgnoreRules(
344
+ directory: string,
345
+ inheritedRules: readonly RepositoryIgnoreRule[],
346
+ ): Promise<readonly RepositoryIgnoreRule[]> {
347
+ const ignorePath = path.join(directory, ".gitignore");
348
+ try {
349
+ const metadata = await this.#settle(() => (this.#operations.lstat ?? fs.lstat)(ignorePath));
350
+ if (metadata.kind === "timeout" || !metadata.value.isFile()) return inheritedRules;
351
+ const outcome = await this.#settle(() =>
352
+ this.#operations.readFile
353
+ ? this.#operations.readFile(ignorePath)
354
+ : fs.readFile(ignorePath, "utf8"),
355
+ );
356
+ if (outcome.kind === "completed" && outcome.value.length > 0) {
357
+ return [
358
+ ...inheritedRules,
359
+ { directory, matcher: ignore({ ignorecase: false }).add(outcome.value) },
360
+ ];
361
+ }
362
+ } catch (error) {
363
+ this.options.signal?.throwIfAborted();
364
+ if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) {
365
+ this.#record(this.#limitations, "unreadable-path", ignorePath);
366
+ this.#interrupted = true;
367
+ }
267
368
  }
369
+ return inheritedRules;
370
+ }
371
+
372
+ #isRepositoryIgnored(
373
+ candidate: string,
374
+ directory: boolean,
375
+ rules: readonly RepositoryIgnoreRule[],
376
+ ): boolean {
377
+ let ignored = false;
378
+ for (const rule of rules) {
379
+ const localPath = path.relative(rule.directory, candidate).split(path.sep).join("/");
380
+ const result = rule.matcher.test(directory ? `${localPath}/` : localPath);
381
+ if (result.ignored) ignored = true;
382
+ else if (result.unignored) ignored = false;
383
+ }
384
+ return ignored;
268
385
  }
269
386
 
270
387
  async #readDirectory(directory: string): Promise<Dirent[] | null> {
@@ -282,16 +399,21 @@ class AstFileEnumerator {
282
399
  async #processEntry(
283
400
  directory: string,
284
401
  entry: Dirent,
285
- bypassConfiguredExclusions: boolean,
402
+ policy: DirectoryScanPolicy,
286
403
  ): Promise<void> {
287
404
  const entryPath = path.join(directory, entry.name);
288
- const exclusion = this.#entryExclusion(entryPath, entry, bypassConfiguredExclusions);
405
+ const exclusion = this.#entryExclusion(entryPath, entry, policy);
289
406
  if (exclusion) {
290
- this.#record(this.#exclusions, exclusion, entryPath);
407
+ let exclusions = this.#exclusions.get(policy.scopeRoot);
408
+ if (!exclusions) {
409
+ exclusions = new Map();
410
+ this.#exclusions.set(policy.scopeRoot, exclusions);
411
+ }
412
+ this.#record(exclusions, exclusion, entryPath);
291
413
  return;
292
414
  }
293
415
  if (entry.isDirectory()) {
294
- await this.#walk(entryPath, bypassConfiguredExclusions);
416
+ await this.#walk(entryPath, policy);
295
417
  return;
296
418
  }
297
419
  if (entry.isFile()) this.#addFile(entryPath);
@@ -300,14 +422,15 @@ class AstFileEnumerator {
300
422
  #entryExclusion(
301
423
  entryPath: string,
302
424
  entry: Dirent,
303
- bypassConfiguredExclusions: boolean,
425
+ policy: DirectoryScanPolicy,
304
426
  ): AstScanExclusionReason | null {
305
427
  if (entry.name.startsWith(".")) return "hidden-entry";
306
428
  if (entry.isSymbolicLink()) return "symlink";
429
+ if (this.#isRepositoryIgnored(entryPath, entry.isDirectory(), policy.rules)) return "gitignore";
307
430
  if (entry.isDirectory()) {
308
431
  if (EXCLUDED_DIRECTORY_SET.has(entry.name)) return "excluded-directory";
309
432
  if (
310
- !bypassConfiguredExclusions &&
433
+ !policy.bypassConfiguredExclusions &&
311
434
  this.options.automaticPathPolicy?.isConfiguredExcluded?.(entryPath, "directory")
312
435
  ) {
313
436
  return "configured-exclusion";
@@ -316,7 +439,7 @@ class AstFileEnumerator {
316
439
  }
317
440
  if (!entry.isFile()) return "non-regular";
318
441
  if (
319
- !bypassConfiguredExclusions &&
442
+ !policy.bypassConfiguredExclusions &&
320
443
  this.options.automaticPathPolicy?.isConfiguredExcluded?.(entryPath, "file")
321
444
  ) {
322
445
  return "configured-exclusion";
@@ -402,7 +525,9 @@ class AstFileEnumerator {
402
525
  this.options.timeoutMs ?? DEFAULT_AST_SCAN_TIMEOUT_MS,
403
526
  this.options.automaticPathPolicy,
404
527
  ),
405
- exclusions: [...this.#exclusions.values()],
528
+ exclusions: [...this.#exclusions].flatMap(([scopeRoot, exclusions]) =>
529
+ [...exclusions.values()].map((entry) => ({ ...entry, scopeRoot })),
530
+ ),
406
531
  limitations: [...this.#limitations.values()].map((entry) => ({
407
532
  ...entry,
408
533
  pathCount:
@@ -1,6 +1,17 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import * as path from "node:path";
3
3
 
4
+ /** Factual no-follow rejection; callers decide whether this is invalid input or a collection issue. */
5
+ export class WorkspaceSymlinkError extends Error {
6
+ constructor(
7
+ readonly requestedPath: string,
8
+ readonly blockedPath: string,
9
+ ) {
10
+ super(`Symbolic-link path is not followed: ${blockedPath}`);
11
+ this.name = "WorkspaceSymlinkError";
12
+ }
13
+ }
14
+
4
15
  /** Reject link traversal below the selected root, including a replaced root itself. */
5
16
  export async function assertUnlinkedPath(
6
17
  root: string,
@@ -9,12 +20,13 @@ export async function assertUnlinkedPath(
9
20
  ): Promise<void> {
10
21
  const parts = relativePath.split("/").filter((part) => part !== "." && part.length > 0);
11
22
  if (!includeLeaf) parts.pop();
23
+ const requestedPath = path.resolve(root, relativePath);
12
24
  let current = root;
13
25
  if ((await fs.lstat(current)).isSymbolicLink())
14
- throw new Error("Symbolic-link root is not followed.");
26
+ throw new WorkspaceSymlinkError(requestedPath, path.resolve(current));
15
27
  for (const part of parts) {
16
28
  current = path.join(current, part);
17
29
  if ((await fs.lstat(current)).isSymbolicLink())
18
- throw new Error(`Symbolic-link ancestor is not followed: ${relativePath}`);
30
+ throw new WorkspaceSymlinkError(requestedPath, path.resolve(current));
19
31
  }
20
32
  }
@@ -214,6 +214,8 @@ export interface WorkspaceInventory {
214
214
  export interface WorkspaceObservation {
215
215
  /** Absolute requested working directory. It is never widened to an ancestor. */
216
216
  readonly root: string;
217
+ /** Runtime-reported structure from one separately authorized selected build. */
218
+ readonly gradle?: import("../gradle/types.ts").GradleObservation;
217
219
  readonly inventory: WorkspaceInventory;
218
220
  readonly inclusion: WorkspaceInclusionPolicy;
219
221
  readonly collection: WorkspaceCollection;
package/src/extension.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  import type { BeforeAgentStartEventResult, ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
5
  import { createCodeIntelligenceApp } from "./app/app.ts";
6
6
  import { registerCodeIntelligenceSettings, resolveOverviewEnabled } from "./config.ts";
7
+ import { registerGradleObservations } from "./gradle/consent.ts";
7
8
  import { reportWorkspaceBudget } from "./overview/budget.ts";
8
9
  import { collectOverview } from "./overview/collect.ts";
9
10
  import type { WorkspaceCodeIntelligenceSession } from "./session/session.ts";
@@ -25,6 +26,7 @@ export default function codeIntelligenceExtension(
25
26
  ) {
26
27
  const app = createCodeIntelligenceApp(pi);
27
28
  const lspState = createLspAdapterState();
29
+ const gradle = registerGradleObservations(pi, { homeDir });
28
30
 
29
31
  registerCodeIntelligenceSettings(pi, homeDir);
30
32
  registerLspSettings(pi, homeDir);
@@ -38,6 +40,7 @@ export default function codeIntelligenceExtension(
38
40
  session.seedSentinelSnapshot(lspState.sentinelSnapshot);
39
41
  session.setProjectTrusted(ctx.isProjectTrusted());
40
42
  session.setHomeDir(homeDir);
43
+ session.setGradleObserver(gradle.forContext(ctx));
41
44
  session.setAutomaticPathPolicy(lspState.providerLease?.automaticPathPolicy ?? null);
42
45
  },
43
46
  homeDir,
@@ -80,6 +83,7 @@ export default function codeIntelligenceExtension(
80
83
  const session = app.getSession(ctx.cwd) ?? app.createSession(ctx.cwd);
81
84
  session.captureNativeInstructionPaths(event.systemPromptOptions.contextFiles ?? []);
82
85
  session.setHomeDir(homeDir);
86
+ session.setGradleObserver(gradle.forContext(ctx));
83
87
  if (!session.hasPinnedOverview()) {
84
88
  session.setOverviewEnabledOnce(
85
89
  resolveOverviewEnabled(ctx.cwd, ctx.isProjectTrusted(), homeDir),
@@ -100,7 +104,12 @@ export default function codeIntelligenceExtension(
100
104
  if (!session.claimOverviewInjection()) return;
101
105
 
102
106
  try {
103
- const overview = await collectOverview(ctx.cwd, ctx.isProjectTrusted(), homeDir);
107
+ const overview = await collectOverview(
108
+ ctx.cwd,
109
+ ctx.isProjectTrusted(),
110
+ homeDir,
111
+ gradle.forContext(ctx),
112
+ );
104
113
  if (!overview) {
105
114
  session.restoreOverviewInjection(false);
106
115
  return;
@@ -0,0 +1,279 @@
1
+ import { isAbsolute, join, relative, sep } from "node:path";
2
+ import {
3
+ type ExtensionAPI,
4
+ type ExtensionContext,
5
+ getAgentDir,
6
+ hasTrustRequiringProjectResources,
7
+ ProjectTrustStore,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import type { CodeRequestControl } from "@mrclrchtr/supi-code-runtime/api";
10
+ import {
11
+ loadSupiConfigSectionForScope,
12
+ removeSupiConfigKey,
13
+ writeSupiConfig,
14
+ } from "@mrclrchtr/supi-core/config";
15
+ import { registerSettings } from "@mrclrchtr/supi-core/settings";
16
+ import { queryGradleModel } from "../analysis/gradle/query.ts";
17
+ import {
18
+ GradlePrerequisiteError,
19
+ hasGradleSettings,
20
+ selectGradleRuntime,
21
+ } from "../analysis/gradle/runtime.ts";
22
+ import type {
23
+ GradleFailureStage,
24
+ GradleModelQuery,
25
+ GradleObservation,
26
+ GradleObserver,
27
+ } from "../analysis/gradle/types.ts";
28
+
29
+ const section = "code-intelligence";
30
+ const key = "gradleObservation";
31
+ const explanation =
32
+ "Gradle model collection executes settings and plugins; it may download distributions or dependencies, write caches, and access files or services outside the reporting root. Reporting bounds are not a sandbox.";
33
+
34
+ function permission(cwd: string): "allow" | "deny" | undefined {
35
+ const value = loadSupiConfigSectionForScope(section, cwd, { scope: "project" })?.[key];
36
+ return value === "allow" || value === "deny" ? value : undefined;
37
+ }
38
+
39
+ function collectionFailure(
40
+ root: string,
41
+ stage: GradleFailureStage,
42
+ error: unknown,
43
+ ): GradleObservation {
44
+ return {
45
+ selectedRoot: root,
46
+ query: "GradleBuild/BasicGradleProject",
47
+ stage,
48
+ status:
49
+ error instanceof GradlePrerequisiteError
50
+ ? error.status
51
+ : stage === "query" || stage === "unknown"
52
+ ? "failed"
53
+ : "unavailable",
54
+ reason: error instanceof Error ? error.message.slice(0, 500) : "Gradle collection failed.",
55
+ };
56
+ }
57
+
58
+ /** Owned, live-authorized Gradle requests for one Pi session working directory. */
59
+ class SessionGradleObserver implements GradleObserver {
60
+ readonly active = new Set<AbortController>();
61
+ constructor(
62
+ readonly cwd: string,
63
+ readonly trusted: (root: string) => boolean,
64
+ readonly query: GradleModelQuery,
65
+ ) {}
66
+ cancel(): void {
67
+ for (const controller of this.active) controller.abort();
68
+ }
69
+ async observe(
70
+ root: string,
71
+ control?: CodeRequestControl,
72
+ ): Promise<GradleObservation | undefined> {
73
+ const base = { selectedRoot: root, query: "GradleBuild/BasicGradleProject" as const };
74
+ let stage: GradleFailureStage = "prerequisites";
75
+ try {
76
+ if (!(await hasGradleSettings(root))) return undefined;
77
+ stage = "authorization";
78
+ if (!this.trusted(root))
79
+ return {
80
+ ...base,
81
+ status: "blocked",
82
+ stage: "authorization",
83
+ reason:
84
+ "Gradle execution requires an actual Pi project-trust gate. Use /trust and reload; a bare SuPi config is insufficient.",
85
+ };
86
+ const decision = permission(this.cwd);
87
+ if (decision !== "allow")
88
+ return {
89
+ ...base,
90
+ status: "blocked",
91
+ stage: "authorization",
92
+ reason:
93
+ decision === "deny"
94
+ ? "Gradle model collection was denied in project settings."
95
+ : "Gradle model permission is unset; no execution occurred.",
96
+ };
97
+ return await this.collect(root, control);
98
+ } catch (error) {
99
+ return collectionFailure(root, stage, error);
100
+ }
101
+ }
102
+
103
+ private async collect(root: string, control?: CodeRequestControl): Promise<GradleObservation> {
104
+ const base = { selectedRoot: root, query: "GradleBuild/BasicGradleProject" as const };
105
+ const controller = new AbortController();
106
+ this.active.add(controller);
107
+ let stage: GradleFailureStage = "prerequisites";
108
+ try {
109
+ const signal = control?.signal
110
+ ? AbortSignal.any([control.signal, controller.signal])
111
+ : controller.signal;
112
+ if (signal.aborted)
113
+ return {
114
+ ...base,
115
+ status: "interrupted",
116
+ stage,
117
+ reason: "Gradle model collection was cancelled.",
118
+ };
119
+ if (control?.deadline !== undefined && Date.now() >= control.deadline)
120
+ return {
121
+ ...base,
122
+ status: "timeout",
123
+ stage,
124
+ reason: "Gradle observation deadline expired before runtime selection.",
125
+ };
126
+ const runtime = await selectGradleRuntime(root);
127
+ if (!this.trusted(root) || permission(this.cwd) !== "allow" || signal.aborted)
128
+ return {
129
+ ...base,
130
+ status: "interrupted",
131
+ stage: "authorization",
132
+ reason: "Gradle authorization was revoked; no new query was started.",
133
+ };
134
+ stage = "unknown";
135
+ const result = await this.query(root, runtime, { ...control, signal });
136
+ if (signal.aborted || !this.trusted(root) || permission(this.cwd) !== "allow")
137
+ return {
138
+ ...base,
139
+ runtime,
140
+ status: "interrupted",
141
+ stage: result.status === "complete" ? "query" : result.stage,
142
+ gradleVersion: result.gradleVersion,
143
+ reason:
144
+ "Gradle authorization changed or collection was cancelled; prior side effects may remain.",
145
+ };
146
+ return { ...result, runtime };
147
+ } catch (error) {
148
+ return collectionFailure(root, stage, error);
149
+ } finally {
150
+ this.active.delete(controller);
151
+ }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Register project-only consent, startup prompting, and owned-request cancellation.
157
+ * Pi's effective trust boolean alone is insufficient in a directory containing only
158
+ * .pi/supi/config.json: Pi implicitly trusts directories without protected resources.
159
+ * Snapshot the protected-resource gate at session_start, or require Pi's user-owned
160
+ * saved trust decision. Explicit external focuses require their own saved trust.
161
+ */
162
+ export function registerGradleObservations(
163
+ pi: ExtensionAPI,
164
+ options: {
165
+ homeDir?: string;
166
+ query?: GradleModelQuery;
167
+ interactive?: boolean;
168
+ } = {},
169
+ ): {
170
+ forContext(ctx: ExtensionContext): GradleObserver;
171
+ } {
172
+ const { homeDir, query = queryGradleModel, interactive = true } = options;
173
+ const sessions = new Map<string, SessionGradleObserver>();
174
+ const contexts = new Map<string, ExtensionContext>();
175
+ const gatedRoots = new Set<string>();
176
+ const trustStore = new ProjectTrustStore(homeDir ? join(homeDir, ".pi/agent") : getAgentDir());
177
+ const savedTrust = (root: string) => {
178
+ try {
179
+ return trustStore.get(root) === true;
180
+ } catch {
181
+ return false;
182
+ }
183
+ };
184
+ const forContext = (ctx: ExtensionContext): SessionGradleObserver => {
185
+ contexts.set(ctx.cwd, ctx);
186
+ let observer = sessions.get(ctx.cwd);
187
+ if (!observer) {
188
+ observer = new SessionGradleObserver(
189
+ ctx.cwd,
190
+ (root) => {
191
+ if (!contexts.get(ctx.cwd)?.isProjectTrusted()) return false;
192
+ const local = relative(ctx.cwd, root);
193
+ const inside =
194
+ local === "" || (local !== ".." && !local.startsWith(`..${sep}`) && !isAbsolute(local));
195
+ return inside ? gatedRoots.has(ctx.cwd) || savedTrust(ctx.cwd) : savedTrust(root);
196
+ },
197
+ query,
198
+ );
199
+ sessions.set(ctx.cwd, observer);
200
+ }
201
+ return observer;
202
+ };
203
+ if (interactive)
204
+ registerSettings(pi, {
205
+ id: "code-intelligence-gradle",
206
+ label: "Code Intelligence",
207
+ subsection: "Gradle observations",
208
+ async read(context) {
209
+ if (context.scope !== "project") return { rows: [] };
210
+ const value = permission(context.cwd);
211
+ return {
212
+ rows: [
213
+ {
214
+ field: {
215
+ kind: "enum",
216
+ key,
217
+ label: "Gradle Model Permission",
218
+ values: ["allow", "deny"],
219
+ description: `${explanation} Project only. Reset asks at the next eligible startup. Changes affect the next query; Deny cancels owned work where possible, not side effects or unrelated daemons.`,
220
+ },
221
+ displayValue: value ? (value === "allow" ? "Allow" : "Deny") : "Unset",
222
+ editValue: value ?? "",
223
+ source: value ? "project" : "default",
224
+ inheritanceSource: "default",
225
+ },
226
+ ],
227
+ };
228
+ },
229
+ async apply(request) {
230
+ if (request.scope !== "project" || request.fieldKey !== key)
231
+ throw new Error("Gradle consent is project-only.");
232
+ if (request.action.kind === "unset")
233
+ removeSupiConfigKey({ section, cwd: request.cwd, scope: "project" }, key);
234
+ else {
235
+ if (!["allow", "deny"].includes(request.action.value))
236
+ throw new Error("Expected Allow or Deny.");
237
+ writeSupiConfig(
238
+ { section, cwd: request.cwd, scope: "project" },
239
+ { [key]: request.action.value },
240
+ );
241
+ }
242
+ if (permission(request.cwd) !== "allow") sessions.get(request.cwd)?.cancel();
243
+ return {
244
+ notice: {
245
+ level: "info",
246
+ message:
247
+ "Gradle permission saved. Applies to the next query; cancellation cannot undo side effects or stop unrelated daemons.",
248
+ },
249
+ };
250
+ },
251
+ });
252
+ pi.on("session_start", async (_event, ctx) => {
253
+ if (ctx.isProjectTrusted() && hasTrustRequiringProjectResources(ctx.cwd))
254
+ gatedRoots.add(ctx.cwd);
255
+ const observer = forContext(ctx);
256
+ if (
257
+ !interactive ||
258
+ !ctx.hasUI ||
259
+ !observer.trusted(ctx.cwd) ||
260
+ permission(ctx.cwd) !== undefined ||
261
+ !(await hasGradleSettings(ctx.cwd).catch(() => false))
262
+ )
263
+ return;
264
+ const answer = await ctx.ui.select(`Allow Gradle model collection? ${explanation}`, [
265
+ "Allow",
266
+ "Deny",
267
+ "Cancel",
268
+ ]);
269
+ if (answer === "Allow" || answer === "Deny")
270
+ writeSupiConfig({ section, cwd: ctx.cwd, scope: "project" }, { [key]: answer.toLowerCase() });
271
+ });
272
+ pi.on("session_shutdown", () => {
273
+ for (const observer of sessions.values()) observer.cancel();
274
+ sessions.clear();
275
+ contexts.clear();
276
+ gatedRoots.clear();
277
+ });
278
+ return { forContext };
279
+ }
package/src/headless.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { createSessionCache } from "./app/app.ts";
3
+ import { registerGradleObservations } from "./gradle/consent.ts";
3
4
  import { registerLspSessionLifecycle } from "./substrate/lsp/lifecycle.ts";
4
5
  import { createLspAdapterState } from "./substrate/lsp/state.ts";
5
6
  import { registerCodeIntelligenceTools } from "./tool/register.ts";
@@ -24,11 +25,13 @@ const inspectionToolNames = new Set<string>(HEADLESS_INSPECTION_TOOL_NAMES);
24
25
  export default function headlessInspectionProfile(pi: ExtensionAPI): void {
25
26
  const sessions = createSessionCache();
26
27
  const lspState = createLspAdapterState();
28
+ const gradle = registerGradleObservations(pi, { interactive: false });
27
29
  registerLspSessionLifecycle(pi, lspState, (ctx) => {
28
30
  const session = sessions.getOrCreate(ctx.cwd);
29
31
  session.attachLspController(lspState.controller);
30
32
  session.seedSentinelSnapshot(lspState.sentinelSnapshot);
31
33
  session.setProjectTrusted(ctx.isProjectTrusted());
34
+ session.setGradleObserver(gradle.forContext(ctx));
32
35
  session.setAutomaticPathPolicy(lspState.providerLease?.automaticPathPolicy ?? null);
33
36
  });
34
37
  pi.on("session_shutdown", () => sessions.clear());