@floydous/pi-agent-kernel 0.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 (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +108 -0
  3. package/config.toml +24 -0
  4. package/docs/README.md +22 -0
  5. package/docs/architecture.md +40 -0
  6. package/docs/configuration.md +43 -0
  7. package/docs/editing-and-verification.md +41 -0
  8. package/docs/lsp.md +31 -0
  9. package/docs/retrieval.md +42 -0
  10. package/docs/testing.md +32 -0
  11. package/package.json +48 -0
  12. package/src/config/index.ts +2 -0
  13. package/src/config/kernel_config.ts +218 -0
  14. package/src/config/toml.ts +237 -0
  15. package/src/context/session_repair.ts +99 -0
  16. package/src/dedup/content_store.ts +365 -0
  17. package/src/dedup/recall_tool.ts +157 -0
  18. package/src/editing/patch.ts +482 -0
  19. package/src/editing/post_edit_verification.ts +200 -0
  20. package/src/editing/syntax-verify.ts +353 -0
  21. package/src/index.ts +852 -0
  22. package/src/lsp/adapters/base.ts +42 -0
  23. package/src/lsp/adapters/index.ts +21 -0
  24. package/src/lsp/adapters/python.ts +37 -0
  25. package/src/lsp/adapters/rust.ts +35 -0
  26. package/src/lsp/adapters/typescript.ts +40 -0
  27. package/src/lsp/index.ts +13 -0
  28. package/src/lsp/lsp_client.ts +650 -0
  29. package/src/lsp/lsp_detector.ts +52 -0
  30. package/src/lsp/lsp_formatter.ts +284 -0
  31. package/src/lsp/lsp_installer.ts +604 -0
  32. package/src/lsp/lsp_manager.ts +202 -0
  33. package/src/lsp/lsp_modal.ts +675 -0
  34. package/src/lsp/lsp_registry.ts +539 -0
  35. package/src/lsp/lsp_types.ts +143 -0
  36. package/src/retrieval/ast_search.ts +926 -0
  37. package/src/retrieval/repomap.ts +779 -0
  38. package/src/retrieval/search_bm25.ts +190 -0
  39. package/src/retrieval/search_chunker.ts +251 -0
  40. package/src/retrieval/search_config.ts +162 -0
  41. package/src/retrieval/search_embedder.ts +362 -0
  42. package/src/retrieval/search_index.ts +753 -0
  43. package/src/retrieval/search_modal.ts +358 -0
  44. package/src/retrieval/symbol_reader.ts +200 -0
  45. package/src/safety/atomic_write.ts +26 -0
  46. package/src/safety/epistemic_guard.ts +733 -0
  47. package/src/safety/kernel_debug.ts +15 -0
  48. package/src/safety/output_clamper.ts +213 -0
  49. package/src/tools/ast_search_tool.ts +131 -0
  50. package/src/tools/code_search_tool.ts +147 -0
  51. package/src/tools/context.ts +20 -0
  52. package/src/tools/edit_tool.ts +288 -0
  53. package/src/tools/lsp_tool.ts +813 -0
  54. package/src/tools/read_tool.ts +348 -0
  55. package/src/tools/repo_map_tool.ts +57 -0
  56. package/src/ui/footer.ts +287 -0
  57. package/src/ui/tui_utils.ts +278 -0
@@ -0,0 +1,284 @@
1
+ import { pathToFileURL, fileURLToPath } from "node:url";
2
+ import * as path from "node:path";
3
+ import * as fs from "node:fs";
4
+ import {
5
+ LspDiagnostic,
6
+ LspDiagnosticSeverity,
7
+ LspLocation,
8
+ LspLocationLink,
9
+ LspHover,
10
+ LspDocumentSymbol,
11
+ LspSymbolInformation,
12
+ LspSymbolKind,
13
+ } from "./lsp_types";
14
+
15
+ export function normalizeUri(uri: string): string {
16
+ try {
17
+ let p = fileURLToPath(uri);
18
+ if (process.platform === "win32" && /^[a-zA-Z]:/.test(p)) {
19
+ p = p[0].toLowerCase() + p.slice(1);
20
+ }
21
+ const u = pathToFileURL(p).href;
22
+ return u.replace(/^file:\/\/\/([a-zA-Z]):/, (_, letter) => "file:///" + letter.toLowerCase() + ":");
23
+ } catch {
24
+ return uri;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Robust cross-platform path to file:// URI conversion
30
+ */
31
+ export function pathToUri(filePath: string): string {
32
+ const abs = path.resolve(filePath);
33
+ return normalizeUri(pathToFileURL(abs).href);
34
+ }
35
+
36
+ /**
37
+ * Robust cross-platform file:// URI to local file path conversion
38
+ */
39
+ export function uriToPath(uri: string): string {
40
+ try {
41
+ const raw = fileURLToPath(uri);
42
+ if (process.platform === "win32" && /^[a-z]:/i.test(raw)) {
43
+ return raw[0].toUpperCase() + raw.slice(1);
44
+ }
45
+ return raw;
46
+ } catch {
47
+ return uri.replace(/^file:\/\/\/?/, "");
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Format severity enum into concise label
53
+ */
54
+ function severityLabel(severity?: LspDiagnosticSeverity): string {
55
+ switch (severity) {
56
+ case LspDiagnosticSeverity.Error:
57
+ return "ERROR";
58
+ case LspDiagnosticSeverity.Warning:
59
+ return "WARN";
60
+ case LspDiagnosticSeverity.Information:
61
+ return "INFO";
62
+ case LspDiagnosticSeverity.Hint:
63
+ return "HINT";
64
+ default:
65
+ return "DIAG";
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Symbol kind name lookup
71
+ */
72
+ function symbolKindLabel(kind: LspSymbolKind): string {
73
+ return LspSymbolKind[kind]?.toLowerCase() || "symbol";
74
+ }
75
+
76
+ /**
77
+ * Format diagnostics into compact, token-dense text output
78
+ */
79
+ export function formatDiagnostics(
80
+ diagnostics: LspDiagnostic[],
81
+ _filePath?: string,
82
+ _cwd?: string
83
+ ): string {
84
+ if (!diagnostics || diagnostics.length === 0) {
85
+ return "";
86
+ }
87
+
88
+ const lines: string[] = [];
89
+
90
+ for (const d of diagnostics) {
91
+ const sev = severityLabel(d.severity);
92
+ const line = d.range.start.line + 1; // Convert 0-indexed to 1-indexed
93
+ const col = d.range.start.character + 1;
94
+ const codeStr = d.code !== undefined ? ` [${d.code}]` : "";
95
+ const srcStr = d.source ? ` (${d.source})` : "";
96
+ lines.push(`- [${line}:${col}] [${sev}]${codeStr} ${d.message}${srcStr}`);
97
+ }
98
+
99
+ return lines.join("\n");
100
+ }
101
+
102
+ /**
103
+ * Normalize LSP Definition / Location / LocationLink into simple LspLocation[]
104
+ */
105
+ export function normalizeLocations(
106
+ result: LspLocation | LspLocation[] | LspLocationLink[] | null | undefined
107
+ ): LspLocation[] {
108
+ if (!result) return [];
109
+ if (!Array.isArray(result)) return [result];
110
+
111
+ return result.map((item) => {
112
+ if ("targetUri" in item) {
113
+ // LspLocationLink
114
+ return {
115
+ uri: item.targetUri,
116
+ range: item.targetSelectionRange || item.targetRange,
117
+ };
118
+ }
119
+ return item;
120
+ });
121
+ }
122
+
123
+ /**
124
+ * Format definition or declaration locations into compact output
125
+ */
126
+ export function formatDefinitions(
127
+ locations: LspLocation[],
128
+ cwd?: string
129
+ ): string {
130
+ if (!locations || locations.length === 0) {
131
+ return "Definition not found.";
132
+ }
133
+
134
+ const lines = locations.map((loc) => {
135
+ const filePath = uriToPath(loc.uri);
136
+ const displayPath = cwd ? path.relative(cwd, filePath) || filePath : filePath;
137
+ const line = loc.range.start.line + 1;
138
+ const col = loc.range.start.character + 1;
139
+ return `${displayPath}:${line}:${col}`;
140
+ });
141
+
142
+ return lines.join("\n");
143
+ }
144
+
145
+ /**
146
+ * Extract a bounded snippet around the target character span without truncating the symbol.
147
+ */
148
+ export function windowAround(
149
+ line: string,
150
+ startCol0: number,
151
+ endCol0: number,
152
+ budget = 50
153
+ ): string {
154
+ const normLine = line.replace(/\r?\n$/, "");
155
+ const s = Math.max(0, Math.min(startCol0, normLine.length));
156
+ const e = Math.max(s, Math.min(endCol0, normLine.length));
157
+ const symLen = Math.max(1, e - s);
158
+ const effectiveBudget = Math.max(budget, symLen);
159
+ const pad = Math.max(0, effectiveBudget - symLen);
160
+ const left = Math.max(0, s - Math.floor(pad / 2));
161
+ const right = Math.min(normLine.length, e + Math.ceil(pad / 2));
162
+ const snippet = normLine.slice(left, right).trim();
163
+ const prefix = left > 0 ? "... " : "";
164
+ const suffix = right < normLine.length ? " ..." : "";
165
+ return `${prefix}${snippet}${suffix}`.trim();
166
+ }
167
+
168
+ /**
169
+ * Format symbol references into compact output with bounded line snippets.
170
+ * Never leaks read evidence into epistemic ledger (metadata only).
171
+ */
172
+ export function formatReferences(
173
+ references: LspLocation[],
174
+ cwd?: string
175
+ ): string {
176
+ if (!references || references.length === 0) {
177
+ return "No references found.";
178
+ }
179
+
180
+ // Per-query line cache: read each file from disk at most once
181
+ const fileLinesCache = new Map<string, string[] | null>();
182
+
183
+ const getLines = (filePath: string): string[] | null => {
184
+ if (fileLinesCache.has(filePath)) {
185
+ return fileLinesCache.get(filePath)!;
186
+ }
187
+ try {
188
+ if (fs.existsSync(filePath)) {
189
+ const lines = fs.readFileSync(filePath, "utf8").split("\n");
190
+ fileLinesCache.set(filePath, lines);
191
+ return lines;
192
+ }
193
+ } catch {
194
+ // Fall through to null for inaccessible/virtual files
195
+ }
196
+ fileLinesCache.set(filePath, null);
197
+ return null;
198
+ };
199
+
200
+ const lines = references.map((loc) => {
201
+ const filePath = uriToPath(loc.uri);
202
+ const displayPath = cwd ? path.relative(cwd, filePath) || filePath : filePath;
203
+ const line1 = loc.range.start.line + 1;
204
+ const col1 = loc.range.start.character + 1;
205
+ const baseLoc = `${displayPath}:${line1}:${col1}`;
206
+
207
+ const cachedLines = getLines(filePath);
208
+ if (!cachedLines || loc.range.start.line >= cachedLines.length) {
209
+ return baseLoc;
210
+ }
211
+
212
+ const rawLine = cachedLines[loc.range.start.line] || "";
213
+ const startCol0 = loc.range.start.character;
214
+ const endCol0 =
215
+ loc.range.end?.line === loc.range.start.line
216
+ ? loc.range.end.character
217
+ : startCol0 + 1;
218
+
219
+ const snippet = windowAround(rawLine, startCol0, endCol0, 50);
220
+ return snippet ? `${baseLoc}: ${snippet}` : baseLoc;
221
+ });
222
+
223
+ return lines.join("\n");
224
+ }
225
+
226
+ /**
227
+ * Format hover response (type signatures, markdown docstrings)
228
+ */
229
+ export function formatHover(hover: LspHover | null | undefined): string {
230
+ if (!hover || !hover.contents) {
231
+ return "No hover information available at this position.";
232
+ }
233
+
234
+ const extractText = (content: any): string => {
235
+ if (typeof content === "string") return content;
236
+ if (content && typeof content === "object") {
237
+ if ("value" in content) return content.value;
238
+ if (Array.isArray(content)) return content.map(extractText).join("\n");
239
+ }
240
+ return String(content);
241
+ };
242
+
243
+ const rawText = extractText(hover.contents).trim();
244
+ return rawText || "No hover information available.";
245
+ }
246
+
247
+ /**
248
+ * Format document symbols (hierarchical or flat)
249
+ */
250
+ export function formatDocumentSymbols(
251
+ symbols: (LspDocumentSymbol | LspSymbolInformation)[] | null | undefined
252
+ ): string {
253
+ if (!symbols || symbols.length === 0) {
254
+ return "No symbols found.";
255
+ }
256
+
257
+ const lines: string[] = [];
258
+
259
+ const renderSymbol = (s: any, depth = 0) => {
260
+ const indent = " ".repeat(depth);
261
+ const kind = symbolKindLabel(s.kind);
262
+ const range = s.range || s.location?.range;
263
+ const line = range ? range.start.line + 1 : 1;
264
+ const detail = s.detail ? ` (${s.detail})` : "";
265
+ lines.push(`${indent}${line}: [${kind}] ${s.name}${detail}`);
266
+
267
+ if (s.children && Array.isArray(s.children)) {
268
+ for (const child of s.children) {
269
+ renderSymbol(child, depth + 1);
270
+ }
271
+ }
272
+ };
273
+
274
+ for (const s of symbols) {
275
+ renderSymbol(s, 0);
276
+ }
277
+
278
+ // Bounded output to prevent blowing context window on monolithic files
279
+ if (lines.length > 100) {
280
+ return lines.slice(0, 100).join("\n") + `\n\n[Truncated: 100/${lines.length} symbols shown]`;
281
+ }
282
+
283
+ return lines.join("\n");
284
+ }