@floydous/pi-agent-kernel 0.4.3 → 0.6.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 (65) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +6 -54
  4. package/config.example.toml +1 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +11 -10
  8. package/docs/editing-and-verification.md +21 -8
  9. package/docs/podman-linux-checks.md +24 -0
  10. package/docs/release-discipline.md +10 -0
  11. package/docs/retrieval.md +21 -23
  12. package/docs/testing.md +3 -3
  13. package/grammars/tree-sitter-html.wasm +0 -0
  14. package/package.json +5 -3
  15. package/src/config/agent_kernel_command.ts +60 -625
  16. package/src/config/kernel_config.ts +53 -69
  17. package/src/config/toml.ts +6 -1
  18. package/src/editing/auto_heal.ts +1 -1
  19. package/src/editing/patch.ts +75 -37
  20. package/src/editing/post_edit_verification.ts +20 -14
  21. package/src/editing/smart_anchor.ts +9 -6
  22. package/src/editing/syntax-verify.ts +79 -222
  23. package/src/index.ts +36 -453
  24. package/src/retrieval/html_chunker.ts +526 -0
  25. package/src/retrieval/search_bm25.ts +39 -28
  26. package/src/retrieval/search_chunker.ts +69 -7
  27. package/src/retrieval/search_config.ts +21 -40
  28. package/src/retrieval/search_embedder.ts +14 -31
  29. package/src/retrieval/search_index.ts +338 -129
  30. package/src/retrieval/search_modal.ts +1208 -222
  31. package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
  32. package/src/retrieval/tree_sitter_engine.ts +171 -36
  33. package/src/retrieval/workspace_walker.ts +78 -2
  34. package/src/safety/atomic_write.ts +1 -1
  35. package/src/safety/epistemic_guard.ts +105 -31
  36. package/src/safety/host_environment.ts +180 -0
  37. package/src/safety/output_clamper.ts +97 -27
  38. package/src/tools/code_search_output.ts +11 -2
  39. package/src/tools/code_search_tool.ts +25 -13
  40. package/src/tools/context.ts +11 -10
  41. package/src/tools/edit_tool.ts +243 -154
  42. package/src/tools/read_tool.ts +285 -214
  43. package/src/tools/stream_reader.ts +206 -0
  44. package/src/ui/footer.ts +7 -7
  45. package/docs/lsp.md +0 -31
  46. package/src/lsp/adapters/base.ts +0 -42
  47. package/src/lsp/adapters/index.ts +0 -21
  48. package/src/lsp/adapters/python.ts +0 -37
  49. package/src/lsp/adapters/rust.ts +0 -35
  50. package/src/lsp/adapters/typescript.ts +0 -40
  51. package/src/lsp/index.ts +0 -13
  52. package/src/lsp/lsp_client.ts +0 -765
  53. package/src/lsp/lsp_detector.ts +0 -52
  54. package/src/lsp/lsp_formatter.ts +0 -323
  55. package/src/lsp/lsp_installer.ts +0 -320
  56. package/src/lsp/lsp_manager.ts +0 -202
  57. package/src/lsp/lsp_modal.ts +0 -675
  58. package/src/lsp/lsp_registry.ts +0 -600
  59. package/src/lsp/lsp_types.ts +0 -143
  60. package/src/retrieval/ast_search.ts +0 -999
  61. package/src/retrieval/symbol_reader.ts +0 -228
  62. package/src/tools/ast_search_formatter.ts +0 -161
  63. package/src/tools/ast_search_tool.ts +0 -146
  64. package/src/tools/lsp_tool.ts +0 -794
  65. package/src/tools/repo_map_tool.ts +0 -56
@@ -1,6 +1,8 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
- import { execFileSync } from "child_process";
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { execFileSync } from "node:child_process";
5
+ import { TreeSitterEngine } from "../retrieval/tree_sitter_engine";
4
6
 
