@floydous/pi-agent-kernel 0.5.0 → 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.
- package/AGENT_KERNEL_SYS_PROMPT.md +15 -6
- package/CHANGELOG.md +51 -0
- package/README.md +2 -3
- package/config.example.toml +1 -0
- package/docs/configuration.md +1 -1
- package/docs/editing-and-verification.md +20 -5
- package/docs/podman-linux-checks.md +24 -0
- package/docs/release-discipline.md +10 -0
- package/docs/retrieval.md +14 -11
- package/grammars/tree-sitter-html.wasm +0 -0
- package/package.json +2 -2
- package/src/config/agent_kernel_command.ts +59 -593
- package/src/config/kernel_config.ts +24 -2
- package/src/editing/patch.ts +48 -21
- package/src/editing/post_edit_verification.ts +8 -4
- package/src/editing/smart_anchor.ts +2 -1
- package/src/editing/syntax-verify.ts +73 -220
- package/src/index.ts +21 -196
- package/src/retrieval/html_chunker.ts +526 -0
- package/src/retrieval/search_bm25.ts +36 -27
- package/src/retrieval/search_chunker.ts +68 -6
- package/src/retrieval/search_config.ts +17 -34
- package/src/retrieval/search_embedder.ts +11 -29
- package/src/retrieval/search_index.ts +307 -145
- package/src/retrieval/search_modal.ts +1209 -222
- package/src/retrieval/tag_extractor.ts +1 -1
- package/src/retrieval/tree_sitter_engine.ts +103 -4
- package/src/retrieval/workspace_walker.ts +72 -0
- package/src/safety/host_environment.ts +180 -0
- package/src/safety/output_clamper.ts +83 -19
- package/src/tools/code_search_output.ts +9 -1
- package/src/tools/code_search_tool.ts +25 -10
- package/src/tools/context.ts +15 -0
- package/src/tools/edit_tool.ts +182 -60
- package/src/tools/read_tool.ts +245 -38
- package/src/tools/stream_reader.ts +206 -0
|
@@ -8,6 +8,7 @@ import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
|
8
8
|
export interface RetrievalConfig {
|
|
9
9
|
default_profile: "auto" | "lean" | "hybrid" | "full" | "off";
|
|
10
10
|
max_search_results: number;
|
|
11
|
+
excluded_paths?: string[];
|
|
11
12
|
}
|
|
12
13
|
|
|
13
14
|
export interface SafetyConfig {
|
|
@@ -23,6 +24,7 @@ export interface EditingConfig {
|
|
|
23
24
|
default_anchors: boolean;
|
|
24
25
|
read_mode: "auto" | "plain" | "anchored";
|
|
25
26
|
syntax_gate?: "warn" | "block";
|
|
27
|
+
normalize_fullwidth_dots?: boolean;
|
|
26
28
|
}
|
|
27
29
|
|
|
28
30
|
export interface KernelConfigOverrides {
|
|
@@ -40,6 +42,7 @@ export interface UiConfig {
|
|
|
40
42
|
export interface InstructionsConfig {
|
|
41
43
|
enabled: boolean;
|
|
42
44
|
pi_docs: boolean;
|
|
45
|
+
host_environment: boolean;
|
|
43
46
|
}
|
|
44
47
|
|
|
45
48
|
export interface KernelConfig {
|
|
@@ -54,6 +57,7 @@ const DEFAULT_CONFIG: KernelConfig = {
|
|
|
54
57
|
retrieval: {
|
|
55
58
|
default_profile: "lean",
|
|
56
59
|
max_search_results: 5,
|
|
60
|
+
excluded_paths: [],
|
|
57
61
|
},
|
|
58
62
|
safety: {
|
|
59
63
|
enable_epistemic_guard: true,
|
|
@@ -67,6 +71,7 @@ const DEFAULT_CONFIG: KernelConfig = {
|
|
|
67
71
|
default_anchors: false,
|
|
68
72
|
read_mode: "plain",
|
|
69
73
|
syntax_gate: "warn",
|
|
74
|
+
normalize_fullwidth_dots: true,
|
|
70
75
|
},
|
|
71
76
|
ui: {
|
|
72
77
|
enable_pastel_footer: true,
|
|
@@ -74,6 +79,7 @@ const DEFAULT_CONFIG: KernelConfig = {
|
|
|
74
79
|
instructions: {
|
|
75
80
|
enabled: true,
|
|
76
81
|
pi_docs: true,
|
|
82
|
+
host_environment: true,
|
|
77
83
|
},
|
|
78
84
|
};
|
|
79
85
|
|
|
@@ -83,6 +89,7 @@ const ALLOWED_CONFIG_KEYS: Record<keyof KernelConfig, ReadonlySet<string>> = {
|
|
|
83
89
|
retrieval: new Set([
|
|
84
90
|
"default_profile",
|
|
85
91
|
"max_search_results",
|
|
92
|
+
"excluded_paths",
|
|
86
93
|
]),
|
|
87
94
|
safety: new Set([
|
|
88
95
|
"enable_epistemic_guard",
|
|
@@ -91,9 +98,9 @@ const ALLOWED_CONFIG_KEYS: Record<keyof KernelConfig, ReadonlySet<string>> = {
|
|
|
91
98
|
"max_total_bytes",
|
|
92
99
|
"exec_timeout_ms",
|
|
93
100
|
]),
|
|
94
|
-
editing: new Set(["mode", "default_anchors", "read_mode", "syntax_gate"]),
|
|
101
|
+
editing: new Set(["mode", "default_anchors", "read_mode", "syntax_gate", "normalize_fullwidth_dots"]),
|
|
95
102
|
ui: new Set(["enable_pastel_footer"]),
|
|
96
|
-
instructions: new Set(["enabled", "pi_docs"]),
|
|
103
|
+
instructions: new Set(["enabled", "pi_docs", "host_environment"]),
|
|
97
104
|
};
|
|
98
105
|
|
|
99
106
|
const DEPRECATED_RETRIEVAL_KEYS = new Set([
|
|
@@ -107,6 +114,12 @@ function configPath(parts: string[]): string {
|
|
|
107
114
|
return parts.join(".");
|
|
108
115
|
}
|
|
109
116
|
|
|
117
|
+
function requireStringArray(value: unknown, path: string): void {
|
|
118
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
|
|
119
|
+
throw new KernelConfigError(`${path} must be an array of strings`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
110
123
|
function requireBoolean(value: unknown, path: string): void {
|
|
111
124
|
if (typeof value !== "boolean") throw new KernelConfigError(`${path} must be a boolean`);
|
|
112
125
|
}
|
|
@@ -139,6 +152,9 @@ export function validateKernelConfig(config: KernelConfig): KernelConfig {
|
|
|
139
152
|
const retrieval = config.retrieval;
|
|
140
153
|
requireEnum(retrieval.default_profile, "retrieval.default_profile", ["auto", "lean", "hybrid", "full", "off"]);
|
|
141
154
|
requireSafeInt(retrieval.max_search_results, "retrieval.max_search_results", 1, 15);
|
|
155
|
+
if (retrieval.excluded_paths !== undefined) {
|
|
156
|
+
requireStringArray(retrieval.excluded_paths, "retrieval.excluded_paths");
|
|
157
|
+
}
|
|
142
158
|
|
|
143
159
|
const safety = config.safety;
|
|
144
160
|
requireBoolean(safety.enable_epistemic_guard, "safety.enable_epistemic_guard");
|
|
@@ -153,10 +169,16 @@ export function validateKernelConfig(config: KernelConfig): KernelConfig {
|
|
|
153
169
|
if (config.editing.syntax_gate !== undefined) {
|
|
154
170
|
requireEnum(config.editing.syntax_gate, "editing.syntax_gate", ["warn", "block"]);
|
|
155
171
|
}
|
|
172
|
+
if (config.editing.normalize_fullwidth_dots !== undefined) {
|
|
173
|
+
requireBoolean(config.editing.normalize_fullwidth_dots, "editing.normalize_fullwidth_dots");
|
|
174
|
+
}
|
|
156
175
|
|
|
157
176
|
requireBoolean(config.ui.enable_pastel_footer, "ui.enable_pastel_footer");
|
|
158
177
|
requireBoolean(config.instructions.enabled, "instructions.enabled");
|
|
159
178
|
requireBoolean(config.instructions.pi_docs, "instructions.pi_docs");
|
|
179
|
+
if (config.instructions.host_environment !== undefined) {
|
|
180
|
+
requireBoolean(config.instructions.host_environment, "instructions.host_environment");
|
|
181
|
+
}
|
|
160
182
|
return config;
|
|
161
183
|
}
|
|
162
184
|
|
package/src/editing/patch.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import { resolveUserPath } from "../safety/epistemic_guard";
|
|
4
4
|
import * as diff from "diff";
|
|
5
|
-
import { checkSyntaxContent } from "./syntax-verify";
|
|
5
|
+
import { checkSyntaxContent, type VerificationResult } from "./syntax-verify";
|
|
6
6
|
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
7
7
|
import { getUnclosedDelimiters, healJsonContent } from "./auto_heal";
|
|
8
8
|
/**
|
|
@@ -20,6 +20,8 @@ export interface PatchResult {
|
|
|
20
20
|
diffOutput?: string;
|
|
21
21
|
error?: string;
|
|
22
22
|
targetRanges?: PatchTargetRange[];
|
|
23
|
+
/** Syntax verdict on the content that was written. */
|
|
24
|
+
syntax?: VerificationResult;
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
export interface PatchBlock {
|
|
@@ -85,14 +87,11 @@ function replaceLineWindow(
|
|
|
85
87
|
replacement: string,
|
|
86
88
|
hadCrlf: boolean,
|
|
87
89
|
): string {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
...contentLines.slice(0, start),
|
|
91
|
-
replacement,
|
|
92
|
-
|
|
93
|
-
].join("\n"),
|
|
94
|
-
hadCrlf,
|
|
95
|
-
);
|
|
90
|
+
const updatedLines =
|
|
91
|
+
replacement === ""
|
|
92
|
+
? [...contentLines.slice(0, start), ...contentLines.slice(start + length)]
|
|
93
|
+
: [...contentLines.slice(0, start), replacement, ...contentLines.slice(start + length)];
|
|
94
|
+
return restoreLineEndings(updatedLines.join("\n"), hadCrlf);
|
|
96
95
|
}
|
|
97
96
|
|
|
98
97
|
function applySingleBlock(
|
|
@@ -141,10 +140,23 @@ function applySingleBlock(
|
|
|
141
140
|
}
|
|
142
141
|
if (exactMatches.length === 1) {
|
|
143
142
|
const start = exactMatches[0];
|
|
143
|
+
let cutStart = start;
|
|
144
|
+
let cutEnd = start + searchNorm.length;
|
|
145
|
+
if (replaceNorm === "") {
|
|
146
|
+
const isLineStart = cutStart === 0 || contentNorm.charAt(cutStart - 1) === "\n";
|
|
147
|
+
const isLineEnd = cutEnd === contentNorm.length || contentNorm.charAt(cutEnd) === "\n";
|
|
148
|
+
if (isLineStart && isLineEnd) {
|
|
149
|
+
if (cutEnd < contentNorm.length && contentNorm.charAt(cutEnd) === "\n") {
|
|
150
|
+
cutEnd++;
|
|
151
|
+
} else if (cutStart > 0 && contentNorm.charAt(cutStart - 1) === "\n") {
|
|
152
|
+
cutStart--;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
144
156
|
const newContent =
|
|
145
|
-
contentNorm.slice(0,
|
|
157
|
+
contentNorm.slice(0, cutStart) +
|
|
146
158
|
replaceNorm +
|
|
147
|
-
contentNorm.slice(
|
|
159
|
+
contentNorm.slice(cutEnd);
|
|
148
160
|
return {
|
|
149
161
|
success: true,
|
|
150
162
|
newContent: restoreLineEndings(newContent, hadCrlf),
|
|
@@ -166,10 +178,23 @@ function applySingleBlock(
|
|
|
166
178
|
}
|
|
167
179
|
}
|
|
168
180
|
const start = bestOffset;
|
|
181
|
+
let cutStart = start;
|
|
182
|
+
let cutEnd = start + searchNorm.length;
|
|
183
|
+
if (replaceNorm === "") {
|
|
184
|
+
const isLineStart = cutStart === 0 || contentNorm.charAt(cutStart - 1) === "\n";
|
|
185
|
+
const isLineEnd = cutEnd === contentNorm.length || contentNorm.charAt(cutEnd) === "\n";
|
|
186
|
+
if (isLineStart && isLineEnd) {
|
|
187
|
+
if (cutEnd < contentNorm.length && contentNorm.charAt(cutEnd) === "\n") {
|
|
188
|
+
cutEnd++;
|
|
189
|
+
} else if (cutStart > 0 && contentNorm.charAt(cutStart - 1) === "\n") {
|
|
190
|
+
cutStart--;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
169
194
|
const newContent =
|
|
170
|
-
contentNorm.slice(0,
|
|
195
|
+
contentNorm.slice(0, cutStart) +
|
|
171
196
|
replaceNorm +
|
|
172
|
-
contentNorm.slice(
|
|
197
|
+
contentNorm.slice(cutEnd);
|
|
173
198
|
return {
|
|
174
199
|
success: true,
|
|
175
200
|
newContent: restoreLineEndings(newContent, hadCrlf),
|
|
@@ -461,7 +486,7 @@ export function applySurgicalPatch(
|
|
|
461
486
|
}
|
|
462
487
|
|
|
463
488
|
let candidateContent = result.newContent;
|
|
464
|
-
let syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
489
|
+
let syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
465
490
|
let autoHealed = false;
|
|
466
491
|
|
|
467
492
|
// Delimiter & Bracket Auto-Healing:
|
|
@@ -471,7 +496,7 @@ export function applySurgicalPatch(
|
|
|
471
496
|
const healedJson = healJsonContent(candidateContent);
|
|
472
497
|
if (healedJson) {
|
|
473
498
|
candidateContent = healedJson;
|
|
474
|
-
syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
499
|
+
syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
475
500
|
autoHealed = syntax.valid;
|
|
476
501
|
}
|
|
477
502
|
} else if (options?.autoHeal !== false) {
|
|
@@ -482,7 +507,7 @@ export function applySurgicalPatch(
|
|
|
482
507
|
const retryReplace = replace + appendDelims;
|
|
483
508
|
const reResult = applySingleBlock(originalContent, search, retryReplace, options);
|
|
484
509
|
if (reResult.success) {
|
|
485
|
-
const reSyntax = checkSyntaxContent(resolvedPath, reResult.newContent);
|
|
510
|
+
const reSyntax = checkSyntaxContent(resolvedPath, reResult.newContent, originalContent);
|
|
486
511
|
if (reSyntax.valid) {
|
|
487
512
|
candidateContent = reResult.newContent;
|
|
488
513
|
syntax = reSyntax;
|
|
@@ -527,6 +552,7 @@ export function applySurgicalPatch(
|
|
|
527
552
|
filePath: resolvedPath,
|
|
528
553
|
strategy: finalStrategy,
|
|
529
554
|
targetRanges: result.targetRange ? [result.targetRange] : [],
|
|
555
|
+
syntax,
|
|
530
556
|
diffOutput: diff.createPatch(
|
|
531
557
|
path.basename(resolvedPath),
|
|
532
558
|
originalContent,
|
|
@@ -636,15 +662,15 @@ export function applyMultiBlockPatch(
|
|
|
636
662
|
error: `Block ${i + 1}/${blocks.length} failed: ${result.error} in ${resolvedPath}`,
|
|
637
663
|
};
|
|
638
664
|
}
|
|
639
|
-
const
|
|
640
|
-
const replaceCount = block.replace.split("\n").length;
|
|
641
|
-
lineDelta += (replaceCount - searchCount);
|
|
665
|
+
const beforeLines = currentContent.split("\n").length;
|
|
642
666
|
currentContent = result.newContent;
|
|
667
|
+
const afterLines = currentContent.split("\n").length;
|
|
668
|
+
lineDelta += (afterLines - beforeLines);
|
|
643
669
|
appliedStrategies.push(`Block ${i + 1}: ${result.strategy}`);
|
|
644
670
|
}
|
|
645
671
|
|
|
646
672
|
let candidateContent = currentContent;
|
|
647
|
-
let syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
673
|
+
let syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
648
674
|
let autoHealed = false;
|
|
649
675
|
|
|
650
676
|
if (!syntax.valid) {
|
|
@@ -653,7 +679,7 @@ export function applyMultiBlockPatch(
|
|
|
653
679
|
const healedJson = healJsonContent(candidateContent);
|
|
654
680
|
if (healedJson) {
|
|
655
681
|
candidateContent = healedJson;
|
|
656
|
-
syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
682
|
+
syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
657
683
|
autoHealed = syntax.valid;
|
|
658
684
|
}
|
|
659
685
|
}
|
|
@@ -693,6 +719,7 @@ export function applyMultiBlockPatch(
|
|
|
693
719
|
filePath: resolvedPath,
|
|
694
720
|
strategy: finalStrategy,
|
|
695
721
|
targetRanges: plannedRanges,
|
|
722
|
+
syntax,
|
|
696
723
|
diffOutput: diff.createPatch(
|
|
697
724
|
path.basename(resolvedPath),
|
|
698
725
|
originalContent,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { checkSyntax } from "./syntax-verify";
|
|
1
|
+
import { checkSyntax, type VerificationResult } from "./syntax-verify";
|
|
2
2
|
|
|
3
3
|
export type VerificationState =
|
|
4
4
|
| "clean"
|
|
@@ -79,6 +79,7 @@ export function renderPostEditVerification(
|
|
|
79
79
|
result: PostEditVerification,
|
|
80
80
|
reason?: string,
|
|
81
81
|
targetFile?: string,
|
|
82
|
+
lineSpanSummary?: string,
|
|
82
83
|
): string {
|
|
83
84
|
const hasSyntaxFailure = result.syntax.state === "failed";
|
|
84
85
|
const hasSyntaxUncertainty = [
|
|
@@ -101,7 +102,8 @@ export function renderPostEditVerification(
|
|
|
101
102
|
!hasDiagnosticWarning &&
|
|
102
103
|
(!hasSyntaxUncertainty || result.syntax.state === "clean")
|
|
103
104
|
) {
|
|
104
|
-
|
|
105
|
+
const spanInfo = lineSpanSummary ? ` (${lineSpanSummary})` : "";
|
|
106
|
+
return targetFile ? `Successfully applied edit to ${targetFile}${spanInfo}.` : `Successfully applied edit${spanInfo}.`;
|
|
105
107
|
}
|
|
106
108
|
|
|
107
109
|
const lines: string[] = [];
|
|
@@ -119,7 +121,7 @@ export function renderPostEditVerification(
|
|
|
119
121
|
}
|
|
120
122
|
|
|
121
123
|
// Edit was applied
|
|
122
|
-
lines.push("Edit: Applied");
|
|
124
|
+
lines.push(lineSpanSummary ? `Edit: Applied (${lineSpanSummary})` : "Edit: Applied");
|
|
123
125
|
|
|
124
126
|
if (hasSyntaxFailure || (hasSyntaxUncertainty && result.syntax.state !== "clean")) {
|
|
125
127
|
lines.push("Syntax Error:");
|
|
@@ -161,8 +163,10 @@ export function renderEditFailure(reason: string): string {
|
|
|
161
163
|
export async function verifyEditedFile(
|
|
162
164
|
filePath: string,
|
|
163
165
|
diagnostics?: () => Promise<DiagnosticCheck>,
|
|
166
|
+
/** The verdict the patch already reached on the written content; skips checking it again. */
|
|
167
|
+
precomputedSyntax?: VerificationResult,
|
|
164
168
|
): Promise<PostEditVerification> {
|
|
165
|
-
const syntax = checkSyntax(filePath);
|
|
169
|
+
const syntax = precomputedSyntax ?? checkSyntax(filePath);
|
|
166
170
|
if (!syntax.valid) {
|
|
167
171
|
return {
|
|
168
172
|
edit: "applied",
|
|
@@ -365,7 +365,7 @@ export function applySmartAnchorEdits(
|
|
|
365
365
|
: candidateContentNorm;
|
|
366
366
|
|
|
367
367
|
// Syntax validation gate
|
|
368
|
-
const syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
368
|
+
const syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
369
369
|
if (!syntax.valid && options.syntaxGate !== "warn") {
|
|
370
370
|
return {
|
|
371
371
|
success: false,
|
|
@@ -411,5 +411,6 @@ export function applySmartAnchorEdits(
|
|
|
411
411
|
strategy: "smart_anchor",
|
|
412
412
|
diffOutput,
|
|
413
413
|
targetRanges: preflight.targetRanges,
|
|
414
|
+
syntax,
|
|
414
415
|
};
|
|
415
416
|
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
2
3
|
import * as path from "node:path";
|
|
3
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,202 +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
|
-
* domain of project-native typechecks (e.g. tsc, cargo check).
|
|
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
|
-
default:
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
i++;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
if (state === "squote" || state === "dquote") {
|
|
192
|
-
return `Unterminated string literal (reached end of file, last line ${line})`;
|
|
193
|
-
}
|
|
194
|
-
if (state === "template") {
|
|
195
|
-
return `Unterminated template literal (reached end of file, last line ${line})`;
|
|
196
|
-
}
|
|
197
|
-
if (state === "blockComment") {
|
|
198
|
-
return `Unterminated block comment (last line ${line})`;
|
|
199
|
-
}
|
|
200
|
-
if (stack.length > 0) {
|
|
201
|
-
const unclosed = stack[stack.length - 1];
|
|
202
|
-
return `Unclosed '${unclosed.ch}' opened on line ${unclosed.line} (still open at end of file)`;
|
|
203
|
-
}
|
|
204
|
-
return null;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
13
|
let cachedNodeExec: { bin: string; env?: Record<string, string> } | null | undefined;
|
|
208
14
|
|
|
209
15
|
export function resolveNodeExecutable(): { bin: string; env?: Record<string, string> } | null {
|
|
@@ -337,22 +143,6 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
|
|
|
337
143
|
ext === ".mts" ||
|
|
338
144
|
ext === ".cts"
|
|
339
145
|
) {
|
|
340
|
-
const isJsx = ext === ".tsx" || ext === ".jsx";
|
|
341
|
-
// JSX/TSX text contains arbitrary unescaped delimiters (e.g. <p>step (1)</p>)
|
|
342
|
-
// that a naive bracket counter misidentifies. For JSX, tsc with --jsx preserve
|
|
343
|
-
// performs complete and authoritative syntax validation.
|
|
344
|
-
if (!isJsx) {
|
|
345
|
-
const tsContent = fs.readFileSync(resolvedPath, "utf8");
|
|
346
|
-
const structuralError = checkTsStructure(tsContent);
|
|
347
|
-
if (structuralError) {
|
|
348
|
-
return {
|
|
349
|
-
valid: false,
|
|
350
|
-
status: "failed",
|
|
351
|
-
error: `Syntax validation failed on ${path.basename(resolvedPath)}:\n${structuralError}`,
|
|
352
|
-
};
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
146
|
const nodeExec = resolveNodeExecutable();
|
|
357
147
|
const compiler = resolveTypeScriptCompiler();
|
|
358
148
|
if (!nodeExec || !fs.existsSync(compiler)) {
|
|
@@ -427,28 +217,91 @@ export function checkSyntax(filePath: string): VerificationResult {
|
|
|
427
217
|
const resolvedPath = path.isAbsolute(filePath)
|
|
428
218
|
? filePath
|
|
429
219
|
: path.resolve(process.cwd(), filePath);
|
|
430
|
-
|
|
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` : ""}`;
|
|
431
249
|
}
|
|
432
250
|
|
|
433
251
|
/**
|
|
434
|
-
* Validate candidate content without changing the target file.
|
|
435
|
-
*
|
|
436
|
-
*
|
|
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.
|
|
437
260
|
*/
|
|
438
261
|
export function checkSyntaxContent(
|
|
439
262
|
filePath: string,
|
|
440
263
|
content: string,
|
|
264
|
+
original?: string,
|
|
441
265
|
): VerificationResult {
|
|
442
266
|
const resolvedPath = path.isAbsolute(filePath)
|
|
443
267
|
? filePath
|
|
444
268
|
: path.resolve(process.cwd(), filePath);
|
|
445
|
-
const
|
|
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 {
|
|
446
299
|
let tempDir: string | undefined;
|
|
447
300
|
|
|
448
301
|
try {
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
);
|
|
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-"));
|
|
452
305
|
const candidatePath = path.join(tempDir, `candidate${extension}`);
|
|
453
306
|
fs.writeFileSync(candidatePath, content, "utf8");
|
|
454
307
|
const res = validateSyntaxAtPath(candidatePath);
|