@floydous/pi-agent-kernel 0.3.31 → 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 +35 -4
- package/README.md +39 -74
- package/config.example.toml +36 -0
- package/docs/configuration.md +11 -3
- package/docs/retrieval.md +17 -1
- package/docs/testing.md +5 -3
- package/package.json +9 -7
- package/src/config/agent_kernel_command.ts +91 -91
- package/src/config/kernel_config.ts +179 -43
- package/src/config/toml.ts +15 -4
- package/src/context/session_repair.ts +179 -80
- package/src/editing/patch.ts +28 -16
- package/src/editing/smart_anchor.ts +29 -36
- package/src/editing/syntax-verify.ts +52 -18
- package/src/index.ts +257 -219
- package/src/lsp/lsp_client.ts +138 -23
- package/src/lsp/lsp_formatter.ts +61 -24
- package/src/lsp/lsp_installer.ts +277 -561
- package/src/lsp/lsp_manager.ts +1 -1
- package/src/lsp/lsp_registry.ts +110 -73
- package/src/retrieval/ast_search.ts +136 -172
- package/src/retrieval/repomap.ts +8 -47
- package/src/retrieval/search_bm25.ts +5 -2
- package/src/retrieval/search_cache.ts +69 -0
- package/src/retrieval/search_chunker.ts +21 -43
- package/src/retrieval/search_config.ts +75 -18
- package/src/retrieval/search_embedder.ts +8 -16
- package/src/retrieval/search_index.ts +923 -123
- package/src/retrieval/workspace_walker.ts +262 -0
- package/src/safety/atomic_write.ts +59 -20
- package/src/safety/epistemic_guard.ts +163 -43
- package/src/safety/output_clamper.ts +316 -74
- 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 +124 -43
- package/src/tools/lsp_tool.ts +17 -4
- package/src/tools/read_tool.ts +48 -7
- package/config.toml +0 -31
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import ignore, { type Ignore } from "ignore";
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_IGNORED_DIRS = new Set([
|
|
6
|
+
".git",
|
|
7
|
+
"node_modules",
|
|
8
|
+
".venv",
|
|
9
|
+
"venv",
|
|
10
|
+
"__pycache__",
|
|
11
|
+
".pytest_cache",
|
|
12
|
+
"dist",
|
|
13
|
+
"build",
|
|
14
|
+
"coverage",
|
|
15
|
+
".pi",
|
|
16
|
+
".hermes",
|
|
17
|
+
".next",
|
|
18
|
+
".turbo",
|
|
19
|
+
".cache",
|
|
20
|
+
"target",
|
|
21
|
+
"vendor",
|
|
22
|
+
"agent-kernel-benchmark",
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
export interface IgnoreFrame {
|
|
26
|
+
dirRel: string; // relative to baseRoot with forward slashes (empty string for baseRoot)
|
|
27
|
+
ig: Ignore;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Finds the enclosing git root containing startDir, if any.
|
|
32
|
+
*/
|
|
33
|
+
export function findGitRoot(startDir: string): string | null {
|
|
34
|
+
let curr = path.resolve(startDir);
|
|
35
|
+
while (true) {
|
|
36
|
+
if (fs.existsSync(path.join(curr, ".git"))) {
|
|
37
|
+
return curr;
|
|
38
|
+
}
|
|
39
|
+
const parent = path.dirname(curr);
|
|
40
|
+
if (parent === curr) break;
|
|
41
|
+
curr = parent;
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Creates an ignore instance from a file path if the file exists.
|
|
48
|
+
*/
|
|
49
|
+
export function loadIgnoreFile(filePath: string): Ignore | null {
|
|
50
|
+
if (!fs.existsSync(filePath)) return null;
|
|
51
|
+
try {
|
|
52
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
53
|
+
const ig = typeof ignore === "function" ? ignore() : (ignore as any).default();
|
|
54
|
+
return ig.add(content);
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Checks whether a path (relative to baseRoot, with forward slashes) is ignored
|
|
62
|
+
* according to the stack of IgnoreFrames (evaluated from deepest child to root).
|
|
63
|
+
*/
|
|
64
|
+
export function isPathIgnored(stack: IgnoreFrame[], relPath: string, isDirectory: boolean): boolean {
|
|
65
|
+
const targetPath = isDirectory && !relPath.endsWith("/") ? relPath + "/" : relPath;
|
|
66
|
+
for (let i = stack.length - 1; i >= 0; i--) {
|
|
67
|
+
const frame = stack[i];
|
|
68
|
+
let relToFrame = frame.dirRel ? targetPath.slice(frame.dirRel.length + 1) : targetPath;
|
|
69
|
+
if (relToFrame.startsWith("/")) relToFrame = relToFrame.slice(1);
|
|
70
|
+
if (!relToFrame) continue;
|
|
71
|
+
|
|
72
|
+
const res = (frame.ig as any).test(relToFrame);
|
|
73
|
+
if (res.unignored) return false;
|
|
74
|
+
if (res.ignored) return true;
|
|
75
|
+
}
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface WalkWorkspaceOptions {
|
|
80
|
+
rootDir: string;
|
|
81
|
+
maxFiles?: number;
|
|
82
|
+
extensions?: Set<string>;
|
|
83
|
+
includeGithub?: boolean;
|
|
84
|
+
onFile?: (filePath: string) => boolean | void;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Walks workspace directories recursively respecting .gitignore, additive .piignore,
|
|
89
|
+
* and built-in hard exclusions (DEFAULT_IGNORED_DIRS).
|
|
90
|
+
*
|
|
91
|
+
* Safety boundaries:
|
|
92
|
+
* 1. Hard exclusions (DEFAULT_IGNORED_DIRS) cannot be overridden by user negations.
|
|
93
|
+
* 2. Gitignore hierarchy (nested .gitignore overrides parent .gitignore).
|
|
94
|
+
* 3. Additive .piignore (can only add exclusions; cannot un-ignore Git-ignored files).
|
|
95
|
+
* 4. Symlinks & containment: Symbolic links are skipped; traversed directories must remain
|
|
96
|
+
* strictly bounded inside the canonical workspace root.
|
|
97
|
+
* 5. Parent scope inheritance: When rootDir is a subdirectory of a Git repository, parent
|
|
98
|
+
* .gitignore files from gitRoot down to rootDir are discovered and applied in order.
|
|
99
|
+
*
|
|
100
|
+
* Returns absolute paths to matching files.
|
|
101
|
+
*/
|
|
102
|
+
export function walkWorkspaceFiles(options: WalkWorkspaceOptions): string[] {
|
|
103
|
+
const rootDir = path.resolve(options.rootDir);
|
|
104
|
+
const maxFiles = options.maxFiles ?? 500;
|
|
105
|
+
const extensions = options.extensions;
|
|
106
|
+
const includeGithub = options.includeGithub ?? true;
|
|
107
|
+
const files: string[] = [];
|
|
108
|
+
|
|
109
|
+
let canonicalRoot: string;
|
|
110
|
+
try {
|
|
111
|
+
canonicalRoot = fs.realpathSync(rootDir);
|
|
112
|
+
} catch {
|
|
113
|
+
canonicalRoot = rootDir;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const visitedDirs = new Set<string>();
|
|
117
|
+
visitedDirs.add(canonicalRoot);
|
|
118
|
+
|
|
119
|
+
// Resolve Git base root (to support starting at subdirectories)
|
|
120
|
+
const gitRoot = findGitRoot(rootDir);
|
|
121
|
+
const baseRoot = gitRoot ? path.resolve(gitRoot) : rootDir;
|
|
122
|
+
|
|
123
|
+
// Build initial ignore stacks from baseRoot down to rootDir
|
|
124
|
+
const rootGitFrames: IgnoreFrame[] = [];
|
|
125
|
+
const rootPiFrames: IgnoreFrame[] = [];
|
|
126
|
+
|
|
127
|
+
// Collect directories in the path from baseRoot down to rootDir
|
|
128
|
+
const initialDirs: string[] = [];
|
|
129
|
+
let curr = rootDir;
|
|
130
|
+
while (curr.startsWith(baseRoot)) {
|
|
131
|
+
initialDirs.unshift(curr);
|
|
132
|
+
if (curr === baseRoot) break;
|
|
133
|
+
const parent = path.dirname(curr);
|
|
134
|
+
if (parent === curr) break;
|
|
135
|
+
curr = parent;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
for (const dir of initialDirs) {
|
|
139
|
+
const dirRel = path.relative(baseRoot, dir).replace(/\\/g, "/");
|
|
140
|
+
const localGit = loadIgnoreFile(path.join(dir, ".gitignore"));
|
|
141
|
+
if (localGit) {
|
|
142
|
+
rootGitFrames.push({ dirRel, ig: localGit });
|
|
143
|
+
}
|
|
144
|
+
const localPi = loadIgnoreFile(path.join(dir, ".piignore"));
|
|
145
|
+
if (localPi) {
|
|
146
|
+
rootPiFrames.push({ dirRel, ig: localPi });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function scan(dir: string, gitStack: IgnoreFrame[], piStack: IgnoreFrame[]): boolean {
|
|
151
|
+
if (files.length >= maxFiles) return false;
|
|
152
|
+
|
|
153
|
+
let entries: fs.Dirent[];
|
|
154
|
+
try {
|
|
155
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
156
|
+
} catch {
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Check for local directory .gitignore / .piignore when below rootDir
|
|
161
|
+
const currentGitStack = [...gitStack];
|
|
162
|
+
const currentPiStack = [...piStack];
|
|
163
|
+
const dirRel = path.relative(baseRoot, dir).replace(/\\/g, "/");
|
|
164
|
+
|
|
165
|
+
// If dir is not one of the preloaded initialDirs, load local ignore files
|
|
166
|
+
if (!initialDirs.includes(dir)) {
|
|
167
|
+
const localGitIgnore = loadIgnoreFile(path.join(dir, ".gitignore"));
|
|
168
|
+
if (localGitIgnore) {
|
|
169
|
+
currentGitStack.push({ dirRel, ig: localGitIgnore });
|
|
170
|
+
}
|
|
171
|
+
const localPiIgnore = loadIgnoreFile(path.join(dir, ".piignore"));
|
|
172
|
+
if (localPiIgnore) {
|
|
173
|
+
currentPiStack.push({ dirRel, ig: localPiIgnore });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
for (const entry of entries) {
|
|
178
|
+
if (files.length >= maxFiles) return false;
|
|
179
|
+
|
|
180
|
+
// Skip symbolic links to prevent circular loops or out-of-tree escapes
|
|
181
|
+
if (entry.isSymbolicLink()) {
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Handle hidden files/folders: ignore unless .github is explicitly permitted
|
|
186
|
+
if (entry.name.startsWith(".")) {
|
|
187
|
+
if (!includeGithub || entry.name !== ".github") {
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Built-in hard exclusions (cannot be negated)
|
|
193
|
+
if (DEFAULT_IGNORED_DIRS.has(entry.name)) {
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const fullPath = path.join(dir, entry.name);
|
|
198
|
+
const entryRel = path.relative(baseRoot, fullPath).replace(/\\/g, "/");
|
|
199
|
+
|
|
200
|
+
if (entry.isDirectory()) {
|
|
201
|
+
let realDir: string;
|
|
202
|
+
try {
|
|
203
|
+
realDir = fs.realpathSync(fullPath);
|
|
204
|
+
} catch {
|
|
205
|
+
// Dangling link or permission error; safely skip
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Symlink & workspace containment guard
|
|
210
|
+
const relToRoot = path.relative(canonicalRoot, realDir);
|
|
211
|
+
if (relToRoot.startsWith("..") || path.isAbsolute(relToRoot)) {
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (visitedDirs.has(realDir)) {
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Test directory ignore against .gitignore then .piignore
|
|
220
|
+
if (
|
|
221
|
+
isPathIgnored(currentGitStack, entryRel, true) ||
|
|
222
|
+
isPathIgnored(currentPiStack, entryRel, true)
|
|
223
|
+
) {
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
visitedDirs.add(realDir);
|
|
228
|
+
const shouldContinue = scan(fullPath, currentGitStack, currentPiStack);
|
|
229
|
+
if (!shouldContinue) return false;
|
|
230
|
+
} else if (entry.isFile()) {
|
|
231
|
+
// Extension filtering
|
|
232
|
+
if (extensions) {
|
|
233
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
234
|
+
if (!extensions.has(ext)) {
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Check .gitignore first
|
|
240
|
+
if (isPathIgnored(currentGitStack, entryRel, false)) {
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Check additive .piignore second
|
|
245
|
+
if (isPathIgnored(currentPiStack, entryRel, false)) {
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
files.push(fullPath);
|
|
250
|
+
if (options.onFile) {
|
|
251
|
+
const cont = options.onFile(fullPath);
|
|
252
|
+
if (cont === false) return false;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return true;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
scan(rootDir, rootGitFrames, rootPiFrames);
|
|
261
|
+
return files;
|
|
262
|
+
}
|
|
@@ -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
|
}
|
|
@@ -34,7 +34,7 @@ function commandName(token: string): string {
|
|
|
34
34
|
return path
|
|
35
35
|
.basename(token)
|
|
36
36
|
.toLowerCase()
|
|
37
|
-
.replace(/\.exe
|
|
37
|
+
.replace(/\.(exe|cmd|bat)$/i, "");
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
/** Resolve the path forms accepted by Pi's file tools, including ~ paths. */
|
|
@@ -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,
|