@mrclrchtr/supi-code-intelligence 11.0.1 → 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 +36 -10
  47. package/node_modules/ignore/index.d.ts +3 -2
  48. package/node_modules/ignore/index.js +57 -53
  49. package/node_modules/ignore/legacy.js +50 -46
  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
@@ -0,0 +1,103 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import { type Static, Type } from "typebox";
3
+ import type { TargetWorkflowOutcome } from "../../session/target-workflow.ts";
4
+ import {
5
+ ConfidenceSchema,
6
+ EvidenceListSchema,
7
+ NavigationTargetSchema,
8
+ RecoveryRangeSchema,
9
+ } from "../result/structured.ts";
10
+ import type { ResolveDetails } from "../result/types.ts";
11
+
12
+ /** Codemode contract for resolution, including candidate selection and invalid input. */
13
+ export const ResolveOutputSchema = Type.Object(
14
+ {
15
+ kind: StringEnum([
16
+ "resolved",
17
+ "target-group",
18
+ "disambiguation",
19
+ "kind-mismatch",
20
+ "invalid-input",
21
+ ]),
22
+ confidence: ConfidenceSchema,
23
+ targets: Type.Array(NavigationTargetSchema),
24
+ evidenceLists: Type.Array(EvidenceListSchema),
25
+ nextQueries: Type.Array(Type.String()),
26
+ notes: Type.Array(Type.String()),
27
+ message: Type.Optional(Type.String()),
28
+ file: Type.Optional(Type.String()),
29
+ requestedKind: Type.Optional(Type.String()),
30
+ unknownNestingCount: Type.Optional(Type.Integer()),
31
+ discoveryProvenance: Type.Optional(Type.Array(StringEnum(["semantic", "structural"]))),
32
+ partialReason: Type.Optional(Type.Union([Type.String(), Type.Null()])),
33
+ errorRanges: Type.Optional(Type.Array(RecoveryRangeSchema)),
34
+ },
35
+ { additionalProperties: false },
36
+ );
37
+
38
+ /** Project caller-visible targets without internal store identity or fingerprints. */
39
+ export function structuredResolveResult(
40
+ data: ResolveDetails,
41
+ outcome: Exclude<TargetWorkflowOutcome, { kind: "unavailable" }>,
42
+ ): Static<typeof ResolveOutputSchema> {
43
+ return {
44
+ kind: outcome.kind,
45
+ confidence: data.confidence,
46
+ targets: [
47
+ ...data.targets.map((entry) => ({
48
+ handle: entry.targetId,
49
+ name: entry.name,
50
+ kind: entry.kind,
51
+ ...(entry.nativeKind === undefined ? {} : { nativeKind: entry.nativeKind }),
52
+ file: entry.file,
53
+ line: entry.displayLine,
54
+ character: entry.displayCharacter,
55
+ anchorKind: entry.anchorKind,
56
+ container: entry.container,
57
+ confidence: entry.confidence,
58
+ provenance: [...entry.provenance],
59
+ ...(entry.resolution
60
+ ? {
61
+ resolution: {
62
+ requested: { ...entry.resolution.requested },
63
+ resolved: { ...entry.resolution.resolved },
64
+ snapped: entry.resolution.snapped,
65
+ source: entry.resolution.source,
66
+ },
67
+ }
68
+ : {}),
69
+ })),
70
+ ...(data.candidates ?? []).map((candidate) => ({
71
+ handle: candidate.targetId,
72
+ name: candidate.name,
73
+ kind: candidate.kind,
74
+ file: candidate.file,
75
+ line: candidate.line,
76
+ character: candidate.character,
77
+ anchorKind: candidate.anchorKind,
78
+ container: candidate.container,
79
+ })),
80
+ ],
81
+ evidenceLists: (data.evidenceLists ?? []).map((evidence) => ({ ...evidence })),
82
+ nextQueries: data.nextQueries,
83
+ notes: outcome.kind === "resolved" ? [...outcome.notes] : [],
84
+ ...(data.message === undefined ? {} : { message: data.message }),
85
+ ...(data.groupFile === undefined ? {} : { file: data.groupFile }),
86
+ ...(data.requestedKind === undefined ? {} : { requestedKind: data.requestedKind }),
87
+ ...(data.groupUnknownNestingCount === undefined
88
+ ? {}
89
+ : { unknownNestingCount: data.groupUnknownNestingCount }),
90
+ ...(data.groupDiscoveryProvenance === undefined
91
+ ? {}
92
+ : { discoveryProvenance: [...data.groupDiscoveryProvenance] }),
93
+ ...(data.groupPartialReason === undefined ? {} : { partialReason: data.groupPartialReason }),
94
+ ...(data.groupErrorRanges === undefined
95
+ ? {}
96
+ : {
97
+ errorRanges: data.groupErrorRanges.map((range) => ({
98
+ start: { ...range.start },
99
+ end: { ...range.end },
100
+ })),
101
+ }),
102
+ };
103
+ }
@@ -52,12 +52,13 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
52
52
  import { tmpdir } from "node:os";
