@criogaid/pi-hashline-edit 0.4.0 → 0.5.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 (60) hide show
  1. package/README.md +116 -20
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.ts +1 -3
  10. package/src/core/types.ts +4 -7
  11. package/src/index.ts +9 -11
  12. package/src/integration/config-registration.test.ts +206 -0
  13. package/src/integration/grep-rg.test.ts +73 -60
  14. package/src/integration/large-text.test.ts +9 -8
  15. package/src/integration/replace-package.test.ts +11 -7
  16. package/src/pi/action-fusion.test.ts +110 -34
  17. package/src/pi/action-fusion.ts +77 -114
  18. package/src/pi/anchor-format.test.ts +43 -22
  19. package/src/pi/anchor-format.ts +23 -8
  20. package/src/pi/budgets.ts +7 -2
  21. package/src/pi/config.test.ts +153 -40
  22. package/src/pi/config.ts +87 -41
  23. package/src/pi/e2e-scenarios.test.ts +12 -11
  24. package/src/pi/edit-tool.ts +20 -156
  25. package/src/pi/error-text.ts +10 -5
  26. package/src/pi/execute.test.ts +299 -175
  27. package/src/pi/failure-context.test.ts +7 -2
  28. package/src/pi/failure-context.ts +155 -8
  29. package/src/pi/failure-path.test.ts +33 -26
  30. package/src/pi/file-commit.ts +2 -1
  31. package/src/pi/fusion-card.ts +83 -2
  32. package/src/pi/grep-output.ts +26 -9
  33. package/src/pi/grep-render.ts +6 -5
  34. package/src/pi/grep-scope.ts +2 -15
  35. package/src/pi/grep-search.ts +29 -15
  36. package/src/pi/grep-tool.ts +94 -78
  37. package/src/pi/grep.test.ts +357 -320
  38. package/src/pi/mutation-outcome.testing.ts +22 -0
  39. package/src/pi/mutation-result.test.ts +51 -2
  40. package/src/pi/mutation-result.ts +62 -55
  41. package/src/pi/mutation-runner.ts +16 -33
  42. package/src/pi/pi.test.ts +10 -5
  43. package/src/pi/read-tool.ts +61 -33
  44. package/src/pi/registration.test.ts +1 -5
  45. package/src/pi/render.test.ts +16 -8
  46. package/src/pi/render.ts +4 -91
  47. package/src/pi/replace-regex.ts +54 -0
  48. package/src/pi/replace-tool.ts +24 -58
  49. package/src/pi/replace-worker.ts +2 -2
  50. package/src/pi/replace.test.ts +62 -58
  51. package/src/pi/result-safety.test.ts +124 -84
  52. package/src/pi/rg-line-ranges.ts +3 -2
  53. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  54. package/src/pi/{rg-line-filter.ts → rg-process.ts} +35 -4
  55. package/src/pi/rg-text-view.ts +17 -33
  56. package/src/pi/schema.ts +2 -10
  57. package/src/pi/write-tool.ts +1 -2
  58. package/src/pi/write.test.ts +10 -9
  59. package/src/core/index.ts +0 -14
  60. package/src/pi/state.ts +0 -26
@@ -0,0 +1,22 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import { byteRevision } from "./file-commit.ts";
3
+ import type { MutationOutcome } from "./mutation-result.ts";
4
+
5
+ /** Build a completed overwrite fixture with matching published and observed bytes. */
6
+ export function publishedMutation<T>(
7
+ content: string,
8
+ result: AgentToolResult<T>,
9
+ anchors?: string,
10
+ ): MutationOutcome<T> {
11
+ const revision = byteRevision(content);
12
+ return {
13
+ result,
14
+ commit: {
15
+ publication: "PUBLISHED",
16
+ publishedRevision: revision,
17
+ observedRevision: revision,
18
+ created: false,
19
+ },
20
+ anchors,
21
+ };
22
+ }
@@ -1,9 +1,10 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
4
- import { generateMutationDetails } from "./mutation-result.ts";
5
- import { displayCarriageReturns } from "./anchor-format.ts";
4
+ import { formatMutationAnchors, generateMutationDetails } from "./mutation-result.ts";
5
+ import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
6
6
  import { byteRevision } from "./file-commit.ts";
