@floydous/pi-agent-kernel 0.4.0 → 0.4.1
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 +6 -4
- package/CHANGELOG.md +32 -91
- package/README.md +39 -74
- package/config.example.toml +1 -1
- package/docs/retrieval.md +2 -0
- package/package.json +7 -6
- package/src/config/agent_kernel_command.ts +29 -14
- package/src/config/kernel_config.ts +175 -30
- package/src/context/session_repair.ts +166 -85
- package/src/editing/patch.ts +28 -16
- package/src/editing/smart_anchor.ts +13 -29
- package/src/editing/syntax-verify.ts +35 -11
- package/src/index.ts +161 -141
- package/src/lsp/lsp_client.ts +101 -20
- package/src/lsp/lsp_formatter.ts +57 -22
- package/src/lsp/lsp_installer.ts +272 -487
- package/src/lsp/lsp_manager.ts +1 -1
- package/src/lsp/lsp_registry.ts +75 -46
- package/src/retrieval/search_bm25.ts +5 -2
- package/src/retrieval/search_cache.ts +69 -0
- package/src/retrieval/search_chunker.ts +12 -9
- package/src/retrieval/search_config.ts +20 -8
- package/src/retrieval/search_embedder.ts +8 -16
- package/src/retrieval/search_index.ts +552 -121
- package/src/safety/atomic_write.ts +59 -20
- package/src/safety/epistemic_guard.ts +162 -42
- package/src/safety/output_clamper.ts +316 -76
- package/src/tools/code_search_output.ts +59 -23
- package/src/tools/code_search_tool.ts +42 -46
- package/src/tools/context.ts +15 -1
- package/src/tools/edit_tool.ts +113 -35
- package/src/tools/lsp_tool.ts +5 -2
- package/src/tools/read_tool.ts +44 -3
|
@@ -1,26 +1,65 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
2
4
|
import { kernelDebug } from "./kernel_debug";
|
|
3
5
|
|
|
6
|
+
function syncDirectory(directory: string): void {
|
|
7
|
+
if (process.platform === "win32") return;
|
|
8
|
+
try {
|
|
9
|
+
const fd = fs.openSync(directory, fs.constants.O_RDONLY);
|
|
10
|
+
try {
|
|
11
|
+
fs.fsyncSync(fd);
|
|
12
|
+
} finally {
|
|
13
|
+
fs.closeSync(fd);
|
|
14
|
+
}
|
|
15
|
+
} catch (error) {
|
|
16
|
+
// Directory fsync is not available on every filesystem; rename is still
|
|
17
|
+
// atomic, and the failure is intentionally non-fatal after the rename.
|
|
18
|
+
kernelDebug(error);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
4
22
|
/**
|
|
5
|
-
* Write a file
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* holds the old complete file or the new complete file, never a partial one.
|
|
23
|
+
* Write a file through an exclusive sibling temp file, preserving metadata
|
|
24
|
+
* where the platform exposes it. A plain writeFileSync can leave a truncated
|
|
25
|
+
* destination after a crash; fsync + rename prevents that partial state.
|
|
9
26
|
*/
|
|
10
|
-
export function writeFileSyncAtomic(
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
27
|
+
export function writeFileSyncAtomic(filePath: string, data: string | Buffer): void {
|
|
28
|
+
const target = path.resolve(filePath);
|
|
29
|
+
let targetStat: fs.Stats | undefined;
|
|
30
|
+
try {
|
|
31
|
+
targetStat = fs.lstatSync(target);
|
|
32
|
+
if (targetStat.isSymbolicLink()) {
|
|
33
|
+
throw new Error("Refusing to atomically replace a symbolic-link target");
|
|
34
|
+
}
|
|
35
|
+
} catch (error: any) {
|
|
36
|
+
if (error?.code !== "ENOENT") throw error;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const mode = targetStat ? (targetStat.mode & 0o7777) : 0o600;
|
|
40
|
+
const temp = `${target}.${process.pid}.${Date.now()}.${randomBytes(6).toString("hex")}.tmp`;
|
|
41
|
+
let fd: number | undefined;
|
|
42
|
+
try {
|
|
43
|
+
fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, mode);
|
|
44
|
+
fs.writeFileSync(fd, data);
|
|
45
|
+
fs.fsyncSync(fd);
|
|
46
|
+
fs.closeSync(fd);
|
|
47
|
+
fd = undefined;
|
|
48
|
+
|
|
49
|
+
if (targetStat && process.platform !== "win32") {
|
|
50
|
+
fs.chmodSync(temp, mode);
|
|
51
|
+
if (targetStat.uid !== process.getuid?.() || targetStat.gid !== process.getgid?.()) {
|
|
52
|
+
fs.chownSync(temp, targetStat.uid, targetStat.gid);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
fs.renameSync(temp, target);
|
|
57
|
+
syncDirectory(path.dirname(target));
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (fd !== undefined) {
|
|
60
|
+
try { fs.closeSync(fd); } catch (closeError) { kernelDebug(closeError); }
|
|
61
|
+
}
|
|
62
|
+
try { fs.unlinkSync(temp); } catch (cleanupError) { kernelDebug(cleanupError); }
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
26
65
|
}
|
|
@@ -422,52 +422,68 @@ export function parsePagingAndDiffOutput(
|
|
|
422
422
|
cwd = process.cwd(),
|
|
423
423
|
): Map<string, number[]> {
|
|
424
424
|
const result = new Map<string, number[]>();
|
|
425
|
-
if (candidateFiles.length === 0) return result;
|
|
425
|
+
if (candidateFiles.length === 0 || !outputText) return result;
|
|
426
426
|
|
|
427
427
|
const targetPath = path.isAbsolute(candidateFiles[0])
|
|
428
428
|
? path.normalize(candidateFiles[0])
|
|
429
429
|
: path.resolve(cwd, candidateFiles[0]);
|
|
430
430
|
|
|
431
|
-
let
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
431
|
+
let sourceLines: string[];
|
|
432
|
+
try {
|
|
433
|
+
const sourceText = fs.readFileSync(targetPath, "utf8").replace(/\r\n/g, "\n");
|
|
434
|
+
sourceLines = sourceText.split("\n");
|
|
435
|
+
if (sourceText.endsWith("\n")) sourceLines.pop();
|
|
436
|
+
} catch {
|
|
437
|
+
return result;
|
|
438
438
|
}
|
|
439
439
|
|
|
440
|
-
|
|
440
|
+
const outputLines = outputText.replace(/\r\n/g, "\n").split("\n");
|
|
441
|
+
if (outputLines.at(-1) === "") outputLines.pop();
|
|
442
|
+
if (outputLines.length === 0) return result;
|
|
443
|
+
|
|
444
|
+
const matchesRange = (start: number, end: number): boolean => {
|
|
445
|
+
if (
|
|
446
|
+
!Number.isSafeInteger(start) ||
|
|
447
|
+
!Number.isSafeInteger(end) ||
|
|
448
|
+
start < 1 ||
|
|
449
|
+
end < start ||
|
|
450
|
+
end > sourceLines.length
|
|
451
|
+
) {
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
const expected = sourceLines.slice(start - 1, end);
|
|
455
|
+
return (
|
|
456
|
+
expected.length === outputLines.length &&
|
|
457
|
+
expected.every((line, index) => line === outputLines[index])
|
|
458
|
+
);
|
|
459
|
+
};
|
|
460
|
+
|
|
441
461
|
const headMatch = command.match(/\bhead\b.*?-n\s*(\d+)/i);
|
|
442
462
|
if (headMatch) {
|
|
443
|
-
const
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
463
|
+
const end = Math.min(parseInt(headMatch[1]!, 10), sourceLines.length);
|
|
464
|
+
if (end > 0 && matchesRange(1, end)) {
|
|
465
|
+
result.set(targetPath, Array.from({ length: end }, (_, index) => index + 1));
|
|
466
|
+
}
|
|
447
467
|
return result;
|
|
448
468
|
}
|
|
449
469
|
|
|
450
|
-
// 2. tail -n <N>
|
|
451
470
|
const tailMatch = command.match(/\btail\b.*?-n\s*(\d+)/i);
|
|
452
471
|
if (tailMatch) {
|
|
453
|
-
const count = parseInt(tailMatch[1]
|
|
454
|
-
const start =
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
result.set(targetPath, lines);
|
|
472
|
+
const count = Math.min(parseInt(tailMatch[1]!, 10), sourceLines.length);
|
|
473
|
+
const start = sourceLines.length - count + 1;
|
|
474
|
+
if (count > 0 && matchesRange(start, sourceLines.length)) {
|
|
475
|
+
result.set(targetPath, Array.from({ length: count }, (_, index) => start + index));
|
|
476
|
+
}
|
|
459
477
|
return result;
|
|
460
478
|
}
|
|
461
479
|
|
|
462
|
-
// 3. sed -n '<start>,<end>p'
|
|
463
480
|
const sedMatch = command.match(/\bsed\b.*?-n\s*['"]?(\d+),(\d+)p['"]?/i);
|
|
464
481
|
if (sedMatch) {
|
|
465
|
-
const start = parseInt(sedMatch[1]
|
|
466
|
-
const end = parseInt(sedMatch[2]
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
return result;
|
|
482
|
+
const start = parseInt(sedMatch[1]!, 10);
|
|
483
|
+
const end = parseInt(sedMatch[2]!, 10);
|
|
484
|
+
if (matchesRange(start, end)) {
|
|
485
|
+
result.set(targetPath, Array.from({ length: end - start + 1 }, (_, index) => start + index));
|
|
486
|
+
}
|
|
471
487
|
}
|
|
472
488
|
|
|
473
489
|
return result;
|
|
@@ -819,16 +835,22 @@ export class EpistemicGuard {
|
|
|
819
835
|
outputText,
|
|
820
836
|
);
|
|
821
837
|
}
|
|
822
|
-
// Also scan outputText for polyglot compiler/test traces across the
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
838
|
+
// Also scan outputText for polyglot compiler/test traces across the
|
|
839
|
+
// workspace. Paging/search output already has stricter attribution above;
|
|
840
|
+
// feeding it into the generic grep parser would let synthetic `1:line`
|
|
841
|
+
// text manufacture read evidence.
|
|
842
|
+
const isPagingOrSearchOutput = /\b(head|tail|sed|grep|rg)\b/i.test(command);
|
|
843
|
+
if (!isPagingOrSearchOutput) {
|
|
844
|
+
const traces = parseGrepOutput(outputText, files, cwd);
|
|
845
|
+
for (const [filePath, lineNumbers] of traces.entries()) {
|
|
846
|
+
const ranges = linesToRanges(lineNumbers);
|
|
847
|
+
if (ranges.length > 0) {
|
|
848
|
+
this.recordFileRead(filePath, sessionId, cwd, undefined, {
|
|
849
|
+
coverage: { complete: false, ranges },
|
|
850
|
+
provenance: "bash",
|
|
851
|
+
query: command,
|
|
852
|
+
});
|
|
853
|
+
}
|
|
832
854
|
}
|
|
833
855
|
}
|
|
834
856
|
return files;
|
|
@@ -923,20 +945,90 @@ export class EpistemicGuard {
|
|
|
923
945
|
return { allowed: true };
|
|
924
946
|
}
|
|
925
947
|
|
|
926
|
-
// 4. Edit operations:
|
|
948
|
+
// 4. Edit operations: Per-Block Hybrid Authorization
|
|
949
|
+
// Each block in a multi-block edit must independently satisfy either:
|
|
950
|
+
// - Tier 1: its resolved target range is covered by visible read evidence, OR
|
|
951
|
+
// - Tier 2: its search block is substantive (>=2 lines and >=35 chars, or >=50 chars).
|
|
952
|
+
if (targetRanges && targetRanges.length > 0 && searchBlocks && searchBlocks.length === targetRanges.length) {
|
|
953
|
+
let allCoveredByRead = true;
|
|
954
|
+
let failingBlockIndex = -1;
|
|
955
|
+
|
|
956
|
+
for (let i = 0; i < targetRanges.length; i++) {
|
|
957
|
+
const range = targetRanges[i];
|
|
958
|
+
const sb = searchBlocks[i];
|
|
959
|
+
|
|
960
|
+
// Validate range integrity
|
|
961
|
+
if (
|
|
962
|
+
!range ||
|
|
963
|
+
!Number.isFinite(range.startLine) ||
|
|
964
|
+
!Number.isFinite(range.endLine) ||
|
|
965
|
+
range.startLine < 1 ||
|
|
966
|
+
range.endLine < range.startLine ||
|
|
967
|
+
(evidence.coverage.totalLines !== undefined && range.endLine > evidence.coverage.totalLines)
|
|
968
|
+
) {
|
|
969
|
+
return {
|
|
970
|
+
allowed: false,
|
|
971
|
+
reason: `[BLOCKED: Malformed or out-of-bounds target range in block ${i + 1}/${targetRanges.length} -> read({ path: "${relPath}" })]`,
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
if (!sb || typeof sb !== "string" || sb.trim().length === 0) {
|
|
976
|
+
return {
|
|
977
|
+
allowed: false,
|
|
978
|
+
reason: `[BLOCKED: Empty search block in block ${i + 1}/${targetRanges.length} -> read({ path: "${relPath}" })]`,
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
const isCovered = coversRanges(evidence.coverage, [range]);
|
|
983
|
+
if (!isCovered) {
|
|
984
|
+
allCoveredByRead = false;
|
|
985
|
+
const contentLines = sb.replace(/\r\n/g, "\n").split("\n").filter((l) => l.trim().length > 0);
|
|
986
|
+
const totalSubstantiveChars = contentLines.reduce((sum, line) => sum + line.trim().length, 0);
|
|
987
|
+
const isSubstantive = contentLines.length >= 2 && totalSubstantiveChars >= 35;
|
|
988
|
+
if (!isSubstantive) {
|
|
989
|
+
failingBlockIndex = i;
|
|
990
|
+
break;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
if (failingBlockIndex === -1) {
|
|
996
|
+
return { allowed: true, tier: allCoveredByRead ? 1 : 2 };
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
const failRange = targetRanges[failingBlockIndex];
|
|
1000
|
+
const maxAvailable = evidence.coverage.totalLines !== undefined
|
|
1001
|
+
? Math.max(1, evidence.coverage.totalLines - failRange.startLine + 1)
|
|
1002
|
+
: Math.max(15, failRange.endLine - failRange.startLine + 5);
|
|
1003
|
+
const hintLimit = Math.min(Math.max(15, failRange.endLine - failRange.startLine + 5), maxAvailable);
|
|
1004
|
+
return {
|
|
1005
|
+
allowed: false,
|
|
1006
|
+
reason: `[BLOCKED: Target lines not covered by visible read and search block is non-substantive (<2 lines / <35 chars) -> read({ path: "${relPath}", offset: ${failRange.startLine}, limit: ${hintLimit} })]`,
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
|
|
927
1010
|
// Tier 1: Strict range coverage
|
|
928
1011
|
if (evidence.kind === "read" && coversRanges(evidence.coverage, targetRanges)) {
|
|
929
1012
|
return { allowed: true, tier: 1 };
|
|
930
1013
|
}
|
|
931
1014
|
|
|
1015
|
+
// Search metadata is useful for navigation but never authorizes mutation,
|
|
1016
|
+
// regardless of how substantial the proposed replacement text is.
|
|
1017
|
+
if (evidence.kind !== "read") {
|
|
1018
|
+
return {
|
|
1019
|
+
allowed: false,
|
|
1020
|
+
reason: `[BLOCKED: Search metadata does not authorize edits -> read({ path: "${relPath}" })]`,
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
|
|
932
1024
|
// Tier 2: Substantive unique block authorization
|
|
933
1025
|
// If range math has gaps (e.g. grep context, compiler traces, symbol extraction boundaries),
|
|
934
|
-
// authorize if every search block is substantive (>=2 lines and >=35 chars
|
|
1026
|
+
// authorize if every search block is substantive (>=2 non-empty content lines and >=35 chars).
|
|
935
1027
|
if (searchBlocks && searchBlocks.length > 0) {
|
|
936
1028
|
const allSubstantive = searchBlocks.every((sb) => {
|
|
937
|
-
const
|
|
938
|
-
const
|
|
939
|
-
return
|
|
1029
|
+
const contentLines = sb.replace(/\r\n/g, "\n").split("\n").filter((l) => l.trim().length > 0);
|
|
1030
|
+
const totalSubstantiveChars = contentLines.reduce((sum, line) => sum + line.trim().length, 0);
|
|
1031
|
+
return contentLines.length >= 2 && totalSubstantiveChars >= 35;
|
|
940
1032
|
});
|
|
941
1033
|
|
|
942
1034
|
if (allSubstantive) {
|
|
@@ -964,6 +1056,34 @@ export class EpistemicGuard {
|
|
|
964
1056
|
return this.getSessionEvidence(sessionId).has(this.normalize(filePath, cwd));
|
|
965
1057
|
}
|
|
966
1058
|
|
|
1059
|
+
public restoreEvidence(
|
|
1060
|
+
filePath: string,
|
|
1061
|
+
sessionId: string,
|
|
1062
|
+
evidence: ContextEvidence | null,
|
|
1063
|
+
cwd = process.cwd(),
|
|
1064
|
+
): void {
|
|
1065
|
+
const normalized = this.normalize(filePath, cwd);
|
|
1066
|
+
const sessionEvidence = this.inspectedFilesBySession.get(sessionId);
|
|
1067
|
+
if (!sessionEvidence) return;
|
|
1068
|
+
if (!evidence) {
|
|
1069
|
+
sessionEvidence.delete(normalized);
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
sessionEvidence.set(normalized, {
|
|
1073
|
+
kind: evidence.kind,
|
|
1074
|
+
fingerprint: evidence.snapshot,
|
|
1075
|
+
coverage: {
|
|
1076
|
+
complete: evidence.coverage.complete,
|
|
1077
|
+
ranges: evidence.coverage.ranges.map((range) => ({ ...range })),
|
|
1078
|
+
...(evidence.coverage.totalLines === undefined
|
|
1079
|
+
? {}
|
|
1080
|
+
: { totalLines: evidence.coverage.totalLines }),
|
|
1081
|
+
},
|
|
1082
|
+
provenance: evidence.provenance,
|
|
1083
|
+
...(evidence.query === undefined ? {} : { query: evidence.query }),
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
|
|
967
1087
|
/** Return a stable, non-content ledger view for diagnostics and tests. */
|
|
968
1088
|
public getEvidence(
|
|
969
1089
|
filePath: string,
|