5
7
  export interface VerificationResult {
6
8
  valid: boolean;
@@ -8,200 +10,6 @@ export interface VerificationResult {
8
10
  error?: string;
9
11
  }
10
12
 
11
- /**
12
- * Structural syntax validation for TypeScript/JSX files.
13
- *
14
- * `node --check` cannot parse TS and a full `tsc` parse is too slow for a
15
- * per-edit gate, so this strips comments and string/template literals
16
- * (respecting escapes) and verifies that all delimiters — ( ) [ ] { } — are
17
- * balanced. This deterministically catches the dominant per-edit failure
18
- * class: truncated replacements, missing closing braces/parens, unterminated
19
- * strings or block comments. It is NOT a full parse; type errors remain the
20
- * job of the post-edit LSP diagnostics hook.
21
- */
22
- /**
23
- * Decides whether a '/' at the current position starts a regex literal
24
- * rather than a division operator. Standard lexer heuristic:
25
- * - right after certain keywords (return /re/, typeof /re/, ...) -> regex
26
- * - right after any other identifier/number -> division (x / 2)
27
- * - right after ')', ']', '}', '.', or a closing quote -> division
28
- * - anywhere else (start of file, after operators, '(', '=', ',', etc.)
29
- * -> regex
30
- */
31
- const REGEX_PRECEDING_KEYWORDS = new Set([
32
- "return",
33
- "typeof",
34
- "instanceof",
35
- "in",
36
- "of",
37
- "new",
38
- "delete",
39
- "void",
40
- "throw",
41
- "case",
42
- "do",
43
- "else",
44
- "yield",
45
- "await",
46
- ]);
47
-
48
- function regexCanStart(prevSig: string, lastWord: string): boolean {
49
- if (lastWord) return REGEX_PRECEDING_KEYWORDS.has(lastWord);
50
- if (prevSig === "") return true;
51
- return !")]}\"'`.".includes(prevSig);
52
- }
53
-
54
- function checkTsStructure(content: string): string | null {
55
- const stack: { ch: string; line: number; isTemplateInterp?: boolean }[] = [];
56
- let line = 1;
57
- let i = 0;
58
- // State machine over raw source: code | 'str' | "str" | `tpl` | //line | /*block */ | /regex/
59
- type State =
60
- | "code"
61
- | "squote"
62
- | "dquote"
63
- | "template"
64
- | "lineComment"
65
- | "blockComment"
66
- | "regex";
67
- let state: State = "code";
68
- // Inside a regex character class [...], '/' does not terminate the regex.
69
- let inCharClass = false;
70
- // Last significant (non-whitespace) char seen in code state — used to
71
- // decide whether a '/' starts a regex literal or is a division operator.
72
- let prevSig = "";
73
- // Current identifier/number token being scanned (for keyword detection).
74
- let lastWord = "";
75
- const closers: Record<string, string> = {
76
- ")": "(",
77
- "]": "[",
78
- "}": "{",
79
- };
80
-
81
- while (i < content.length) {
82
- const ch = content[i];
83
- const next = content[i + 1];
84
- if (ch === "\n") {
85
- line++;
86
- if (state === "lineComment" || state === "regex") state = "code";
87
- i++;
88
- continue;
89
- }
90
-
91
- switch (state) {
92
- case "lineComment":
93
- break;
94
- case "blockComment":
95
- if (ch === "*" && next === "/") {
96
- state = "code";
97
- i++;
98
- }
99
- break;
100
- case "squote":
101
- if (ch === "\\") i++;
102
- else if (ch === "'") {
103
- state = "code";
104
- prevSig = "'";
105
- lastWord = "";
106
- }
107
- break;
108
- case "dquote":
109
- if (ch === "\\") i++;
110
- else if (ch === '"') {
111
- state = "code";
112
- prevSig = '"';
113
- lastWord = "";
114
- }
115
- break;
116
- case "template":
117
- if (ch === "\\") {
118
- i++;
119
- } else if (ch === "$" && next === "{") {
120
- stack.push({ ch: "{", line, isTemplateInterp: true });
121
- state = "code";
122
- i++;
123
- } else if (ch === "`") {
124
- state = "code";
125
- prevSig = "`";
126
- lastWord = "";
127
- }
128
- break;
129
- case "code":
130
- if (ch === "/" && next === "/") {
131
- state = "lineComment";
132
- i++;
133
- } else if (ch === "/" && next === "*") {
134
- state = "blockComment";
135
- i++;
136
- } else if (ch === "/" && prevSig !== "<" && next !== ">" && regexCanStart(prevSig, lastWord)) {
137
- // Regex literal (division makes no sense at this position).
138
- // Delimiters inside it are pattern syntax, not code structure.
139
- state = "regex";
140
- inCharClass = false;
141
- lastWord = "";
142
- } else if (ch === "'") {
143
- state = "squote";
144
- prevSig = "'";
145
- lastWord = "";
146
- } else if (ch === '"') {
147
- state = "dquote";
148
- prevSig = '"';
149
- lastWord = "";
150
- } else if (ch === "`") {
151
- state = "template";
152
- prevSig = "`";
153
- lastWord = "";
154
- } else if (ch === "(" || ch === "[" || ch === "{") {
155
- stack.push({ ch, line });
156
- } else if (ch === ")" || ch === "]" || ch === "}") {
157
- const top = stack.pop();
158
- if (!top || top.ch !== closers[ch]) {
159
- return `Unbalanced '${ch}' on line ${line}${top ? ` (unclosed '${top.ch}' from line ${top.line})` : " (no matching opener)"}`;
160
- }
161
- if (top.isTemplateInterp) {
162
- state = "template";
163
- prevSig = "}";
164
- lastWord = "";
165
- }
166
- }
167
- if (!/\s/.test(ch)) prevSig = ch;
168
- // Accumulate identifier/number tokens; whitespace preserves the
169
- // token (so 'return /re/' and 'x / 2' both resolve correctly),
170
- // while any other character ends it.
171
- if (/\s/.test(ch)) {
172
- // keep lastWord
173
- } else if (/[A-Za-z0-9_$]/.test(ch)) {
174
- lastWord += ch;
175
- } else {
176
- lastWord = "";
177
- }
178
- break;
179
- case "regex":
180
- if (ch === "\\") i++;
181
- else if (ch === "[") inCharClass = true;
182
- else if (ch === "]") inCharClass = false;
183
- else if (ch === "/" && !inCharClass) state = "code";
184
- break;
185
- }
186
- i++;
187
- }
188
-
189
- if (state === "squote" || state === "dquote") {
190
- return `Unterminated string literal (reached end of file, last line ${line})`;
191
- }
192
- if (state === "template") {
193
- return `Unterminated template literal (reached end of file, last line ${line})`;
194
- }
195
- if (state === "blockComment") {
196
- return `Unterminated block comment (last line ${line})`;
197
- }
198
- if (stack.length > 0) {
199
- const unclosed = stack[stack.length - 1];
200
- return `Unclosed '${unclosed.ch}' opened on line ${unclosed.line} (still open at end of file)`;
201
- }
202
- return null;
203
- }
204
-
205
13
  let cachedNodeExec: { bin: string; env?: Record<string, string> } | null | undefined;
206
14
 
207
15
  export function resolveNodeExecutable(): { bin: string; env?: Record<string, string> } | null {
@@ -228,7 +36,9 @@ export function resolveNodeExecutable(): { bin: string; env?: Record<string, str
228
36
  cachedNodeExec = cand;
229
37
  return cand;
230
38
  }
231
- } catch {}
39
+ } catch (error) {
40
+ void error;
41
+ }
232
42
  }