7
+ import { MAX_BLOCK_BYTES } from "./budgets.ts";
7
8
 
8
9
  for (const [name, before, after] of [
9
10
  ["LF", "guard\nold\ntail\n", "guard\nnew\ntail\n"],
@@ -35,3 +36,51 @@ for (const [name, before, after] of [
35
36
  });
36
37
  });
37
38
  }
39
+
40
+ test("mutation anchors use the full byte budget when no omission notice is needed", () => {
41
+ const anchors = createAnchorFormatter(4);
42
+ const heading = "Updated anchors:";
43
+ const prefix = `\n${heading}\n`;
44
+ const available = MAX_BLOCK_BYTES - Buffer.byteLength(prefix + anchors.row(1, ""));
45
+ const content = "界".repeat(Math.floor(available / 3)) + "x".repeat(available % 3);
46
+ const expected = prefix + anchors.row(1, content);
47
+ assert.equal(Buffer.byteLength(expected), MAX_BLOCK_BYTES);
48
+ const report = formatMutationAnchors([], [content], [0], anchors, heading, new Set([0]));
49
+ assert.equal(report, expected);
50
+ });
51
+
52
+ test("mutation anchors count separators exactly at the byte boundary", () => {
53
+ const anchors = createAnchorFormatter(4);
54
+ const heading = "Updated anchors:";
55
+ const prefix = `\n${heading}\n`;
56
+ const tail = "tail";
57
+ const overhead = Buffer.byteLength(`${prefix}${anchors.row(1, "")}\n${anchors.row(2, tail)}`);
58
+ const lines = ["x".repeat(MAX_BLOCK_BYTES - overhead), tail];
59
+ const expected = prefix + lines.map((line, index) => anchors.row(index + 1, line)).join("\n");
60
+ assert.equal(Buffer.byteLength(expected), MAX_BLOCK_BYTES);
61
+ assert.equal(
62
+ formatMutationAnchors([], lines, [0, 1], anchors, heading, new Set([0, 1])),
63
+ expected,
64
+ );
65
+ });
66
+
67
+ test("mutation anchors reserve the notice after overflow and retain later fitting rows", () => {
68
+ const anchors = createAnchorFormatter(4);
69
+ const heading = "Updated anchors:";
70
+ const overhead = Buffer.byteLength(`\n${heading}\n${anchors.row(1, "")}`);
71
+ for (const extra of [0, 1, MAX_BLOCK_BYTES]) {
72
+ const lines = ["x".repeat(MAX_BLOCK_BYTES - overhead + extra), "short", "last"];
73
+ const report = formatMutationAnchors(
74
+ [],
75
+ lines,
76
+ [0, 1, 2].values(),
77
+ anchors,
78
+ heading,
79
+ new Set([0, 1, 2]),
80
+ );
81
+ assert.ok(Buffer.byteLength(report) <= MAX_BLOCK_BYTES);
82
+ assert.match(report, /additional anchors omitted/);
83
+ assert.ok(!report.includes(anchors.row(1, lines[0])));
84
+ assert.ok(report.includes(`${anchors.row(2, lines[1])}\n${anchors.row(3, lines[2])}`));
85
+ }
86
+ });
@@ -1,9 +1,14 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
- import { FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
2
+ import {
3
+ FileMutationError,
4
+ type CommitResult,
5
+ type MutationVersions,
6
+ type PublicationStatus,
7
+ } from "./file-commit.ts";
3
8
  import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
4
9
  import { displayCarriageReturns, type AnchorFormatter } from "./anchor-format.ts";
5
10
  import { normalizeLineEndings } from "../core/lines.ts";
6
- import { errorMessage } from "./error-text.ts";
11
+ import { errorMessage } from "../core/errors.ts";
7
12
  import { formatKiB, MAX_BLOCK_BYTES } from "./budgets.ts";
8
13
 
9
14
  /** Keep byte-faithful diff/patch data and a separate preview of the shared logical text. */
@@ -49,55 +54,47 @@ export function postProcessMutation<T>(
49
54
  }
50
55
  }