53
53
  import { join } from "node:path";
54
54
  import type { CodeIntelResult } from "../../types/index.ts";
55
+ import { boundModelContent } from "../result/model-budget.ts";
55
56
  import type { ToolOutputTruncationDetails } from "../result/types.ts";
56
57
 
57
58
  /**
58
59
  * Apply the canonical output bound to one assembled code-tool result:
59
- * truncate at PI limits, spill the full content to a temp file when it
60
- * overflowed or the human display omits returned evidence. A display-only
60
+ * bound the inline preview before applying PI safety limits, and spill the
61
+ * original content when either bound or the human display omits evidence. A display-only
61
62
  * continuation does not add text to model content. File failure is fatal only
62
63
  * when model content would otherwise be lost.
63
64
  */
@@ -69,10 +70,13 @@ export function boundCodeToolResult(
69
70
  const withTruncation = (truncation: ToolOutputTruncationDetails) =>
70
71
  details ? { ...details, truncation } : details;
71
72
 
72
- const { text, truncated } = truncateToolContent(content, {
73
+ const preview = boundModelContent(content, details);
74
+ const safety = truncateToolContent(preview.text, {
73
75
  maxLines: options.maxLines,
74
76
  maxBytes: options.maxBytes,
75
77
  });
78
+ const { text } = safety;
79
+ const truncated = preview.truncated || safety.truncated;
76
80
  const displayTruncated = details?.truncation?.displayTruncated === true;
77
81
  const truncation = { truncated, ...(displayTruncated ? { displayTruncated } : {}) };
78
82
  if ((truncated || displayTruncated) && content.length > 0) {
@@ -82,7 +86,11 @@ export function boundCodeToolResult(
82
86
  content: [
83
87
  {
84
88
  type: "text" as const,
85
- text: truncated ? `${text}\n_Full output saved to: \`${spillPath}\`_` : text,
89
+ text: preview.truncated
90
+ ? `_Full output saved to: \`${spillPath}\`_\n\n${text}`
91
+ : truncated
92
+ ? `${text}\n_Full output saved to: \`${spillPath}\`_`
93
+ : text,
86
94
  },
87
95
  ],
88
96
  details: withTruncation({ ...truncation, fullOutputPath: spillPath }),
@@ -105,6 +105,7 @@ export function registerCodeIntelligenceTools(
105
105
  promptSnippet: surface.promptSnippet,
106
106
  promptGuidelines: surface.promptGuidelines,
107
107
  parameters: spec.parameters,
108
+ outputSchema: spec.outputSchema,
108
109
  // biome-ignore lint/complexity/useMaxParams: pi ToolDefinition.execute signature
109
110
  execute: async (toolCallId, params, signal, onUpdate, ctx: ExtensionContext) => {
110
111
  const operationId = createDebugOperationId(operationSecret, toolCallId);
@@ -115,7 +116,7 @@ export function registerCodeIntelligenceTools(
115
116
  try {
116
117
  const session = getOrCreateSession(ctx.cwd);
117
118
  session.setProjectTrusted(ctx.isProjectTrusted());
118
- const { content, details } = await spec.run(params, {
119
+ const { content, details, structuredContent } = await spec.run(params, {
119
120
  cwd: ctx.cwd,
120
121
  operationId,
121
122
  signal,
@@ -131,11 +132,14 @@ export function registerCodeIntelligenceTools(
131
132
  outcome: "completed",
132
133
  });
133
134
  reportWorkspaceBudget(ctx, details?.budgetWarning, operationId);
134
- return boundCodeToolResult(content, details, {
135
- toolName: spec.name,
136
- maxLines: spec.maxLines,
137
- maxBytes: spec.maxBytes,
138
- });
135
+ return {
136
+ ...boundCodeToolResult(content, details, {
137
+ toolName: spec.name,
138
+ maxLines: spec.maxLines,
139
+ maxBytes: spec.maxBytes,
140
+ }),
141
+ ...(structuredContent === undefined ? {} : { structuredContent }),
142
+ };
139
143
  } catch (error) {
140
144
  const outcome = terminalCodeOperationOutcome(error, signal);
141
145
  recordCodeWorkflowTiming(workflowTimer, operationId, spec.name, {
@@ -18,6 +18,8 @@ export interface ToolDisplaySectionInput<T> {
18
18
  /** Provider explanation for incomplete collection, when available. */
19
19
  partialMessage?: string;
20
20
  maxItems?: number;
21
+ /** Explicit content-count meaning when display rows are not individual Evidence atoms. */
22
+ preview?: ToolDisplaySection["preview"];
21
23
  }
22
24
 
23
25
  /** Build a bounded, serializable TUI section from collected facts. */
@@ -45,6 +47,7 @@ export function createToolDisplaySection<T>(input: ToolDisplaySectionInput<T>):
45
47
  omittedCount,
46
48
  partialReason: input.partialReason ?? null,
47
49
  ...(input.partialMessage === undefined ? {} : { partialMessage: input.partialMessage }),
50
+ ...(input.preview ? { preview: { ...input.preview } } : {}),
48
51
  };
49
52
  }
50
53
 
@@ -81,6 +84,7 @@ export function readToolDisplaySections(value: unknown): ToolDisplaySection[] {
81
84
  ) {
82
85
  return [];
83
86
  }
87
+ const preview = readPreview(record.preview);
84
88
  return [
85
89
  {
86
90
  key: record.key,
@@ -95,11 +99,24 @@ export function readToolDisplaySections(value: unknown): ToolDisplaySection[] {
95
99
  ...(typeof record.partialMessage === "string"
96
100
  ? { partialMessage: record.partialMessage }
97
101
  : {}),
102
+ ...(preview ? { preview } : {}),
98
103
  },
99
104
  ];
100
105
  });
101
106
  }
102
107
 
108
+ function readPreview(value: unknown): ToolDisplaySection["preview"] {
109
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
110
+ const record = value as Record<string, unknown>;
111
+ if (record.unit !== "group" && record.unit !== "block") return undefined;
112
+ return {
113
+ unit: record.unit,
114
+ ...(typeof record.evidenceSummary === "string"
115
+ ? { evidenceSummary: truncateDisplayText(record.evidenceSummary) }
116
+ : {}),
117
+ };
118
+ }
119
+
103
120
  function isCount(value: unknown): value is number {
104
121
  return typeof value === "number" && Number.isInteger(value) && value >= 0;
105
122
  }
@@ -0,0 +1,195 @@
1
+ import type { CodeIntelResult } from "../../types/index.ts";
2
+ import { formatSemanticHealthState } from "../code_health/semantic-state.ts";
3
+ import type { HealthDetails, SearchDetails } from "./types.ts";
4
+
5
+ /** Economic inline bound (approximately 2,000 tokens), independent of Pi's safety limit. */
6
+ export const MODEL_OUTPUT_MAX_CHARACTERS = 8_000;
7
+ const NOTICE_RESERVE = 1_024;
8
+ const MAX_FACT_CHARACTERS = 4_000;
9
+
10
+ type Details = NonNullable<CodeIntelResult["details"]>;
11
+
12
+ /** Preserve collection state and diagnostic snippets before a bounded, explicitly incomplete excerpt. */
13
+ export function boundModelContent(
14
+ content: string,
15
+ details: CodeIntelResult["details"],
16
+ ): {
17
+ text: string;
18
+ truncated: boolean;
19
+ } {
20
+ if (details?.modelBudgetManaged || content.length <= MODEL_OUTPUT_MAX_CHARACTERS) {
21
+ return { text: content, truncated: false };
22
+ }
23
+ const lines = [
24
+ "[truncated: model preview; read the saved output for full returned evidence.]",
25
+ "Counts describe the returned result, not this shortened preview.",
26
+ ];
27
+ // Reserve diagnostic space before verbose limitations can exhaust the summary.
28
+ // Single-line facts also keep Pi's later line bound from discarding late sections.
29
+ if (details) lines.push(...diagnosticFacts(details).map((fact) => shortFact(fact, 320)));
30
+ const facts = details ? summary(details) : [];
31
+ for (let index = 0; index < facts.length; index++) {
32
+ const fact = shortFact(facts[index], 256);
33
+ if (lines.join("\n").length + fact.length > MAX_FACT_CHARACTERS) {
34
+ lines.push(`Additional summary lines omitted: ${facts.length - index}.`);
35
+ break;
36
+ }
37
+ lines.push(fact);
38
+ }
39
+ const header = `${lines.join("\n")}\n\n## Incomplete text excerpt\n`;
40
+ const remaining = MODEL_OUTPUT_MAX_CHARACTERS - NOTICE_RESERVE - header.length;
41
+ return { text: `${header}${shorten(content, remaining)}`, truncated: true };
42
+ }
43
+
44
+ function shorten(value: string, limit: number): string {
45
+ if (value.length <= limit) return value;
46
+ let end = Math.max(0, limit - 15);
47
+ const unit = value.charCodeAt(end - 1);
48
+ if (unit >= 0xd800 && unit <= 0xdbff) end--;
49
+ return `${value.slice(0, end)}… [shortened]`;
50
+ }
51
+
52
+ function shortFact(value: string, limit: number): string {
53
+ return shorten(value.replace(/\s+/gu, " "), limit);
54
+ }
55
+
56
+ function diagnosticFacts(details: Details): string[] {
57
+ if (details.type === "inspect") {
58
+ return (details.data.diagnostics ?? [])
59
+ .slice(0, 3)
60
+ .map(
61
+ (diagnostic) =>
62
+ `Diagnostic L${diagnostic.line}:${diagnostic.character} (severity=${diagnostic.severity}): ${diagnostic.message}`,
63
+ );
64
+ }
65
+ if (details.type === "health") {
66
+ const snippets: string[] = [];
67
+ for (const entry of details.data.diagnosticObservation.entries) {
68
+ for (const message of entry.messages ?? []) {
69
+ snippets.push(`${entry.file}:${message.line} ${message.severity}: ${message.message}`);
70
+ if (snippets.length === 3) return snippets;
71
+ }
72
+ }
73
+ return snippets;
74
+ }
75
+ return [];
76
+ }
77
+
78
+ function summary(details: Details): string[] {
79
+ const data = details.data;
80
+ return [
81
+ `Result status: ${details.status ?? "completed"}.`,
82
+ ...(details.message ? [details.message] : []),
83
+ ...("confidence" in data ? [`Confidence: ${data.confidence}.`] : []),
84
+ ...(data.evidenceLists ?? []).map(
85
+ (list) =>
86
+ `${list.key}: returned=${list.shownCount}, total=${list.totalCount ?? "unknown"}, cap-omitted=${list.omittedCount ?? "unknown"}; partial=${list.partialReason ?? "none"}${list.invalidLocationCount ? `; invalid locations=${list.invalidLocationCount}` : ""}${list.partialMessage ? `; ${list.partialMessage}` : ""}`,
87
+ ),
88
+ ...sectionFacts(details),
89
+ ];
90
+ }
91
+
92
+ function sectionFacts(details: Details): string[] {
93
+ switch (details.type) {
94
+ case "inspect": {
95
+ const data = details.data;
96
+ return [
97
+ `Focus: ${data.focusTarget}; diagnostics window: ${data.diagnosticWindow ? `L${data.diagnosticWindow.startLine}–L${data.diagnosticWindow.endLine}` : "unavailable"}.`,
98
+ ...data.sections.map(
99
+ (section) =>
100
+ `${section.key}: ${section.status}${section.reason ? ` — ${section.reason}` : ""}${section.recovery ? `; recovered syntax in ${section.recovery.file}` : ""}`,
101
+ ),
102
+ ];
103
+ }
104
+ case "graph":
105
+ return [
106
+ `Target: ${details.data.targetName} — ${details.data.targetFile}.`,
107
+ ...details.data.sections.map(
108
+ (section) =>
109
+ `${section.rel} (${section.source}): ${section.status}; external=${section.externalCount}${section.depth ? `; depth=${section.depth}` : ""}${section.message ? `; ${section.message}` : ""}${section.recovery ? `; syntax recovery: ${section.recovery.reason}` : ""}`,
110
+ ),
111
+ "Callees are written source expressions, not resolved symbol identities; direct depth excludes nested scopes.",
112
+ ];
113
+ case "resolve":
114
+ return [
115
+ `${details.data.resultKind}: ${details.data.targetCount} targets; ${details.data.omittedCount} cap omissions.`,
116
+ ...(details.data.groupPartialReason
117
+ ? [`Partial discovery: ${details.data.groupPartialReason}`]
118
+ : []),
119
+ ...details.data.targets
120
+ .slice(0, 3)
121
+ .map(
122
+ (target) =>
123
+ `${target.targetId}: ${target.name ?? "anonymous"} ${target.file}:${target.displayLine}:${target.displayCharacter}; ${target.anchorKind} anchor; confidence=${target.confidence}; provenance=${target.provenance.join("+")}`,
124
+ ),
125
+ ];
126
+ case "search":
127
+ return searchFacts(details.data);
128
+ case "health":
129
+ return healthFacts(details.data);
130
+ case "context":
131
+ return [
132
+ `Focus: ${details.data.focusTarget ?? "workspace"}.`,
133
+ ...(details.data.sections ?? []).map(
134
+ (section) =>
135
+ `${section.title}: ${section.status}${section.reason ? ` — ${section.reason}` : ""}`,
136
+ ),
137
+ ];
138
+ }
139
+ }
140
+
141
+ function searchFacts(data: SearchDetails): string[] {
142
+ const scan = data.scan;
143
+ const lines = [`Search scope: ${data.scope ?? "workspace"}.`];
144
+ if (scan) {
145
+ lines.push(
146
+ `AST universe: ${scan.universe}; complete=${scan.complete}; eligible=${scan.eligibleFileCount ?? "unknown"}; analyzed=${scan.analyzedFileCount}.`,
147
+ ...scan.limitations.map(
148
+ (limit) =>
149
+ `Scan limitation: ${limit.reason}; paths=${limit.pathCount ?? "unknown"}${limit.reason === "unreadable-path" && limit.examples.length ? `; examples=${limit.examples.join(", ")}` : ""}.`,
150
+ ),
151
+ ...(scan.exclusions.length
152
+ ? ["Policy skips are traversal decisions; other explicit scopes may include these paths."]
153
+ : []),
154
+ ...scan.exclusions.map(
155
+ (exclusion) =>
156
+ `Policy skip: ${exclusion.reason}; paths=${exclusion.pathCount}; scope=${exclusion.scopeRoot}.`,
157
+ ),
158
+ );
159
+ }
160
+ if (data.automaticPathExclusion)
161
+ lines.push(`Automatic path exclusions: ${data.automaticPathExclusion.excludedCount}.`);
162
+ if (data.structuralFailures?.length) {
163
+ lines.push(
164
+ `Structural failures: ${data.structuralFailures.length}.`,
165
+ ...data.structuralFailures.slice(0, 3).map((failure) => `${failure.file}: ${failure.reason}`),
166
+ );
167
+ }
168
+ return lines;
169
+ }
170
+
171
+ function healthFacts(data: HealthDetails): string[] {
172
+ const observation = data.diagnosticObservation;
173
+ const lines = [
174
+ `LSP: ${formatSemanticHealthState(data.semanticState)}; structural: ${data.structuralStatus ?? String(data.structuralAvailable)}.`,
175
+ `Server inventory is workspace-wide: ${data.serverCount}; routes: ${JSON.stringify(data.serverRouteStatusCounts)}.`,
176
+ `Refresh: ${data.refresh.kind}. Maintenance recovery is separate from diagnostic confirmation.`,
177
+ ];
178
+ if ("reason" in data.refresh) lines.push(`Refresh reason: ${data.refresh.reason}`);
179
+ if (observation.kind !== "not-requested") {
180
+ const scope = observation.scope;
181
+ lines.push(
182
+ `Diagnostics: ${observation.kind}; ${scope.kind === "file" ? `file=${scope.path}` : `tracked-file snapshot; filter=${scope.filter ?? "none"}; not workspace-wide verification`}.`,
183
+ `Diagnostic coverage: requested=${observation.evidence.requested}, confirmed=${observation.evidence.confirmed}, unconfirmed=${observation.evidence.unconfirmed}, failed=${observation.evidence.failed}, removed=${observation.evidence.removed}.`,
184
+ );
185
+ if ("reason" in observation) lines.push(`Diagnostic limitation: ${observation.reason}`);
186
+ if (observation.scopeStatus)
187
+ lines.push(`File scope status: ${JSON.stringify(observation.scopeStatus)}`);
188
+ }
189
+ if (data.capabilityWarnings?.hasWarnings)
190
+ lines.push(
191
+ `Capability warnings: ${data.capabilityWarnings.warnings.length}.`,
192
+ ...data.capabilityWarnings.warnings.slice(0, 3).map((warning) => warning.message),
193
+ );
194
+ return lines;
195
+ }
@@ -0,0 +1,62 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import { Type } from "typebox";
3
+
4
+ /** Collection confidence, independent of result completeness. */
5
+ export const ConfidenceSchema = StringEnum(["semantic", "structural", "heuristic", "unavailable"]);
6
+
7
+ /** Canonical evidence counts; null totals mean collection could not establish completeness. */
8
+ export const EvidenceListSchema = Type.Object(
9
+ {
10
+ key: Type.String(),
11
+ totalCount: Type.Union([Type.Integer(), Type.Null()]),
12
+ shownCount: Type.Integer(),
13
+ omittedCount: Type.Union([Type.Integer(), Type.Null()]),
14
+ partialReason: Type.Union([Type.String(), Type.Null()]),
15
+ partialMessage: Type.Optional(Type.String()),
16
+ invalidLocationCount: Type.Optional(Type.Integer()),
17
+ },
18
+ { additionalProperties: false },
19
+ );
20
+
21
+ /** Provider recovery ranges use zero-based UTF-16 positions. */
22
+ export const RecoveryRangeSchema = Type.Object({
23
+ start: Type.Object({ line: Type.Integer(), character: Type.Integer() }),
24
+ end: Type.Object({ line: Type.Integer(), character: Type.Integer() }),
25
+ });
26
+
27
+ /** Reusable target handle with one-based UTF-16 coordinates, never a mutable store entry. */
28
+ export const NavigationTargetSchema = Type.Object(
29
+ {
30
+ handle: Type.String(),
31
+ name: Type.Union([Type.String(), Type.Null()]),
32
+ kind: Type.Union([Type.String(), Type.Null()]),
33
+ nativeKind: Type.Optional(Type.String()),
34
+ file: Type.String(),
35
+ line: Type.Integer(),
36
+ character: Type.Integer(),
37
+ anchorKind: StringEnum(["name", "declaration"]),
38
+ container: Type.Optional(Type.Union([Type.String(), Type.Null()])),
39
+ confidence: Type.Optional(ConfidenceSchema),
40
+ provenance: Type.Optional(Type.Array(StringEnum(["semantic", "structural"]))),
41
+ resolution: Type.Optional(
42
+ Type.Object({
43
+ requested: Type.Object({ line: Type.Integer(), character: Type.Integer() }),
44
+ resolved: Type.Object({ line: Type.Integer(), character: Type.Integer() }),
45
+ snapped: Type.Boolean(),
46
+ source: StringEnum(["semantic", "structural", "structural-identifier"]),
47
+ }),
48
+ ),
49
+ },
50
+ { additionalProperties: false },
51
+ );
52
+
53
+ /** Source ranges suggested for a subsequent read, not additional code evidence. */
54
+ export const ReadNextSchema = Type.Object(
55
+ {
56
+ file: Type.String(),
57
+ startLine: Type.Integer(),
58
+ endLine: Type.Integer(),
59
+ reason: Type.String(),
60
+ },
61
+ { additionalProperties: false },
62
+ );
@@ -18,7 +18,7 @@ import type {
18
18
  HealthSection,
19
19
  SemanticHealthState,
20
20
  } from "../../session/health-types.ts";
21
- import type { InspectResultData } from "../../session/inspect-types.ts";
21
+ import type { InspectDiagnostic, InspectResultData } from "../../session/inspect-types.ts";
22
22
  import type { TargetSymbolKind } from "../../session/target-input.ts";
23
23
  import type {
24
24
  AnchorKind,
@@ -32,7 +32,7 @@ export type ToolResultStatus = "completed" | "invalid-input" | "disambiguation"
32
32
 
33
33
  /** Separate model-content and human-display bounds, with one optional continuation file. */
34
34
  export interface ToolOutputTruncationDetails {
35
- /** Model content exceeded the PI output limit. */
35
+ /** Model content exceeded its economic budget or the PI safety limit. */
36
36
  truncated: boolean;
37
37
  /** The TUI omits evidence that remains in the model content. */
38
38
  displayTruncated?: boolean;
@@ -51,6 +51,12 @@ export interface ToolDisplaySection {
51
51
  partialReason: string | null;
52
52
  /** Provider explanation for incomplete collection, when available. */
53
53
  partialMessage?: string;
54
+ /** Content counts are separate from canonical evidence when rows are grouped or framed. */
55
+ preview?: {
56
+ unit: "group" | "block";
57
+ /** Assembly-owned canonical evidence summary, not evidence inferred from display rows. */
58
+ evidenceSummary?: string;
59
+ };
54
60
  }
55
61
 
56
62
  // ── Anchored coordinate resolution metadata ───────────────────────────
@@ -238,6 +244,8 @@ export interface InspectDetails {
238
244
  confidence: ConfidenceMode;
239
245
  focusTarget: string;
240
246
  diagnosticWindow: { startLine: number; endLine: number } | null;
247
+ /** Bounded diagnostic facts, independent of TUI preview strings. */
248
+ diagnostics?: readonly InspectDiagnostic[];
241
249
  sections: InspectSectionDetails[];
242
250
  evidenceLists?: EvidenceListMetadata[];
243
251
  nextQueries: string[];
package/src/tool/specs.ts CHANGED
@@ -28,6 +28,8 @@ export interface CodeIntelligenceToolDefinitionSpec {
28
28
  name: CodeIntelligenceToolName;
29
29
  label: string;
30
30
  parameters: TSchema;
31
+ /** Machine-readable success and recoverable-input outcomes for programmatic callers. */
32
+ outputSchema?: TSchema;
31
33
  maxLines?: number;
32
34
  maxBytes?: number;
33
35
  run: (params: unknown, ctx: CodeIntelToolExecCtx) => Promise<CodeIntelResult> | CodeIntelResult;
@@ -1,4 +1,4 @@
1
- import type { AgentToolUpdateCallback } from "@earendil-works/pi-coding-agent";
1
+ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-coding-agent";
2
2
  import type { WorkspaceCodeIntelligenceSession } from "../session/session.ts";
3
3
  import type { GraphDetails } from "../tool/code_graph/details.ts";
4
4
  import type {
@@ -51,6 +51,8 @@ export interface CodeIntelResultDetails {
51
51
  message?: string;
52
52
  displaySections?: readonly ToolDisplaySection[];
53
53
  truncation?: ToolOutputTruncationDetails;
54
+ /** Workspace navigation and instruction delivery already own a separate model budget. */
55
+ modelBudgetManaged?: boolean;
54
56
  /** UI/debug-only soft-budget warning; never part of model content. */
55
57
  budgetWarning?: import("../tool/code_orientation/workspace-output.ts").WorkspaceBudgetWarning;
56
58
  }
@@ -58,6 +60,8 @@ export interface CodeIntelResultDetails {
58
60
  /** Tool result shape returned by executeAction. */
59
61
  export interface CodeIntelResult {
60
62
  content: string;
63
+ /** Caller-facing JSON for codemode; independent of UI details and model-visible text. */
64
+ structuredContent?: AgentToolResult<unknown>["structuredContent"];
61
65
  details?:
62
66
  | (CodeIntelResultDetails & { type: "context"; data: ContextDetails })
63
67
  | (CodeIntelResultDetails & { type: "inspect"; data: InspectDetails })
@@ -20,18 +20,24 @@ export function renderToolDisplaySections(
20
20
  }
21
21
 
22
22
  function formatDisplayBounds(section: ToolDisplaySection): string {
23
+ const summary = section.preview?.evidenceSummary;
24
+ const prefix = summary ? `${summary}; ` : "";
25
+ const unit = section.preview?.unit;
26
+ const label = (count: number) => (unit ? ` preview ${unit}${count === 1 ? "" : "s"}` : "");
23
27
  if (section.totalCount === null) {
24
- const omitted = section.omittedCount ? `; ${section.omittedCount} collected omitted` : "";
28
+ const omitted = section.omittedCount
29
+ ? `; ${section.omittedCount}${label(section.omittedCount)} collected omitted`
30
+ : "";
25
31
  const reason = section.partialReason
26
32
  ? `; more may exist — ${section.partialReason}`
27
33
  : "; partial";
28
34
  const message = section.partialMessage ? `; ${section.partialMessage}` : "";
29
- return ` (${section.shownCount}${omitted}${reason}${message})`;
35
+ return ` (${prefix}${section.shownCount}${label(section.shownCount)}${omitted}${reason}${message})`;
30
36
  }
31
37
  if (section.omittedCount && section.omittedCount > 0) {
32
- return ` (${section.shownCount} of ${section.totalCount}; ${section.omittedCount} omitted)`;
38
+ return ` (${prefix}${section.shownCount} of ${section.totalCount}${label(section.totalCount)}; ${section.omittedCount}${label(section.omittedCount)} omitted)`;
33
39
  }
34
- return ` (${section.totalCount})`;
40
+ return ` (${prefix}${section.totalCount}${label(section.totalCount)})`;
35
41
  }
36
42
 
37
43
  /** Format one call argument for a compact human transcript row. */