@floydous/pi-agent-kernel 0.3.1 → 0.3.3

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.
@@ -0,0 +1,420 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as diff from "diff";
4
+ import { checkSyntaxContent } from "./syntax-verify";
5
+ import { writeFileSyncAtomic } from "../safety/atomic_write";
6
+ import type { PatchResult, PatchTargetRange } from "./patch";
7
+
8
+ // ─── FNV-1a 32-bit Context Line Hashing ─────────────────────────────────────
9
+ const HEX = "0123456789ABCDEF";
10
+ const DICT = Array.from({ length: 256 }, (_, i) => {
11
+ const h = i >>> 4;
12
+ const l = i & 0x0f;
13
+ return `${HEX[h]}${HEX[l]}`;
14
+ });
15
+
16
+ export const ANCHOR_SEP = "#";
17
+ export const CONTENT_SEP = "│";
18
+ const FNV_OFFSET = 0x811c9dc5;
19
+ const FNV_PRIME = 0x01000193;
20
+
21
+ export function normalizeLine(line: string): string {
22
+ return line.replace(/\r/g, "").trimEnd();
23
+ }
24
+
25
+ function fnvHash(prev: string, curr: string, next: string): string {
26
+ let hash = FNV_OFFSET;
27
+ for (let i = 0; i < prev.length; i++) {
28
+ hash = Math.imul(hash ^ prev.charCodeAt(i), FNV_PRIME);
29
+ }
30
+ hash = Math.imul(hash ^ 0, FNV_PRIME); // \0 delimiter
31
+ for (let i = 0; i < curr.length; i++) {
32
+ hash = Math.imul(hash ^ curr.charCodeAt(i), FNV_PRIME);
33
+ }
34
+ hash = Math.imul(hash ^ 0, FNV_PRIME); // \0 delimiter
35
+ for (let i = 0; i < next.length; i++) {
36
+ hash = Math.imul(hash ^ next.charCodeAt(i), FNV_PRIME);
37
+ }
38
+ return DICT[hash & 0xff];
39
+ }
40
+
41
+ /**
42
+ * Compute context hash incorporating immediate neighbors.
43
+ * Missing neighbors at file boundaries contribute an empty string.
44
+ */
45
+ export function computeLineHash(fileLines: readonly string[], index: number): string {
46
+ if (index < 0 || index >= fileLines.length) return "";
47
+ const prev = index > 0 ? normalizeLine(fileLines[index - 1]!) : "";
48
+ const curr = normalizeLine(fileLines[index]!);
49
+ const next = index < fileLines.length - 1 ? normalizeLine(fileLines[index + 1]!) : "";
50
+ return fnvHash(prev, curr, next);
51
+ }
52
+
53
+ /** Format file lines with padded line numbers and context anchors: ` 42#3F│code` */
54
+ export function formatSmartAnchorLines(
55
+ fileLines: readonly string[],
56
+ startLine = 1,
57
+ endLine = fileLines.length,
58
+ ): string {
59
+ const totalDigits = String(endLine).length;
60
+ const clampedStart = Math.max(1, startLine);
61
+ const clampedEnd = Math.min(fileLines.length, endLine);
62
+
63
+ return fileLines
64
+ .slice(clampedStart - 1, clampedEnd)
65
+ .map((line, idx) => {
66
+ const lineNum = clampedStart + idx;
67
+ const pad = String(lineNum).padStart(totalDigits, " ");
68
+ const hash = computeLineHash(fileLines, lineNum - 1);
69
+ return `${pad}${ANCHOR_SEP}${hash}${CONTENT_SEP}${line}`;
70
+ })
71
+ .join("\n");
72
+ }
73
+
74
+ // ─── Anchor Parsing ─────────────────────────────────────────────────────────
75
+
76
+ export interface ParsedAnchor {
77
+ line: number;
78
+ hash?: string;
79
+ raw: string;
80
+ }
81
+
82
+ /**
83
+ * Parse an anchor reference string or integer.
84
+ * Accepts: "288#ZH", " 288#ZH│code", "288", or numeric 288.
85
+ */
86
+ export function parseAnchorRef(ref: string | number): ParsedAnchor {
87
+ if (typeof ref === "number") {
88
+ if (!Number.isFinite(ref) || ref < 1) {
89
+ throw new Error(`Invalid line number: ${ref}. Must be an integer >= 1.`);
90
+ }
91
+ return { line: Math.floor(ref), raw: String(ref) };
92
+ }
93
+
94
+ const core = ref.trim();
95
+ if (!core) {
96
+ throw new Error(`Empty anchor reference provided.`);
97
+ }
98
+
99
+ const match = core.match(/^(\d+)(?:#([0-9A-Fa-f]{2}))?(?:[│:].*)?$/);
100
+ if (!match) {
101
+ throw new Error(`Invalid anchor format "${ref}". Expected "LINE#HASH" (e.g. "42#3F") or line number "42".`);
102
+ }
103
+
104
+ const line = parseInt(match[1], 10);
105
+ if (line < 1) {
106
+ throw new Error(`Line number must be >= 1, got ${line} in "${ref}".`);
107
+ }
108
+
109
+ return {
110
+ line,
111
+ hash: match[2] ? match[2].toUpperCase() : undefined,
112
+ raw: core,
113
+ };
114
+ }
115
+
116
+ // ─── Anchor Validation & Neighbor Spillover Recovery ─────────────────────────
117
+
118
+ export interface SmartAnchorEditBlock {
119
+ pos?: string | number;
120
+ end?: string | number;
121
+ start_line?: number;
122
+ end_line?: number;
123
+ lines?: string[];
124
+ search?: string;
125
+ replace?: string;
126
+ }
127
+
128
+ export interface ResolvedSmartSpan {
129
+ startLine: number;
130
+ endLine: number;
131
+ replacementLines: string[];
132
+ recoveredNeighbor?: boolean;
133
+ }
134
+
135
+ export interface SmartAnchorPreflightResult {
136
+ success: boolean;
137
+ error?: string;
138
+ staleDetails?: string;
139
+ targetRanges?: PatchTargetRange[];
140
+ resolvedSpans?: ResolvedSmartSpan[];
141
+ }
142
+
143
+ function formatStaleAnchorError(
144
+ fileLines: readonly string[],
145
+ line: number,
146
+ expectedHash: string,
147
+ actualHash: string,
148
+ ): string {
149
+ const start = Math.max(1, line - 2);
150
+ const end = Math.min(fileLines.length, line + 2);
151
+ const preview = formatSmartAnchorLines(fileLines, start, end);
152
+ return `[E_STALE_ANCHOR] Anchor mismatch at line ${line}: expected #${expectedHash}, actual file has #${actualHash}.\n` +
153
+ `Current context:\n${preview}\nCopy the current anchors from above and retry.`;
154
+ }
155
+
156
+ /**
157
+ * Preflight and resolve anchor blocks against file lines.
158
+ * Applies neighbor tolerance [L-1, L+1] to recover from model attention spillover.
159
+ */
160
+ export function preflightSmartAnchorEdits(
161
+ fileContent: string,
162
+ edits: SmartAnchorEditBlock[],
163
+ ): SmartAnchorPreflightResult {
164
+ const fileLines = fileContent.split("\n");
165
+ const totalLines = fileLines.length;
166
+ const resolvedSpans: ResolvedSmartSpan[] = [];
167
+ const targetRanges: PatchTargetRange[] = [];
168
+
169
+ for (let i = 0; i < edits.length; i++) {
170
+ const block = edits[i];
171
+ if (!block) continue;
172
+
173
+ // Handle fallback search/replace block embedded in edits
174
+ if (typeof block.search === "string" && typeof block.replace === "string") {
175
+ const idx = fileContent.indexOf(block.search);
176
+ if (idx < 0) {
177
+ return {
178
+ success: false,
179
+ error: `[EDIT FAILED] Block ${i + 1}/${edits.length}: search text not found in file.`,
180
+ };
181
+ }
182
+ const count = fileContent.split(block.search).length - 1;
183
+ if (count > 1) {
184
+ return {
185
+ success: false,
186
+ error: `[EDIT FAILED] Block ${i + 1}/${edits.length} is ambiguous: matched ${count} times in file.`,
187
+ };
188
+ }
189
+ const beforeMatch = fileContent.slice(0, idx);
190
+ const startL = beforeMatch.split("\n").length;
191
+ const matchLines = block.search.split("\n").length;
192
+ const endL = startL + matchLines - 1;
193
+ resolvedSpans.push({
194
+ startLine: startL,
195
+ endLine: endL,
196
+ replacementLines: block.replace.split("\n"),
197
+ });
198
+ targetRanges.push({ startLine: startL, endLine: endL });
199
+ continue;
200
+ }
201
+
202
+ // Positional anchor resolution
203
+ let startLine = block.start_line;
204
+ let endLine = block.end_line;
205
+ let startHash: string | undefined;
206
+ let endHash: string | undefined;
207
+
208
+ if (block.pos !== undefined) {
209
+ try {
210
+ const p = parseAnchorRef(block.pos);
211
+ startLine = p.line;
212
+ startHash = p.hash;
213
+ } catch (err: any) {
214
+ return { success: false, error: `Block ${i + 1}: ${err.message}` };
215
+ }
216
+ }
217
+
218
+ if (block.end !== undefined) {
219
+ try {
220
+ const e = parseAnchorRef(block.end);
221
+ endLine = e.line;
222
+ endHash = e.hash;
223
+ } catch (err: any) {
224
+ return { success: false, error: `Block ${i + 1}: ${err.message}` };
225
+ }
226
+ }
227
+
228
+ if (startLine === undefined) {
229
+ return {
230
+ success: false,
231
+ error: `Block ${i + 1}: missing anchor. Must specify 'pos', 'start_line', or 'search'.`,
232
+ };
233
+ }
234
+ if (endLine === undefined) {
235
+ endLine = startLine;
236
+ }
237
+
238
+ if (startLine < 1 || startLine > totalLines) {
239
+ return {
240
+ success: false,
241
+ error: `[E_RANGE_OOB] Block ${i + 1}: start line ${startLine} is out of file bounds (1-${totalLines}).`,
242
+ };
243
+ }
244
+ if (endLine < startLine || endLine > totalLines) {
245
+ return {
246
+ success: false,
247
+ error: `[E_RANGE_OOB] Block ${i + 1}: end line ${endLine} is invalid (start: ${startLine}, file lines: ${totalLines}).`,
248
+ };
249
+ }
250
+
251
+ let recoveredNeighbor = false;
252
+
253
+ // Verify Start Anchor Hash
254
+ if (startHash) {
255
+ const actualHash = computeLineHash(fileLines, startLine - 1);
256
+ if (actualHash !== startHash) {
257
+ // Neighbor tolerance check: attention spillover across adjacent lines
258
+ const prevHash = startLine > 1 ? computeLineHash(fileLines, startLine - 2) : undefined;
259
+ const nextHash = startLine < totalLines ? computeLineHash(fileLines, startLine) : undefined;
260
+
261
+ if (startHash === prevHash || startHash === nextHash) {
262
+ recoveredNeighbor = true;
263
+ } else {
264
+ return {
265
+ success: false,
266
+ error: formatStaleAnchorError(fileLines, startLine, startHash, actualHash),
267
+ };
268
+ }
269
+ }
270
+ }
271
+
272
+ // Verify End Anchor Hash
273
+ if (endHash) {
274
+ const actualEndHash = computeLineHash(fileLines, endLine - 1);
275
+ if (actualEndHash !== endHash) {
276
+ const prevHash = endLine > 1 ? computeLineHash(fileLines, endLine - 2) : undefined;
277
+ const nextHash = endLine < totalLines ? computeLineHash(fileLines, endLine) : undefined;
278
+
279
+ if (endHash === prevHash || endHash === nextHash) {
280
+ recoveredNeighbor = true;
281
+ } else {
282
+ return {
283
+ success: false,
284
+ error: formatStaleAnchorError(fileLines, endLine, endHash, actualEndHash),
285
+ };
286
+ }
287
+ }
288
+ }
289
+
290
+ const replacementLines = Array.isArray(block.lines) ? block.lines : [];
291
+ resolvedSpans.push({
292
+ startLine,
293
+ endLine,
294
+ replacementLines,
295
+ recoveredNeighbor,
296
+ });
297
+ targetRanges.push({ startLine, endLine });
298
+ }
299
+
300
+ // Check for conflicting / overlapping spans
301
+ for (let j = 0; j < resolvedSpans.length; j++) {
302
+ const left = resolvedSpans[j]!;
303
+ for (let k = j + 1; k < resolvedSpans.length; k++) {
304
+ const right = resolvedSpans[k]!;
305
+ if (left.startLine <= right.endLine && right.startLine <= left.endLine) {
306
+ return {
307
+ success: false,
308
+ error: `[E_EDIT_CONFLICT] Blocks ${j + 1} (lines ${left.startLine}-${left.endLine}) and ${k + 1} (lines ${right.startLine}-${right.endLine}) overlap. Merge them into a single edit or apply disjoint ranges.`,
309
+ };
310
+ }
311
+ }
312
+ }
313
+
314
+ return {
315
+ success: true,
316
+ targetRanges,
317
+ resolvedSpans,
318
+ };
319
+ }
320
+
321
+ // ─── Applying Smart Anchor Edits ─────────────────────────────────────────────
322
+
323
+ export function applySmartAnchorEdits(
324
+ filePath: string,
325
+ edits: SmartAnchorEditBlock[],
326
+ ): PatchResult {
327
+ const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);
328
+ if (!fs.existsSync(resolvedPath)) {
329
+ return {
330
+ success: false,
331
+ filePath: resolvedPath,
332
+ strategy: "smart_anchor",
333
+ error: `File not found: ${resolvedPath}`,
334
+ };
335
+ }
336
+
337
+ let originalContent: string;
338
+ try {
339
+ originalContent = fs.readFileSync(resolvedPath, "utf8");
340
+ } catch (err: any) {
341
+ return {
342
+ success: false,
343
+ filePath: resolvedPath,
344
+ strategy: "smart_anchor",
345
+ error: `Unable to read ${resolvedPath}: ${err.message}`,
346
+ };
347
+ }
348
+
349
+ const preflight = preflightSmartAnchorEdits(originalContent, edits);
350
+ if (!preflight.success || !preflight.resolvedSpans) {
351
+ return {
352
+ success: false,
353
+ filePath: resolvedPath,
354
+ strategy: "smart_anchor",
355
+ error: preflight.error || "Failed to resolve anchor edits",
356
+ };
357
+ }
358
+
359
+ const fileLines = originalContent.split("\n");
360
+ const currentLines = [...fileLines];
361
+
362
+ // Sort spans strictly bottom-to-top (descending line number) so edits do not shift earlier lines
363
+ const sortedSpans = [...preflight.resolvedSpans].sort((a, b) => b.startLine - a.startLine);
364
+
365
+ for (const span of sortedSpans) {
366
+ const deleteCount = span.endLine - span.startLine + 1;
367
+ currentLines.splice(span.startLine - 1, deleteCount, ...span.replacementLines);
368
+ }
369
+
370
+ const candidateContent = currentLines.join("\n");
371
+
372
+ // Syntax validation gate
373
+ const syntax = checkSyntaxContent(resolvedPath, candidateContent);
374
+ if (!syntax.valid) {
375
+ return {
376
+ success: false,
377
+ filePath: resolvedPath,
378
+ strategy: "smart_anchor",
379
+ error: syntax.error || "Candidate syntax validation failed after anchor edits",
380
+ };
381
+ }
382
+
383
+ // Freshness verification: ensure file didn't change on disk during resolution
384
+ try {
385
+ const diskCheck = fs.readFileSync(resolvedPath, "utf8");
386
+ if (diskCheck !== originalContent) {
387
+ return {
388
+ success: false,
389
+ filePath: resolvedPath,
390
+ strategy: "smart_anchor",
391
+ error: `File changed while applying edits: ${resolvedPath}. Re-read and retry.`,
392
+ };
393
+ }
394
+ writeFileSyncAtomic(resolvedPath, candidateContent);
395
+ } catch (writeErr: any) {
396
+ return {
397
+ success: false,
398
+ filePath: resolvedPath,
399
+ strategy: "smart_anchor",
400
+ error: `Unable to write ${resolvedPath}: ${writeErr.message}`,
401
+ };
402
+ }
403
+
404
+ // Unified diff output
405
+ const diffOutput = diff.createPatch(
406
+ resolvedPath,
407
+ originalContent,
408
+ candidateContent,
409
+ "original",
410
+ "modified",
411
+ );
412
+
413
+ return {
414
+ success: true,
415
+ filePath: resolvedPath,
416
+ strategy: "smart_anchor",
417
+ diffOutput,
418
+ targetRanges: preflight.targetRanges,
419
+ };
420
+ }