51
56
 
52
- /** Append only to the summary block after the caller confirms anchor freshness. */
53
- export function appendMutationAnchors<T>(
54
- result: AgentToolResult<T>,
55
- anchors: string,
56
- publish: boolean,
57
- ): AgentToolResult<T> {
58
- return {
59
- ...result,
60
- content: result.content.map((block, index) =>
61
- index === 0 && block.type === "text"
62
- ? { ...block, text: `${block.text}${publish ? anchors : ""}` }
63
- : block,
64
- ),
65
- };
57
+ /** A published (or no-op) mutation with its commit facts, before anchors are released. */
58
+ export interface MutationOutcome<TDetails> {
59
+ readonly result: AgentToolResult<TDetails>;
60
+ /** Publication and revisions from the commit layer; later steps never read them back from details. */
61
+ readonly commit: CommitResult;
62
+ /** Fresh anchor report for the committed text; absent for tools that never report anchors. */
63
+ readonly anchors?: string;
66
64
  }
67
65
 
68
- export function observedFreshness(
69
- result: AgentToolResult<unknown>,
70
- ): "unchanged" | "changed" | "unknown" {
71
- const versions = result.details as Partial<MutationVersions> | undefined;
72
- if (!versions?.publishedRevision || !versions.observedRevision) return "unknown";
73
- return versions.publishedRevision === versions.observedRevision ? "unchanged" : "changed";
66
+ /** Freshness known from the commit layer alone, before any later observation. */
67
+ export function commitFreshness(commit: MutationVersions): "unchanged" | "changed" {
68
+ return commit.publishedRevision === commit.observedRevision ? "unchanged" : "changed";
74
69
  }
75
70
 
76
- /** Finalize from the observed commit revision unless a later freshness check supplies the decision. */
77
- export function finalizeMutationResult<T>(
78
- result: AgentToolResult<T>,
79
- finalize: (result: AgentToolResult<T>, publishAnchors: boolean) => AgentToolResult<T>,
80
- publishAnchors = observedFreshness(result) === "unchanged",
81
- staleNotice = "Anchors omitted: target revision was not confirmed unchanged. Re-read before further edits.",
71
+ /** The single notice for a target whose published revision was not confirmed unchanged. */
72
+ export function staleTargetNotice(marker = ""): string {
73
+ return `${marker ? `${marker} ` : ""}Target not confirmed unchanged since publication; anchors are withheld and earlier anchors may no longer match. Re-read before further edits.`;
74
+ }
75
+
76
+ /**
77
+ * Release the result: append anchors to the summary when the target is fresh,
78
+ * otherwise add the stale notice (prefixed by `staleMarker`, e.g. then_run's).
79
+ */
80
+ export function finalizeMutation<T>(
81
+ { result, anchors }: MutationOutcome<T>,
82
+ fresh: boolean,
83
+ staleMarker = "",
82
84
  ): AgentToolResult<T> {
83
- try {
84
- const finalized = finalize(result, publishAnchors);
85
- return publishAnchors
86
- ? finalized
87
- : {
88
- ...finalized,
89
- content: [...finalized.content, { type: "text", text: staleNotice }],
90
- };
91
- } catch (error) {
92
- const publication =
93
- (result.details as { publication?: PublicationStatus } | undefined)?.publication ?? "UNKNOWN";
94
- throw new FileMutationError(
95
- "post_process",
96
- publication,
97
- `Result generation failed; publication=${publication}. Re-read before retrying: ${errorMessage(error)}`,
98
- { cause: error },
99
- );
85
+ if (!fresh) {
86
+ return {
87
+ ...result,
88
+ content: [...result.content, { type: "text", text: staleTargetNotice(staleMarker) }],
89
+ };
100
90
  }
91
+ if (!anchors) return result;
92
+ return {
93
+ ...result,
94
+ content: result.content.map((block, index) =>
95
+ index === 0 && block.type === "text" ? { ...block, text: block.text + anchors } : block,
96
+ ),
97
+ };
101
98
  }
102
99
 
103
100
  /** Return compact changed-position anchors; selected context rows retain full content within the byte budget. */
@@ -110,9 +107,17 @@ export function formatMutationAnchors(
110
107
  contentIndices?: ReadonlySet<number>,
111
108
  ): string {
112
109
  const notice = `\n… (additional anchors omitted: ${formatKiB(MAX_BLOCK_BYTES)} limit; use read for omitted positions)`;
113
- const rows: string[] = [];
114
- let bytes = Buffer.byteLength(`\n${heading}\n`) + Buffer.byteLength(notice);
110
+ const prefix = `\n${heading}\n`;
111
+ let rows: string[] = [];
112
+ let bytes = Buffer.byteLength(prefix);
115
113
  let omitted = false;
114
+ const append = (row: string): boolean => {
115
+ const rowBytes = Buffer.byteLength(row) + (rows.length ? 1 : 0);
116
+ if (bytes + rowBytes > MAX_BLOCK_BYTES) return false;
117
+ rows.push(row);
118
+ bytes += rowBytes;
119
+ return true;
120
+ };
116
121
  for (const index of indices) {
117
122
  const content = lines[index];
118
123
  // Compare source content, not short hashes: a collision must not suppress a changed row.
@@ -121,13 +126,15 @@ export function formatMutationAnchors(
121
126
  const row = contentIndices?.has(index)
122
127
  ? anchors.row(index + 1, content)
123
128
  : anchors.token(index + 1, content);
124
- const rowBytes = Buffer.byteLength(row) + 1;
125
- if (bytes + rowBytes > MAX_BLOCK_BYTES) {
126
- omitted = true;
127
- continue;
128
- }
129
- rows.push(row);
130
- bytes += rowBytes;
129
+ if (append(row) || omitted) continue;
130
+ // Only reserve a notice after overflow. Reconsider earlier rows in order so
131
+ // a newly oversized row does not prevent later, shorter rows from fitting.
132
+ omitted = true;
133
+ const previousRows = rows;
134
+ rows = [];
135
+ bytes = Buffer.byteLength(prefix) + Buffer.byteLength(notice);
136
+ for (const previous of previousRows) append(previous);
137
+ append(row);
131
138
  }
132
- return rows.length || omitted ? `\n${heading}\n${rows.join("\n")}${omitted ? notice : ""}` : "";
139
+ return rows.length || omitted ? `${prefix}${rows.join("\n")}${omitted ? notice : ""}` : "";
133
140
  }
@@ -1,11 +1,12 @@
1
1
  /**
2
2
  * Shared execution pipeline for the file mutation tools (edit, replace, write).
3
3
  *
4
- * Owns the sequencing every mutation tool must keep identical: then_run
5
- * availability, schema validation, path resolution, the shared file mutation
6
- * queue, and the hand-off to Action Fusion or plain finalization. Anchor
7
- * publication is an explicit outcome field rather than a side channel, so the
8
- * freshness rule (anchors only for an unchanged published revision) lives here.
4
+ * Owns the sequencing every mutation tool must keep identical once Pi has
5
+ * prepared and validated the arguments: separating then_run, path resolution,
6
+ * the shared file mutation queue, and the hand-off to Action Fusion or plain
7
+ * finalization. Each tool
8
+ * returns a typed `MutationOutcome` (result, commit facts, anchors); nothing
9
+ * downstream reads publication or revisions back from result details.
9
10
  *
10
11
  * `runTextMutation` adds the read-modify-write sequence shared by edit and
11
12
  * replace: snapshot bound to the bytes read, cancellation before apply and
@@ -24,10 +25,11 @@ import type {
24
25
  } from "./action-fusion.ts";
25
26
  import { commitReplacement, readEditableSnapshot } from "./file-commit.ts";
26
27
  import {
27
- appendMutationAnchors,
28
- finalizeMutationResult,
28
+ commitFreshness,
29
+ finalizeMutation,
29
30
  generateMutationDetails,
30
31
  postProcessMutation,
32
+ type MutationOutcome,
31
33
  } from "./mutation-result.ts";
32
34
  import { canonicalPath } from "./path.ts";
33
35
  import { throwIfCancelled } from "./error-text.ts";
@@ -48,20 +50,9 @@ export interface MutationTarget {
48
50
  readonly signal: AbortSignal | undefined;
49
51
  }
50
52
 
51
- export interface MutationOutcome<TDetails> {
52
- readonly result: AgentToolResult<TDetails>;
53
- /** Fresh anchor report; appended to the summary only once freshness is confirmed. */
54
- readonly anchors?: string;
55
- }
56
-
57
53
  export interface MutationToolSpec<TParams extends { path: string }, TDetails> {
58
54
  readonly cwd: string;
59
55
  readonly fusion: ActionFusionExecutor | undefined;
60
- /**
61
- * Whether results carry fresh anchors. Anchor-reporting tools append a stale
62
- * notice when freshness is unconfirmed; others leave staleness to then_run.
63
- */
64
- readonly reportsAnchors: boolean;
65
56
  /** Perform the mutation. Runs inside the file mutation queue. */
66
57
  run(params: TParams, target: MutationTarget): Promise<MutationOutcome<TDetails>>;
67
58
  }
@@ -85,27 +76,19 @@ export async function executeMutation<TParams extends { path: string }, TDetails
85
76
  const { then_run, ...mutationParams } = call.params;
86
77
  const absolutePath = canonicalPath(cwd, mutationParams.path);
87
78
  const target: MutationTarget = { absolutePath, displayPath: mutationParams.path, signal };
88
- let anchors = "";
89
- const mutate = (): Promise<AgentToolResult<TDetails>> =>
90
- withFileMutationQueue(absolutePath, async () => {
91
- const outcome = await spec.run(mutationParams as unknown as TParams, target);
92
- anchors = outcome.anchors ?? "";
93
- return outcome.result;
94
- });
95
- const finalizeMutation = spec.reportsAnchors
96
- ? (result: AgentToolResult<TDetails>, publishAnchors: boolean) =>
97
- appendMutationAnchors(result, anchors, publishAnchors)
98
- : undefined;
79
+ const mutate = (): Promise<MutationOutcome<TDetails>> =>
80
+ withFileMutationQueue(absolutePath, () =>
81
+ spec.run(mutationParams as unknown as TParams, target),
82
+ );
99
83
  if (!fusion) {
100
- const result = await mutate();
101
- return finalizeMutation ? finalizeMutationResult(result, finalizeMutation) : result;
84
+ const outcome = await mutate();
85
+ return finalizeMutation(outcome, commitFreshness(outcome.commit) === "unchanged");
102
86
  }
103
87
  return fusion({
104
88
  toolCallId,
105
89
  absolutePath,
106
90
  thenRun: then_run,
107
91
  mutate,
108
- finalizeMutation,
109
92
  signal,
110
93
  ctx,
111
94
  onUpdate,
@@ -164,5 +147,5 @@ export async function runTextMutation(
164
147
  details,
165
148
  };
166
149
  });
167
- return { result, anchors };
150
+ return { result, commit: versions, anchors };
168
151
  }
package/src/pi/pi.test.ts CHANGED
@@ -13,6 +13,7 @@ import { canonicalPath } from "./path.ts";
13
13
  import { join, resolve } from "node:path";
14
14
  import { pathToFileURL } from "node:url";
15
15
  import { callTool } from "./tool-call.testing.ts";
16
+ import { DEFAULT_CONFIG } from "./config.ts";
16
17
 
17
18
  test("canonicalPath resolves relative and absolute", () => {
18
19
  const cwd = resolve("/cwd");
@@ -78,24 +79,28 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
78
79
  ctx,
79
80
  },
80
81
  );
81
- const read = await callTool(makeReadOverride(dir), { path: url }, { toolCallId: "read", ctx });
82
+ const read = await callTool(
83
+ makeReadOverride(dir, DEFAULT_CONFIG),
84
+ { path: url },
85
+ { toolCallId: "read", ctx },
86
+ );
82
87
  if (read.content[0]?.type !== "text") throw new Error("Expected a text read result");
83
88
  assert.match(read.content[0].text, /before/);
84
89
  await callTool(
85
- makeReplaceTool(dir),
90
+ makeReplaceTool(dir, DEFAULT_CONFIG),
86
91
  { path: url, replacements: [{ find: "before", replace: "after" }] },
87
92
  { toolCallId: "replace", ctx },
88
93
  );
89
94
  await callTool(
90
- makeEditOverride(dir),
95
+ makeEditOverride(dir, DEFAULT_CONFIG),
91
96
  {
92
97
  path: `@${url}`,
93
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "after")}`, body: ["edited"] }],
98
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "after", 4)}`, body: ["edited"] }],
94
99
  },