233
43
 
234
44
  cachedNodeExec = null;
@@ -333,22 +143,6 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
333
143
  ext === ".mts" ||
334
144
  ext === ".cts"
335
145
  ) {
336
- const isJsx = ext === ".tsx" || ext === ".jsx";
337
- // JSX/TSX text contains arbitrary unescaped delimiters (e.g. <p>step (1)</p>)
338
- // that a naive bracket counter misidentifies. For JSX, tsc with --jsx preserve
339
- // performs complete and authoritative syntax validation.
340
- if (!isJsx) {
341
- const tsContent = fs.readFileSync(resolvedPath, "utf8");
342
- const structuralError = checkTsStructure(tsContent);
343
- if (structuralError) {
344
- return {
345
- valid: false,
346
- status: "failed",
347
- error: `Syntax validation failed on ${path.basename(resolvedPath)}:\n${structuralError}`,
348
- };
349
- }
350
- }
351
-
352
146
  const nodeExec = resolveNodeExecutable();
353
147
  const compiler = resolveTypeScriptCompiler();
354
148
  if (!nodeExec || !fs.existsSync(compiler)) {
@@ -423,28 +217,91 @@ export function checkSyntax(filePath: string): VerificationResult {
423
217
  const resolvedPath = path.isAbsolute(filePath)
424
218
  ? filePath
425
219
  : path.resolve(process.cwd(), filePath);
426
- return validateSyntaxAtPath(resolvedPath);
220
+ if (!fs.existsSync(resolvedPath)) {
221
+ return { valid: true, status: "clean" };
222
+ }
223
+ let content: string;
224
+ try {
225
+ content = fs.readFileSync(resolvedPath, "utf8");
226
+ } catch (err: any) {
227
+ return {
228
+ valid: false,
229
+ status: "inconclusive",
230
+ error: `Syntax validation could not read ${path.basename(resolvedPath)}: ${err.message || String(err)}`,
231
+ };
232
+ }
233
+ return checkSyntaxContent(resolvedPath, content);
234
+ }
235
+
236
+ // Checked by their own parser in validateSyntaxAtPath; tree-sitter only speeds up the TypeScript family.
237
+ const PARSER_CHECKED = new Set([".py", ".json", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".mts", ".cts"]);
238
+ const TYPESCRIPT_FAMILY = new Set([".ts", ".tsx", ".jsx", ".mts", ".cts"]);
239
+
240
+ // Error recovery can wrap a whole block in one error (e.g. a missing closing brace), so multi-line errors show their span.
241
+ function formatTreeSitterErrors(errors: Array<{ line: number; column: number; endLine: number; missing?: string; text?: string }>): string {
242
+ const shown = errors.slice(0, 3).map((e) => {
243
+ if (e.missing !== undefined) return `[${e.line}:${e.column}] missing "${e.missing}"`;
244
+ return e.endLine > e.line
245
+ ? `[${e.line}:${e.column}] cannot parse lines ${e.line}-${e.endLine}, starting "${e.text}"`
246
+ : `[${e.line}:${e.column}] unexpected "${e.text}"`;
247
+ });
248
+ return `tree-sitter found a syntax error: ${shown.join("; ")}${errors.length > 3 ? `; +${errors.length - 3} more` : ""}`;
427
249
  }
428
250
 
429
251
  /**
430
- * Validate candidate content without changing the target file.
431
- * File-oriented validators run against a temporary sibling with the same
432
- * extension, which keeps their existing behavior while protecting the target.
252
+ * Validate candidate content without changing the target file. Pass the file's current content as `original` so that
253
+ * tree-sitter can judge only what the edit changed (rules measured in .research/syntax-validation/):
254
+ * - TypeScript family: clean when tree-sitter finds no error in the candidate or the original; otherwise tsc decides,
255
+ * because the grammar lags the language (e.g. `interface I<out T>`).
256
+ * - Languages with a grammar but no parser here (Rust, Go, C/C++, Java, C#, Ruby, PHP, Bash): tree-sitter errors are
257
+ * reported only when the original parsed without errors; otherwise the check is not run.
258
+ * - JavaScript, Python, JSON: always their own parser (tree-sitter misses JS early errors and Python indentation).
259
+ * Call TreeSitterEngine.loadLanguages for the extension first; without a loaded grammar the parsers decide alone.
433
260
  */
434
261
  export function checkSyntaxContent(
435
262
  filePath: string,
436
263
  content: string,
264
+ original?: string,
437
265
  ): VerificationResult {
438
266
  const resolvedPath = path.isAbsolute(filePath)
439
267
  ? filePath
440
268
  : path.resolve(process.cwd(), filePath);
441
- const extension = path.extname(resolvedPath) || ".tmp";
269
+ const ext = path.extname(resolvedPath).toLowerCase();
270
+ if (TYPESCRIPT_FAMILY.has(ext) || !PARSER_CHECKED.has(ext)) {
271
+ const engine = TreeSitterEngine.getInstance();
272
+ const errors = engine.findSyntaxErrors(ext, content);
273
+ const originalErrors = original === undefined ? undefined : engine.findSyntaxErrors(ext, original);
274
+ if (!TYPESCRIPT_FAMILY.has(ext)) {
275
+ if (!errors || !originalErrors || originalErrors.length > 0) return { valid: true, status: "not run" };
276
+ return errors.length === 0
277
+ ? { valid: true, status: "clean" }
278
+ : { valid: false, status: "failed", error: formatTreeSitterErrors(errors) };
279
+ }
280
+ if (errors?.length === 0 && !originalErrors?.length) return { valid: true, status: "clean" };
281
+ }
282
+
283
+ // `node --check` passes ES-module syntax errors in a .js file whose package.json sets no "type" (Node 24), so a
284
+ // .js candidate is checked as .mjs and .cjs: valid when either parses, as Node itself decides at run time.
285
+ const extensions = ext === ".js"
286
+ ? (/^\s*(import|export)\b/m.test(content) ? [".mjs", ".cjs"] : [".cjs", ".mjs"])
287
+ : [path.extname(resolvedPath) || ".tmp"];
288
+ let result: VerificationResult | undefined;
289
+ for (const extension of extensions) {
290
+ const res = validateCandidate(content, extension);
291
+ if (res.valid) return res;
292
+ result ??= res;
293
+ }
294
+ return result!;
295
+ }
296
+
297
+ /** Run the file-oriented validators on a temporary copy, so the target is never touched. */
298
+ function validateCandidate(content: string, extension: string): VerificationResult {
442
299
  let tempDir: string | undefined;
443
300
 
444
301
  try {
445
- tempDir = fs.mkdtempSync(
446
- path.join(path.dirname(resolvedPath), ".pi-agent-kernel-validate-"),
447
- );
302
+ // Outside the project, so file watchers never see it; the validators do not depend on the location
303
+ // (tsc ignores tsconfig, and .js is checked with an explicit module type).
304
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), ".pi-agent-kernel-validate-"));
448
305
  const candidatePath = path.join(tempDir, `candidate${extension}`);
449
306
  fs.writeFileSync(candidatePath, content, "utf8");
450
307
  const res = validateSyntaxAtPath(candidatePath);