@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.
- package/LICENSE +15 -0
- package/README.md +108 -0
- package/config.toml +24 -0
- package/docs/README.md +22 -0
- package/docs/architecture.md +40 -0
- package/docs/configuration.md +43 -0
- package/docs/editing-and-verification.md +41 -0
- package/docs/lsp.md +31 -0
- package/docs/retrieval.md +42 -0
- package/docs/testing.md +32 -0
- package/package.json +48 -0
- package/src/config/index.ts +2 -0
- package/src/config/kernel_config.ts +218 -0
- package/src/config/toml.ts +237 -0
- package/src/context/session_repair.ts +99 -0
- package/src/dedup/content_store.ts +365 -0
- package/src/dedup/recall_tool.ts +157 -0
- package/src/editing/patch.ts +482 -0
- package/src/editing/post_edit_verification.ts +200 -0
- package/src/editing/syntax-verify.ts +353 -0
- package/src/index.ts +852 -0
- package/src/lsp/adapters/base.ts +42 -0
- package/src/lsp/adapters/index.ts +21 -0
- package/src/lsp/adapters/python.ts +37 -0
- package/src/lsp/adapters/rust.ts +35 -0
- package/src/lsp/adapters/typescript.ts +40 -0
- package/src/lsp/index.ts +13 -0
- package/src/lsp/lsp_client.ts +650 -0
- package/src/lsp/lsp_detector.ts +52 -0
- package/src/lsp/lsp_formatter.ts +284 -0
- package/src/lsp/lsp_installer.ts +604 -0
- package/src/lsp/lsp_manager.ts +202 -0
- package/src/lsp/lsp_modal.ts +675 -0
- package/src/lsp/lsp_registry.ts +539 -0
- package/src/lsp/lsp_types.ts +143 -0
- package/src/retrieval/ast_search.ts +926 -0
- package/src/retrieval/repomap.ts +779 -0
- package/src/retrieval/search_bm25.ts +190 -0
- package/src/retrieval/search_chunker.ts +251 -0
- package/src/retrieval/search_config.ts +162 -0
- package/src/retrieval/search_embedder.ts +362 -0
- package/src/retrieval/search_index.ts +753 -0
- package/src/retrieval/search_modal.ts +358 -0
- package/src/retrieval/symbol_reader.ts +200 -0
- package/src/safety/atomic_write.ts +26 -0
- package/src/safety/epistemic_guard.ts +733 -0
- package/src/safety/kernel_debug.ts +15 -0
- package/src/safety/output_clamper.ts +213 -0
- package/src/tools/ast_search_tool.ts +131 -0
- package/src/tools/code_search_tool.ts +147 -0
- package/src/tools/context.ts +20 -0
- package/src/tools/edit_tool.ts +288 -0
- package/src/tools/lsp_tool.ts +813 -0
- package/src/tools/read_tool.ts +348 -0
- package/src/tools/repo_map_tool.ts +57 -0
- package/src/ui/footer.ts +287 -0
- package/src/ui/tui_utils.ts +278 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { checkSyntax } from "./syntax-verify";
|
|
2
|
+
|
|
3
|
+
export type VerificationState =
|
|
4
|
+
| "clean"
|
|
5
|
+
| "failed"
|
|
6
|
+
| "findings"
|
|
7
|
+
| "timeout"
|
|
8
|
+
| "not run"
|
|
9
|
+
| "unavailable"
|
|
10
|
+
| "inconclusive";
|
|
11
|
+
|
|
12
|
+
export interface DiagnosticFinding {
|
|
13
|
+
line?: number;
|
|
14
|
+
column?: number;
|
|
15
|
+
message: string;
|
|
16
|
+
severity?: "error" | "warning" | "info";
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface DiagnosticVerification {
|
|
20
|
+
state: VerificationState;
|
|
21
|
+
findings: DiagnosticFinding[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface PostEditVerification {
|
|
25
|
+
edit: "applied" | "not applied";
|
|
26
|
+
syntax: {
|
|
27
|
+
state: VerificationState;
|
|
28
|
+
message?: string;
|
|
29
|
+
};
|
|
30
|
+
diagnostic: DiagnosticVerification;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface DiagnosticCheck {
|
|
34
|
+
state: VerificationState;
|
|
35
|
+
findings?: DiagnosticFinding[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const LABEL_ORDER = ["edit", "diagnostic", "syntax"] as const;
|
|
39
|
+
|
|
40
|
+
function compactMessage(message: string, maxLength = 240): string {
|
|
41
|
+
const compact = message.replace(/\s+/g, " ").trim();
|
|
42
|
+
return compact.length > maxLength
|
|
43
|
+
? `${compact.slice(0, maxLength - 1)}…`
|
|
44
|
+
: compact;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function diagnosticValue(result: DiagnosticVerification): string {
|
|
48
|
+
if (result.findings.length === 0) return result.state;
|
|
49
|
+
|
|
50
|
+
const counts = new Map<string, number>();
|
|
51
|
+
for (const finding of result.findings) {
|
|
52
|
+
const severity = finding.severity || "error";
|
|
53
|
+
counts.set(severity, (counts.get(severity) || 0) + 1);
|
|
54
|
+
}
|
|
55
|
+
return Array.from(counts.entries())
|
|
56
|
+
.map(
|
|
57
|
+
([severity, count]) =>
|
|
58
|
+
`${count} ${severity === "warning" ? "warn" : severity === "info" ? "info" : "err"}`,
|
|
59
|
+
)
|
|
60
|
+
.join(",");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function verificationEntries(
|
|
64
|
+
result: PostEditVerification,
|
|
65
|
+
): Array<[string, string]> {
|
|
66
|
+
if (result.edit === "not applied") return [["edit", "not applied"]];
|
|
67
|
+
return [
|
|
68
|
+
["syntax", result.syntax.state],
|
|
69
|
+
["diagnostic", diagnosticValue(result.diagnostic)],
|
|
70
|
+
];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Render the default edit result in a clean, indented form.
|
|
75
|
+
*/
|
|
76
|
+
export function renderPostEditVerification(
|
|
77
|
+
result: PostEditVerification,
|
|
78
|
+
reason?: string,
|
|
79
|
+
): string {
|
|
80
|
+
const hasSyntaxFailure = result.syntax.state === "failed";
|
|
81
|
+
const hasSyntaxUncertainty = [
|
|
82
|
+
"unavailable",
|
|
83
|
+
"inconclusive",
|
|
84
|
+
"timeout",
|
|
85
|
+
].includes(result.syntax.state);
|
|
86
|
+
const hasDiagnosticError = result.diagnostic.findings.some(
|
|
87
|
+
(finding) => finding.severity === "error" || !finding.severity,
|
|
88
|
+
);
|
|
89
|
+
const hasDiagnosticWarning = result.diagnostic.findings.some(
|
|
90
|
+
(finding) => finding.severity === "warning" || finding.severity === "info",
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
// Token density: return empty string on completely clean verification
|
|
94
|
+
if (
|
|
95
|
+
result.edit === "applied" &&
|
|
96
|
+
!hasSyntaxFailure &&
|
|
97
|
+
!hasDiagnosticError &&
|
|
98
|
+
!hasDiagnosticWarning &&
|
|
99
|
+
(!hasSyntaxUncertainty || result.syntax.state === "clean")
|
|
100
|
+
) {
|
|
101
|
+
return "";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const lines: string[] = [];
|
|
105
|
+
|
|
106
|
+
if (result.edit === "not applied") {
|
|
107
|
+
lines.push("Edit: Not applied");
|
|
108
|
+
lines.push("Reason:");
|
|
109
|
+
if (reason) {
|
|
110
|
+
lines.push(` - ${compactMessage(reason)}`);
|
|
111
|
+
}
|
|
112
|
+
if (result.syntax.message && result.syntax.message !== reason) {
|
|
113
|
+
lines.push(` - ${compactMessage(result.syntax.message)}`);
|
|
114
|
+
}
|
|
115
|
+
return lines.join("\n");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Edit was applied
|
|
119
|
+
lines.push("Edit: Applied");
|
|
120
|
+
|
|
121
|
+
if (hasSyntaxFailure || (hasSyntaxUncertainty && result.syntax.state !== "clean")) {
|
|
122
|
+
lines.push("Syntax Error:");
|
|
123
|
+
lines.push(` - ${compactMessage(result.syntax.message || "Syntax validation failed")}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (result.diagnostic.findings.length > 0) {
|
|
127
|
+
const header = hasDiagnosticError ? "Diagnostics (errors):" : "Diagnostics (warnings):";
|
|
128
|
+
lines.push(header);
|
|
129
|
+
for (const finding of result.diagnostic.findings.slice(0, 5)) {
|
|
130
|
+
const pos =
|
|
131
|
+
finding.line !== undefined
|
|
132
|
+
? finding.column !== undefined
|
|
133
|
+
? `[${finding.line}:${finding.column}] `
|
|
134
|
+
: `[${finding.line}] `
|
|
135
|
+
: "";
|
|
136
|
+
lines.push(` - ${pos}${compactMessage(finding.message)}`);
|
|
137
|
+
}
|
|
138
|
+
if (result.diagnostic.findings.length > 5) {
|
|
139
|
+
lines.push(` - +${result.diagnostic.findings.length - 5} more`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return lines.join("\n");
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Run the cheap local syntax gate and an optional bounded diagnostic check. */
|
|
147
|
+
export function renderEditFailure(reason: string): string {
|
|
148
|
+
return renderPostEditVerification(
|
|
149
|
+
{
|
|
150
|
+
edit: "not applied",
|
|
151
|
+
syntax: { state: "not run" },
|
|
152
|
+
diagnostic: { state: "not run", findings: [] },
|
|
153
|
+
},
|
|
154
|
+
reason,
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export async function verifyEditedFile(
|
|
159
|
+
filePath: string,
|
|
160
|
+
diagnostics?: () => Promise<DiagnosticCheck>,
|
|
161
|
+
): Promise<PostEditVerification> {
|
|
162
|
+
const syntax = checkSyntax(filePath);
|
|
163
|
+
if (!syntax.valid) {
|
|
164
|
+
return {
|
|
165
|
+
edit: "applied",
|
|
166
|
+
syntax: {
|
|
167
|
+
state: syntax.status || "failed",
|
|
168
|
+
message: syntax.error,
|
|
169
|
+
},
|
|
170
|
+
diagnostic: { state: "not run", findings: [] },
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
let diagnostic: DiagnosticVerification = { state: "not run", findings: [] };
|
|
175
|
+
if (diagnostics) {
|
|
176
|
+
try {
|
|
177
|
+
const result = await diagnostics();
|
|
178
|
+
diagnostic = {
|
|
179
|
+
state: result.state,
|
|
180
|
+
findings: result.findings || [],
|
|
181
|
+
};
|
|
182
|
+
} catch (error) {
|
|
183
|
+
diagnostic = {
|
|
184
|
+
state: "inconclusive",
|
|
185
|
+
findings: [
|
|
186
|
+
{
|
|
187
|
+
message: error instanceof Error ? error.message : String(error),
|
|
188
|
+
severity: "info",
|
|
189
|
+
},
|
|
190
|
+
],
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return {
|
|
196
|
+
edit: "applied",
|
|
197
|
+
syntax: { state: syntax.status || "clean" },
|
|
198
|
+
diagnostic,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
import { execFileSync } from "child_process";
|
|
4
|
+
|
|
5
|
+
export interface VerificationResult {
|
|
6
|
+
valid: boolean;
|
|
7
|
+
status?: "clean" | "failed" | "unavailable" | "inconclusive" | "not run";
|
|
8
|
+
error?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
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 }[] = [];
|
|
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 = "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 === "'") state = "code";
|
|
103
|
+
break;
|
|
104
|
+
case "dquote":
|
|
105
|
+
if (ch === "\\") i++;
|
|
106
|
+
else if (ch === '"') state = "code";
|
|
107
|
+
break;
|
|
108
|
+
case "template":
|
|
109
|
+
if (ch === "\\") i++;
|
|
110
|
+
else if (ch === "`") state = "code";
|
|
111
|
+
// NOTE: ${...} interpolations are tracked as part of the template
|
|
112
|
+
// body; braces inside them are balanced by JS itself, and any
|
|
113
|
+
// imbalance surfaces as an unbalanced delimiter anyway.
|
|
114
|
+
break;
|
|
115
|
+
case "code":
|
|
116
|
+
if (ch === "/" && next === "/") {
|
|
117
|
+
state = "lineComment";
|
|
118
|
+
i++;
|
|
119
|
+
} else if (ch === "/" && next === "*") {
|
|
120
|
+
state = "blockComment";
|
|
121
|
+
i++;
|
|
122
|
+
} else if (ch === "/" && regexCanStart(prevSig, lastWord)) {
|
|
123
|
+
// Regex literal (division makes no sense at this position).
|
|
124
|
+
// Delimiters inside it are pattern syntax, not code structure.
|
|
125
|
+
state = "regex";
|
|
126
|
+
inCharClass = false;
|
|
127
|
+
lastWord = "";
|
|
128
|
+
} else if (ch === "'") {
|
|
129
|
+
state = "squote";
|
|
130
|
+
prevSig = "'";
|
|
131
|
+
lastWord = "";
|
|
132
|
+
} else if (ch === '"') {
|
|
133
|
+
state = "dquote";
|
|
134
|
+
prevSig = '"';
|
|
135
|
+
lastWord = "";
|
|
136
|
+
} else if (ch === "`") {
|
|
137
|
+
state = "template";
|
|
138
|
+
prevSig = "`";
|
|
139
|
+
lastWord = "";
|
|
140
|
+
} else if (ch === "(" || ch === "[" || ch === "{") {
|
|
141
|
+
stack.push({ ch, line });
|
|
142
|
+
} else if (ch === ")" || ch === "]" || ch === "}") {
|
|
143
|
+
const top = stack.pop();
|
|
144
|
+
if (!top || top.ch !== closers[ch]) {
|
|
145
|
+
return `Unbalanced '${ch}' on line ${line}${top ? ` (unclosed '${top.ch}' from line ${top.line})` : " (no matching opener)"}`;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!/\s/.test(ch)) prevSig = ch;
|
|
149
|
+
// Accumulate identifier/number tokens; whitespace preserves the
|
|
150
|
+
// token (so 'return /re/' and 'x / 2' both resolve correctly),
|
|
151
|
+
// while any other character ends it.
|
|
152
|
+
if (/\s/.test(ch)) {
|
|
153
|
+
// keep lastWord
|
|
154
|
+
} else if (/[A-Za-z0-9_$]/.test(ch)) {
|
|
155
|
+
lastWord += ch;
|
|
156
|
+
} else {
|
|
157
|
+
lastWord = "";
|
|
158
|
+
}
|
|
159
|
+
break;
|
|
160
|
+
case "regex":
|
|
161
|
+
if (ch === "\\") i++;
|
|
162
|
+
else if (ch === "[") inCharClass = true;
|
|
163
|
+
else if (ch === "]") inCharClass = false;
|
|
164
|
+
else if (ch === "/" && !inCharClass) state = "code";
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
i++;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (state === "squote" || state === "dquote" || state === "template") {
|
|
171
|
+
return `Unterminated string literal (reached end of file, last line ${line})`;
|
|
172
|
+
}
|
|
173
|
+
if (state === "blockComment") {
|
|
174
|
+
return `Unterminated block comment (last line ${line})`;
|
|
175
|
+
}
|
|
176
|
+
if (stack.length > 0) {
|
|
177
|
+
const unclosed = stack[stack.length - 1];
|
|
178
|
+
return `Unclosed '${unclosed.ch}' opened on line ${unclosed.line} (still open at end of file)`;
|
|
179
|
+
}
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
|
|
184
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
185
|
+
return { valid: true, status: "clean" };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const ext = path.extname(resolvedPath).toLowerCase();
|
|
189
|
+
|
|
190
|
+
try {
|
|
191
|
+
if (ext === ".py") {
|
|
192
|
+
try {
|
|
193
|
+
execFileSync("python", ["-m", "py_compile", resolvedPath], {
|
|
194
|
+
stdio: "pipe",
|
|
195
|
+
timeout: 5000,
|
|
196
|
+
});
|
|
197
|
+
} catch (error: any) {
|
|
198
|
+
const unavailable = error?.code === "ENOENT" || error?.status === 9009;
|
|
199
|
+
if (!unavailable) throw error;
|
|
200
|
+
try {
|
|
201
|
+
execFileSync("python3", ["-m", "py_compile", resolvedPath], {
|
|
202
|
+
stdio: "pipe",
|
|
203
|
+
timeout: 5000,
|
|
204
|
+
});
|
|
205
|
+
} catch (fallbackError: any) {
|
|
206
|
+
if (fallbackError?.code === "ENOENT" || fallbackError?.status === 9009) {
|
|
207
|
+
return {
|
|
208
|
+
valid: false,
|
|
209
|
+
status: "unavailable",
|
|
210
|
+
error: "Python runtime unavailable",
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
throw fallbackError;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
} else if (ext === ".json") {
|
|
217
|
+
const content = fs.readFileSync(resolvedPath, "utf8");
|
|
218
|
+
JSON.parse(content);
|
|
219
|
+
} else if (ext === ".js" || ext === ".mjs" || ext === ".cjs") {
|
|
220
|
+
execFileSync(process.execPath, ["--check", resolvedPath], {
|
|
221
|
+
stdio: "pipe",
|
|
222
|
+
timeout: 5000,
|
|
223
|
+
});
|
|
224
|
+
} else if (
|
|
225
|
+
ext === ".ts" ||
|
|
226
|
+
ext === ".tsx" ||
|
|
227
|
+
ext === ".jsx" ||
|
|
228
|
+
ext === ".mts" ||
|
|
229
|
+
ext === ".cts"
|
|
230
|
+
) {
|
|
231
|
+
const tsContent = fs.readFileSync(resolvedPath, "utf8");
|
|
232
|
+
const structuralError = checkTsStructure(tsContent);
|
|
233
|
+
if (structuralError) throw new Error(structuralError);
|
|
234
|
+
|
|
235
|
+
const compiler = path.resolve(
|
|
236
|
+
__dirname,
|
|
237
|
+
"../../node_modules/typescript/bin/tsc",
|
|
238
|
+
);
|
|
239
|
+
const compilerArgs = [
|
|
240
|
+
"--noEmit",
|
|
241
|
+
"--noCheck",
|
|
242
|
+
"--noResolve",
|
|
243
|
+
"--skipLibCheck",
|
|
244
|
+
"--ignoreConfig",
|
|
245
|
+
"--pretty",
|
|
246
|
+
"false",
|
|
247
|
+
"--target",
|
|
248
|
+
"ES2020",
|
|
249
|
+
"--module",
|
|
250
|
+
"CommonJS",
|
|
251
|
+
...(ext === ".tsx" || ext === ".jsx"
|
|
252
|
+
? ["--jsx", "preserve", "--allowJs"]
|
|
253
|
+
: []),
|
|
254
|
+
resolvedPath,
|
|
255
|
+
];
|
|
256
|
+
try {
|
|
257
|
+
execFileSync(process.execPath, [compiler, ...compilerArgs], {
|
|
258
|
+
stdio: "pipe",
|
|
259
|
+
timeout: 5000,
|
|
260
|
+
});
|
|
261
|
+
} catch (error: any) {
|
|
262
|
+
if (error?.code === "ENOENT" || error?.status === 9009) {
|
|
263
|
+
return {
|
|
264
|
+
valid: false,
|
|
265
|
+
status: "unavailable",
|
|
266
|
+
error: "TypeScript compiler unavailable",
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
} else {
|
|
272
|
+
return {
|
|
273
|
+
valid: true,
|
|
274
|
+
status: "not run",
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
return { valid: true, status: "clean" };
|
|
278
|
+
} catch (err: any) {
|
|
279
|
+
const stderr = err.stderr?.toString?.() || "";
|
|
280
|
+
const stdout = err.stdout?.toString?.() || "";
|
|
281
|
+
const output = stderr || stdout || err.message || String(err);
|
|
282
|
+
return {
|
|
283
|
+
valid: false,
|
|
284
|
+
status: "failed",
|
|
285
|
+
error: `Syntax validation failed on ${path.basename(resolvedPath)}:\n${output}`,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function checkSyntax(filePath: string): VerificationResult {
|
|
291
|
+
const resolvedPath = path.isAbsolute(filePath)
|
|
292
|
+
? filePath
|
|
293
|
+
: path.resolve(process.cwd(), filePath);
|
|
294
|
+
return validateSyntaxAtPath(resolvedPath);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Validate candidate content without changing the target file.
|
|
299
|
+
* File-oriented validators run against a temporary sibling with the same
|
|
300
|
+
* extension, which keeps their existing behavior while protecting the target.
|
|
301
|
+
*/
|
|
302
|
+
export function checkSyntaxContent(
|
|
303
|
+
filePath: string,
|
|
304
|
+
content: string,
|
|
305
|
+
): VerificationResult {
|
|
306
|
+
const resolvedPath = path.isAbsolute(filePath)
|
|
307
|
+
? filePath
|
|
308
|
+
: path.resolve(process.cwd(), filePath);
|
|
309
|
+
const extension = path.extname(resolvedPath) || ".tmp";
|
|
310
|
+
let tempDir: string | undefined;
|
|
311
|
+
|
|
312
|
+
try {
|
|
313
|
+
tempDir = fs.mkdtempSync(
|
|
314
|
+
path.join(path.dirname(resolvedPath), ".pi-agent-kernel-validate-"),
|
|
315
|
+
);
|
|
316
|
+
const candidatePath = path.join(tempDir, `candidate${extension}`);
|
|
317
|
+
fs.writeFileSync(candidatePath, content, "utf8");
|
|
318
|
+
const res = validateSyntaxAtPath(candidatePath);
|
|
319
|
+
if (!res.valid && res.error) {
|
|
320
|
+
// Clean up leaked temporary directory and candidate filenames
|
|
321
|
+
let cleanErr = res.error
|
|
322
|
+
.replace(new RegExp(`.*\\.pi-agent-kernel-validate-[^/\\\\]+[\\/\\\\]candidate\\.[a-zA-Z0-9]+:?`, "g"), "")
|
|
323
|
+
.replace(/Syntax validation failed on candidate\.[a-zA-Z0-9]+:?\s*/g, "")
|
|
324
|
+
.trim();
|
|
325
|
+
|
|
326
|
+
// Normalize "(line,col): error TSXXXX:" -> "[line:col] TSXXXX:"
|
|
327
|
+
cleanErr = cleanErr.replace(
|
|
328
|
+
/\(?(\d+)[,:]\s*(\d+)\)?:\s*(?:error\s+)?([A-Za-z0-9_]+:)?/g,
|
|
329
|
+
(_, line, col, code) => `[${line}:${col}] ${code || ""}`,
|
|
330
|
+
).trim();
|
|
331
|
+
|
|
332
|
+
return {
|
|
333
|
+
...res,
|
|
334
|
+
error: cleanErr || res.error,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
return res;
|
|
338
|
+
} catch (err: any) {
|
|
339
|
+
return {
|
|
340
|
+
valid: false,
|
|
341
|
+
status: "inconclusive",
|
|
342
|
+
error: `Syntax validation could not inspect candidate content: ${err.message || String(err)}`,
|
|
343
|
+
};
|
|
344
|
+
} finally {
|
|
345
|
+
if (tempDir) {
|
|
346
|
+
try {
|
|
347
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
348
|
+
} catch {
|
|
349
|
+
// Best-effort cleanup; the validation result remains explicit.
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|