95
100
  { toolCallId: "edit", ctx },
96
101
  );
97
102
  const matches = await callTool(
98
- makeGrepOverride(dir),
103
+ makeGrepOverride(dir, DEFAULT_CONFIG),
99
104
  { path: `@${url}`, pattern: "edited" },
100
105
  { toolCallId: "grep" },
101
106
  );
@@ -18,18 +18,39 @@ import {
18
18
  type ReadToolDetails,
19
19
  type ExtensionContext,
20
20
  type Theme,
21
+ type ToolDefinition,
21
22
  } from "@earendil-works/pi-coding-agent";
22
23
  import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
23
24
  import { Text } from "@earendil-works/pi-tui";
24
25
  import { scanTextLines } from "./text-stream.ts";
25
- import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
26
+ import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
26
27
  import { canonicalPath } from "./path.ts";
27
- import { parseHashline, renderToolError } from "./render.ts";
28
+ import { renderToolError } from "./render.ts";
28
29
  import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
29
30
  import { throwIfCancelled } from "./error-text.ts";
31
+ import { formatKiB } from "./budgets.ts";
32
+ import type { HashlineEditConfig } from "./config.ts";
30
33
 
31
- const MAX_LINES = 500;
32
- const MAX_BYTES = 256 * 1024;
34
+ const DEFAULT_OFFSET = 1;
35
+
36
+ type ReadDetails = ReadToolDetails & { nativeRead?: true };
37
+
38
+ /**
39
+ * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
40
+ * ` · no trailing newline`. A missing final newline is a byte-level fact the
41
+ * numbered rows cannot show, so the header, which the model never copies into an
42
+ * edit `body`, states it. READ_HEADER is the TUI's parser for this exact line.
43
+ */
44
+ function formatReadHeader(
45
+ path: string,
46
+ totalLines: number,
47
+ start: number,
48
+ finalNewline: boolean,
49
+ ): string {
50
+ const shownFrom = start > DEFAULT_OFFSET ? ` (from line ${start})` : "";
51
+ return `${path} · ${totalLines} lines${shownFrom}${finalNewline ? "" : " · no trailing newline"}`;
52
+ }
53
+ const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/;
33
54
 
