@criogaid/pi-hashline-edit 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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +279 -0
  3. package/package.json +50 -0
  4. package/src/core/apply.test.ts +327 -0
  5. package/src/core/apply.ts +264 -0
  6. package/src/core/hash.test.ts +54 -0
  7. package/src/core/hash.ts +68 -0
  8. package/src/core/index.ts +13 -0
  9. package/src/core/lines.test.ts +33 -0
  10. package/src/core/lines.ts +52 -0
  11. package/src/core/types.ts +87 -0
  12. package/src/index.ts +44 -0
  13. package/src/integration/grep-rg.test.ts +390 -0
  14. package/src/pi/action-fusion.test.ts +244 -0
  15. package/src/pi/action-fusion.ts +284 -0
  16. package/src/pi/config.test.ts +22 -0
  17. package/src/pi/config.ts +56 -0
  18. package/src/pi/edit-tool.ts +367 -0
  19. package/src/pi/execute.test.ts +521 -0
  20. package/src/pi/failure-context.test.ts +88 -0
  21. package/src/pi/failure-context.ts +98 -0
  22. package/src/pi/failure-path.test.ts +60 -0
  23. package/src/pi/file-commit.test.ts +200 -0
  24. package/src/pi/file-commit.ts +185 -0
  25. package/src/pi/fusion-card.test.ts +69 -0
  26. package/src/pi/fusion-card.ts +78 -0
  27. package/src/pi/grep-tool.ts +795 -0
  28. package/src/pi/grep.test.ts +515 -0
  29. package/src/pi/pi.test.ts +19 -0
  30. package/src/pi/read-tool.ts +178 -0
  31. package/src/pi/registration.test.ts +41 -0
  32. package/src/pi/render.ts +103 -0
  33. package/src/pi/replace-tool.ts +303 -0
  34. package/src/pi/replace.test.ts +287 -0
  35. package/src/pi/rg-line-filter.test.ts +79 -0
  36. package/src/pi/rg-line-filter.ts +358 -0
  37. package/src/pi/rg-line-ranges.test.ts +30 -0
  38. package/src/pi/rg-line-ranges.ts +106 -0
  39. package/src/pi/state.ts +27 -0
  40. package/src/pi/write-tool.ts +83 -0
  41. package/src/pi/write.test.ts +126 -0
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Per-line content hash.
3
+ *
4
+ * The hash mixes the 1-based line number into the line content, so every line
5
+ * gets a unique hash by construction — line numbers are unique, therefore no
6
+ * in-file collision is possible, and no length extension / fallback is ever
7
+ * needed.
8
+ *
9
+ * Why line + content (not content alone, not content + neighbors):
10
+ *
11
+ * - The line number is the address; the hash is a checksum that the line at
12
+ * that address is still what was read. Mixing the number in makes the hash a
13
+ * pure fingerprint of (position, content): it changes only when the line's
14
+ * own content changes, never when a neighbor changes. (A neighbor-aware hash
15
+ * would change an unchanged line's hash when an adjacent line is edited — a
16
+ * spurious dependency with no benefit under this design's position-fixed
17
+ * apply.)
18
+ * - Content alone would leave identical lines (blank lines, `}`) sharing a
19
+ * hash; mixing the line number disambiguates them for free.
20
+ *
21
+ * @module pi-hashline-edit/core
22
+ */
23
+
24
+ /** Crockford base32 alphabet (without I/L/O/U to avoid ambiguous characters). Exactly 32 characters. */
25
+ const BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
26
+
27
+ /**
28
+ * FNV-1a 32-bit. Stable (same input always yields the same output), evenly
29
+ * distributed, non-cryptographic. Uses `Math.imul` for correct 32-bit integer
30
+ * multiplication under JS.
31
+ */
32
+ function fnv1a32(str: string): number {
33
+ let h = 0x811c9dc5;
34
+ for (let i = 0; i < str.length; i++) {
35
+ h ^= str.charCodeAt(i);
36
+ h = Math.imul(h, 0x01000193);
37
+ }
38
+ return h >>> 0;
39
+ }
40
+
41
+ /** Encode a 32-bit integer into a base32 string of the given length. */
42
+ function toBase32(n: number, len: number): string {
43
+ let s = "";
44
+ for (let i = 0; i < len; i++) {
45
+ s = BASE32[n & 31] + s;
46
+ n = Math.floor(n / 32);
47
+ }
48
+ return s;
49
+ }
50
+
51
+ /**
52
+ * Compute the hash of a single line from its 1-based line number and content.
53
+ *
54
+ * @param line 1-based line number
55
+ * @param content the line's content (no line terminator)
56
+ * @param len hash length (default 4, 20 bits ≈ 1M values)
57
+ */
58
+ export function computeLineHash(line: number, content: string, len = 4): string {
59
+ return toBase32(fnv1a32(`${line}\n${content}`), len);
60
+ }
61
+
62
+ /**
63
+ * Compute per-line hashes for a file. Unique by construction — the 1-based line
64
+ * number is part of each hash, so two identical content lines always differ.
65
+ */
66
+ export function hashFileLines(lines: readonly string[], len = 4): string[] {
67
+ return lines.map((content, i) => computeLineHash(i + 1, content, len));
68
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Public API of the pi-hashline-edit core library.
3
+ *
4
+ * The pure hashline engine, with zero pi dependencies, runnable standalone via
5
+ * `node --test`. The pi integration layer lives under `../pi/`.
6
+ *
7
+ * @module pi-hashline-edit/core
8
+ */
9
+
10
+ export * from "./types.ts";
11
+ export { computeLineHash, hashFileLines } from "./hash.ts";
12
+ export { splitLines, detectLineEnding, hasFinalNewline } from "./lines.ts";
13
+ export { applyEdits } from "./apply.ts";
@@ -0,0 +1,33 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { splitLines, detectLineEnding, hasFinalNewline } from "./lines.ts";
4
+
5
+ test("splitLines edge cases", () => {
6
+ assert.deepEqual(splitLines(""), []);
7
+ assert.deepEqual(splitLines("a"), ["a"]);
8
+ assert.deepEqual(splitLines("a\nb"), ["a", "b"]);
9
+ assert.deepEqual(splitLines("a\nb\n"), ["a", "b"]);
10
+ assert.deepEqual(splitLines("a\n\n"), ["a", ""]);
11
+ assert.deepEqual(splitLines("\n"), [""]);
12
+ });
13
+
14
+ test("splitLines strips CRLF \\r", () => {
15
+ assert.deepEqual(splitLines("a\r\nb\r\n"), ["a", "b"]);
16
+ assert.deepEqual(splitLines("a\r\nb"), ["a", "b"]);
17
+ });
18
+
19
+ test("hasFinalNewline", () => {
20
+ assert.equal(hasFinalNewline("a\nb"), false);
21
+ assert.equal(hasFinalNewline("a\nb\n"), true);
22
+ assert.equal(hasFinalNewline("a\r\nb"), false);
23
+ assert.equal(hasFinalNewline("a\r\nb\r\n"), true);
24
+ assert.equal(hasFinalNewline("a"), false);
25
+ // no lines, no terminator — rejoining [] yields "" either way
26
+ assert.equal(hasFinalNewline(""), true);
27
+ });
28
+
29
+ test("detectLineEnding", () => {
30
+ assert.equal(detectLineEnding("a\nb\n"), "lf");
31
+ assert.equal(detectLineEnding("a\r\nb\r\n"), "crlf");
32
+ assert.equal(detectLineEnding("a\nb\r\nc\n"), "crlf");
33
+ });
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Line text helpers: split/join with CRLF normalization, line-ending detection
3
+ * and final-newline fidelity.
4
+ *
5
+ * CRLF: splitLines normalizes `\r\n` boundaries while preserving standalone
6
+ * `\r` content. detectLineEnding records whether the file uses CRLF at all
7
+ * (any `\r\n` counts) so new boundaries added by an edit can use the file's
8
+ * customary ending.
9
+ *
10
+ * Final newline: splitLines discards whether the input ended with a terminator
11
+ * (a trailing newline terminates the last line, it does not create one).
12
+ * hasFinalNewline recovers that state so a file that lacked a final newline
13
+ * does not silently gain one — editing reassembles per-line separators and
14
+ * must suppress the last line's terminator accordingly.
15
+ *
16
+ * @module pi-hashline-edit/core
17
+ */
18
+
19
+ import type { LineEnding } from "./types.ts";
20
+
21
+ /**
22
+ * Split text into lines, normalizing CRLF boundaries and preserving standalone `\r`.
23
+ *
24
+ * Convention: a trailing newline is treated as the terminator of the last line,
25
+ * not as producing an extra empty trailing line.
26
+ * - `"a\nb\n"` → `["a", "b"]`
27
+ * - `"a\r\nb\r\n"` → `["a", "b"]` (`\r` stripped)
28
+ * - `"a\n\n"` → `["a", ""]`
29
+ * - `""` → `[]`
30
+ */
31
+ export function splitLines(text: string): string[] {
32
+ if (text === "") return [];
33
+ const normalized = text.replace(/\r\n/g, "\n");
34
+ return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
35
+ }
36
+
37
+ /** Whether the text uses CRLF at all (any `\r\n` counts; mixed files report "crlf"). */
38
+ export function detectLineEnding(text: string): LineEnding {
39
+ return text.includes("\r\n") ? "crlf" : "lf";
40
+ }
41
+
42
+ /**
43
+ * Whether the text ends with a line terminator — the state splitLines discards
44
+ * and edit application needs in order to reproduce a document byte for byte.
45
+ *
46
+ * The empty string has no lines and no terminator; it reports `true` so that
47
+ * rejoining its (also empty) line array — which yields `""` either way —
48
+ * round-trips.
49
+ */
50
+ export function hasFinalNewline(text: string): boolean {
51
+ return text === "" || text.endsWith("\n");
52
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Hashline core type definitions.
3
+ *
4
+ * @module pi-hashline-edit/core
5
+ */
6
+
7
+ /** Line anchor: dual reference of line number (1-based) + content hash. */
8
+ export interface Anchor {
9
+ readonly line: number;
10
+ readonly hash: string;
11
+ }
12
+
13
+ /**
14
+ * Edit operation. Every line-numbered op references a line via {@link Anchor} —
15
+ * the line number is the address, the hash a checksum that the line at that
16
+ * address is still what was read; both must match at apply time.
17
+ */
18
+ export type Edit =
19
+ | { readonly op: "replace"; readonly start: Anchor; readonly end?: Anchor; readonly body: string[] }
20
+ | { readonly op: "delete"; readonly start: Anchor; readonly end?: Anchor }
21
+ | { readonly op: "insert_after"; readonly anchor: Anchor; readonly body: string[] }
22
+ | { readonly op: "insert_before"; readonly anchor: Anchor; readonly body: string[] }
23
+ | { readonly op: "append"; readonly body: string[] }
24
+ | { readonly op: "prepend"; readonly body: string[] };
25
+
26
+ export type LineEnding = "lf" | "crlf";
27
+
28
+ /**
29
+ * Outcome of shifted-anchor recovery. When a cited anchor's hash no longer
30
+ * matches the live content, the applicator rescans ±radius lines for the
31
+ * original content — holding the ORIGINAL line number fixed and re-hashing each
32
+ * candidate's content (`computeLineHash(citedLine, candidateContent) === citedHash`
33
+ * iff the candidate is the original content). A ready-to-resend anchor (with the
34
+ * freshly computed hash) is returned so the model can retry without a re-read.
35
+ *
36
+ * - `found` — exactly one nearby line holds the original content; resend the op
37
+ * with the provided anchor.
38
+ * - `ambiguous` — several nearby lines match (e.g. duplicate content); the model
39
+ * picks the right one from the candidates (each carries its own new hash).
40
+ * - `none` — the content genuinely changed; re-read.
41
+ */
42
+ export type AnchorRecovery =
43
+ | { readonly kind: "found"; readonly newLine: number; readonly newHash: string }
44
+ | {
45
+ readonly kind: "ambiguous";
46
+ readonly candidates: ReadonlyArray<{ readonly line: number; readonly hash: string }>;
47
+ }
48
+ | { readonly kind: "none" };
49
+
50
+ /**
51
+ * A single anchor that failed verification, with its recovery attempt.
52
+ *
53
+ * `opIndex` is the 0-based position in the input `edits[]`; `which` names the
54
+ * op's anchor (`"anchor"` = start, `"end"` = range end); `op` is the op kind.
55
+ * `current` is the cited line's live content + hash (null if the line number is
56
+ * out of range) — surfaced when recovery is `none` so the model can self-diagnose.
57
+ */
58
+ export interface AnchorFailure {
59
+ readonly opIndex: number;
60
+ readonly which: "anchor" | "end";
61
+ readonly op: Edit["op"];
62
+ readonly cited: Anchor;
63
+ readonly recovery: AnchorRecovery;
64
+ readonly current: { readonly hash: string; readonly content: string } | null;
65
+ }
66
+
67
+ /** Batch-level failure. `anchor` carries every per-anchor failure collected across the batch. */
68
+ export type ApplyFailure =
69
+ | { readonly kind: "anchor"; readonly failures: readonly AnchorFailure[] }
70
+ | { readonly kind: "range"; readonly message: string }
71
+ | { readonly kind: "noop"; readonly message: string };
72
+
73
+ /**
74
+ * Apply result. On success, `touchedLines` lists the 0-based line indices in
75
+ * the NEW file that this edit produced (inserted or replaced) — callers use it
76
+ * to surface fresh `LINE#HASH` anchors so the model can chain edits without a
77
+ * re-read. On failure, `failure` is either the collected set of anchor failures
78
+ * (each with recovery) or a single range/noop error; nothing is written.
79
+ */
80
+ export type ApplyResult =
81
+ | {
82
+ readonly ok: true;
83
+ readonly text: string;
84
+ readonly changed: boolean;
85
+ readonly touchedLines: readonly number[];
86
+ }
87
+ | { readonly ok: false; readonly failure: ApplyFailure };
package/src/index.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * pi-hashline-edit extension entry.
3
+ *
4
+ * Overrides the built-in read/edit: read outputs "lineNo#hash│content";
5
+ * edit accepts structured hashline ops (edits[] with LINE#HASH anchors), and
6
+ * legacy oldText/newText is rejected explicitly (no silent degradation). grep
7
+ * is overridden the same way so results carry usable anchors. A separate
8
+ * `replace` tool adds location-blind bulk + regex replacement (replaceAll and
9
+ * full JS regex with capture groups) for renames/pattern transforms that
10
+ * would need many individual edits. Each tool carries its own renderer.
11
+ *
12
+ * @module pi-hashline-edit
13
+ */
14
+
15
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
+ import { loadConfig } from "./pi/config.ts";
17
+ import { getState } from "./pi/state.ts";
18
+ import { makeEditOverride } from "./pi/edit-tool.ts";
19
+ import { makeReadOverride } from "./pi/read-tool.ts";
20
+ import { makeGrepOverride } from "./pi/grep-tool.ts";
21
+ import { makeReplaceTool } from "./pi/replace-tool.ts";
22
+ import { makeWriteOverride } from "./pi/write-tool.ts";
23
+ import { createActionFusionExecutor } from "./pi/action-fusion.ts";
24
+ import { registerFusionCards } from "./pi/fusion-card.ts";
25
+
26
+ export default function (pi: ExtensionAPI) {
27
+ const cwd = process.cwd();
28
+
29
+ const state = getState();
30
+ state.config = loadConfig(cwd);
31
+
32
+ // `enabled: false` leaves the extension fully inert — pi's built-in
33
+ // read/edit/grep/replace/write stay in place, as if this package were not installed.
34
+ if (state.config.enabled) {
35
+ const reportProgress = registerFusionCards(pi);
36
+ const fusion = state.config.actionFusion ? createActionFusionExecutor(undefined, reportProgress) : undefined;
37
+ pi.registerTool(makeWriteOverride(cwd, fusion));
38
+ pi.registerTool(makeEditOverride(cwd, fusion));
39
+ pi.registerTool(makeReplaceTool(cwd, fusion));
40
+
41
+ pi.registerTool(makeReadOverride(cwd));
42
+ pi.registerTool(makeGrepOverride(cwd));
43
+ }
44
+ }