34
55
  /**
35
56
  * Render the expanded read body for the TUI: color the header, strip the
@@ -47,9 +68,7 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
47
68
  // Header: "<path> · <N> lines", optionally followed by " (from line <offset>)"
48
69
  // and/or " · no trailing newline".
49
70
  let bodyStart = 0;
50
- const h = lines[0].match(
51
- /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/,
52
- );
71
+ const h = lines[0].match(READ_HEADER);
53
72
  if (h) {
54
73
  out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
55
74
  bodyStart = 1;
@@ -91,7 +110,16 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
91
110
  }
92
111
 
93
112
  /** Build the read override (a ToolDefinition fragment for registerTool). */
94
- export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolDefinition> {
113
+ export function makeReadOverride(
114
+ cwd: string,
115
+ config: HashlineEditConfig,
116
+ ): ToolDefinition<
117
+ ReturnType<typeof createReadToolDefinition>["parameters"],
118
+ ReadDetails | undefined
119
+ > {
120
+ const { hashLen } = config;
121
+ const { defaultLimit } = config.read;
122
+ const maxBytes = config.read.maxKiB * 1024;
95
123
  const builtin = createReadToolDefinition(cwd);
96
124
  const parameters = {
97
125
  ...builtin.parameters,
@@ -102,12 +130,12 @@ export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolD
102
130
  offset: {
103
131
  ...builtin.parameters.properties.offset,
104
132
  ...POSITIVE_SAFE_INTEGER,
105
- description: "1-based line to start from (default 1).",
133
+ description: `1-based line to start from (default ${DEFAULT_OFFSET}).`,
106
134
  },
107
135
  limit: {
108
136
  ...builtin.parameters.properties.limit,
109
137
  ...POSITIVE_SAFE_INTEGER,
110
- description: "Maximum lines to read (default 500).",
138
+ description: `Maximum lines to read (default ${defaultLimit}).`,
111
139
  },
112
140
  },
113
141
  };
@@ -127,10 +155,12 @@ export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolD
127
155
 
128
156
  renderCall: builtin.renderCall,
129
157
 
130
- renderResult(result, { isPartial, expanded }, theme, context) {
158
+ renderResult(result, options, theme, context) {
159
+ const { isPartial, expanded } = options;
131
160
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
132
161
  const content = result.content?.[0];
133
162
  if (context?.isError) return renderToolError(result, theme);
163
+ if (result.details?.nativeRead) return builtin.renderResult!(result, options, theme, context);
134
164
  // Collapsed (not expanded): show nothing — the call line carries the
135
165
  // title, matching the built-in read's fold behavior.
136
166
  if (!expanded) return new Text("", 0, 0);
@@ -146,21 +176,24 @@ export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolD
146
176
  ctx: ExtensionContext,
147
177
  ) {
148
178
  throwIfCancelled(signal);
149
- const offset = params.offset ?? 1;
150
- const limit = params.limit ?? MAX_LINES;
151
- const anchors = createAnchorFormatter();
179
+ const offset = params.offset ?? DEFAULT_OFFSET;
180
+ const limit = params.limit ?? defaultLimit;
181
+ const anchors = createAnchorFormatter(hashLen);
182
+ const readNative = async () => {
183
+ const result = await builtin.execute(toolCallId, params, signal, onUpdate, ctx);
184
+ return { ...result, details: { ...result.details, nativeRead: true as const } };
185
+ };
152
186
 
153
187
  const absPath = canonicalPath(cwd, params.path as string);
154
188
  try {
155
189
  if (await detectSupportedImageMimeTypeFromFile(absPath)) {
156
- return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
190
+ return readNative();
157
191
  }
158
192
  } catch {
159
- return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
193
+ return readNative();
160
194
  }
161
195
 
162
196
  const start = offset;
163
- const end = start + limit;
164
197
  const rows: string[] = [];
165
198
  const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
166
199
  let totalRows = 0;
@@ -172,7 +205,7 @@ export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolD
172
205
  try {
173
206
  stats = await scanTextLines(
174
207
  absPath,
175
- (number) => number >= start && number < end,
208
+ (number) => number >= start && number - start < limit,
176
209
  (line) => {
177
210
  const rowBytes =
178
211
  line.byteLength +
@@ -181,7 +214,7 @@ export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolD
181
214
  totalBytes += rowBytes + (totalRows++ > 0 ? 1 : 0);
182
215
  if (truncated) return;
183
216
  const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
184
- if (nextBytes > MAX_BYTES) {
217
+ if (nextBytes > maxBytes) {
185
218
  truncated = true;
186
219
  firstLineExceedsLimit = rows.length === 0;
187
220
  return;
@@ -189,21 +222,21 @@ export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolD
189
222
  rows.push(anchors.row(line.number, line.text!));
190
223
  outputBytes = nextBytes;
191
224
  },
192
- { signal, maxLineBytes: MAX_BYTES },
225
+ { signal, maxLineBytes: maxBytes },
193
226
  );
194
227
  } catch (error) {
195
228
  // Keep native filesystem diagnostics without retrying decoding or cancellation failures.
196
229
  if (!signal?.aborted && error instanceof Error && "code" in error) {
197
- return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
230
+ return readNative();
198
231
  }
199
232
  throw error;
200
233
  }
201
- if (stats.hasNul) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
234
+ if (stats.hasNul) return readNative();
202
235
  const pagination =
203
- !truncated && rows.length > 0 && end <= stats.totalLines
236
+ !truncated && rows.length > 0 && stats.totalLines - start >= limit
204
237
  ? {
205
238
  start,
206
- end: start + rows.length - 1,
239
+ end: start + (rows.length - 1),
207
240
  totalLines: stats.totalLines,
208
241
  nextOffset: start + rows.length,
209
242
  }
@@ -219,22 +252,17 @@ export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolD
219
252
  lastLinePartial: false,
220
253
  firstLineExceedsLimit,
221
254
  maxLines: totalRows,
222
- maxBytes: MAX_BYTES,
255
+ maxBytes,
223
256
  };
224
257
 
225
- const shownFrom = start > 1 ? ` (from line ${start})` : "";
226
- // A file whose last line carries no terminator is a byte-level fact that the
227
- // numbered rows cannot show; state it in the header, the one line the model
228
- // never copies into an edit `body`.
229
- const noFinalNewline = stats.finalNewline ? "" : " · no trailing newline";
230
258
  const tail = truncation.firstLineExceedsLimit
231
- ? `\n… (line ${start} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row. Reducing limit cannot split a physical line; use bash to inspect it in chunks, or replace for a known literal/regex change)`
259
+ ? `\n… (line ${start} exceeds ${formatKiB(maxBytes)}; cannot return a complete anchor row. Reducing limit cannot split a physical line; use bash to inspect it in chunks, or replace for a known literal/regex change)`
232
260
  : truncation.truncated
233
- ? `\n… (truncated at ${MAX_BYTES >> 10}KB; use offset/limit to read more)`
261
+ ? `\n… (truncated at ${formatKiB(maxBytes)}; use offset/limit to read more)`
234
262
  : pagination
235
263
  ? `\n… (showing lines ${pagination.start}-${pagination.end} of ${pagination.totalLines}; use offset ${pagination.nextOffset} to continue)`
236
264
  : "";
237
- const header = `${params.path} · ${stats.totalLines} lines${shownFrom}${noFinalNewline}\n`;
265
+ const header = `${formatReadHeader(params.path, stats.totalLines, start, stats.finalNewline)}\n`;
238
266
  const body = truncation.content;
239
267
 
240
268
  return {
@@ -4,7 +4,6 @@ import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
5
5
  import { test } from "node:test";
6
6
  import registerHashline from "../index.ts";
7
- import { getState } from "./state.ts";
8
7
  import { initTheme } from "@earendil-works/pi-coding-agent";
9
8
  import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
10
9
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
@@ -14,8 +13,6 @@ import { callTool } from "./tool-call.testing.ts";
14
13
  test("mutation cards use Fusion by default and explicit false removes command support", async () => {
15
14
  const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
16
15
  const previousCwd = process.cwd();
17
- const state = getState();
18
- const previousConfig = state.config;
19
16
  try {
20
17
  await mkdir(join(dir, ".pi"));
21
18
  await writeFile(
@@ -213,7 +210,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
213
210
  const edit = tools.find((tool) => tool.name === "edit");
214
211
  const stale = {
215
212
  path: "stale.txt",
216
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "target")}`, body: ["changed"] }],
213
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, body: ["changed"] }],
217
214
  then_run: { command: "exit 99" },
218
215
  };
219
216
  const staleCard = new ToolExecutionComponent(
@@ -283,7 +280,6 @@ test("mutation cards use Fusion by default and explicit false removes command su
283
280
  }
284
281
  } finally {
285
282
  process.chdir(previousCwd);
286
- state.config = previousConfig;
287
283
  await rm(dir, { recursive: true, force: true });
288
284
  }
289
285
  });