@criogaid/pi-hashline-edit 0.3.1 → 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 (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. 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
+ }
@@ -0,0 +1,86 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
4
+ import { formatMutationAnchors, generateMutationDetails } from "./mutation-result.ts";
5
+ import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
6
+ import { byteRevision } from "./file-commit.ts";
7
+ import { MAX_BLOCK_BYTES } from "./budgets.ts";
8
+
9
+ for (const [name, before, after] of [
10
+ ["LF", "guard\nold\ntail\n", "guard\nnew\ntail\n"],
11
+ ["CRLF", "guard\r\nold\r\ntail\r\n", "guard\r\nnew\r\ntail\r\n"],
12
+ ["mixed", "guard\r\nold\ntail", "guard\r\nnew\ntail"],
13
+ ["standalone CR", "guard\nold\rtail", "guard\nnew\rtail"],
14
+ ["ending conversion", "same\r\n", "same\n"],
15
+ ["empty file", "", "created"],
16
+ ["BOM and literal escapes", "\uFEFFguard\nold\\n\\0", "\uFEFFguard\nnew\\n\\0"],
17
+ ["no-op", "unchanged\n", "unchanged\n"],
18
+ ] as const) {
19
+ test(`mutation evidence preserves raw patch and logical preview for ${name}`, () => {
20
+ const versions = {
21
+ baseRevision: byteRevision(before),
22
+ publishedRevision: byteRevision(after),
23
+ observedRevision: byteRevision(after),
24
+ };
25
+ const publication = before === after ? "NOT_PUBLISHED" : "PUBLISHED";
26
+ const details = generateMutationDetails("file.txt", before, after, versions, publication);
27
+ const raw = generateDiffString(before, after);
28
+ const logical = generateDiffString(before.replace(/\r\n/g, "\n"), after.replace(/\r\n/g, "\n"));
29
+ assert.deepEqual(details, {
30
+ diff: displayCarriageReturns(raw.diff),
31
+ displayDiff: displayCarriageReturns(logical.diff),
32
+ firstChangedLine: raw.firstChangedLine,
33
+ patch: generateUnifiedPatch("file.txt", before, after),
34
+ publication,
35
+ ...versions,
36
+ });
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,85 +1,140 @@
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";
11
+ import { errorMessage } from "../core/errors.ts";
12
+ import { formatKiB, MAX_BLOCK_BYTES } from "./budgets.ts";
6
13
 
7
14
  /** Keep byte-faithful diff/patch data and a separate preview of the shared logical text. */
8
- export function generateMutationDetails(path: string, before: string, after: string, versions: MutationVersions, publication: PublicationStatus) {
9
- const { diff, firstChangedLine } = generateDiffString(before, after);
10
- return {
11
- diff: displayCarriageReturns(diff),
12
- displayDiff: displayCarriageReturns(generateDiffString(normalizeLineEndings(before), normalizeLineEndings(after)).diff),
13
- firstChangedLine,
14
- patch: generateUnifiedPatch(path, before, after),
15
- publication,
16
- ...versions,
17
- revision: versions.publishedRevision,
18
- };
15
+ export function generateMutationDetails(
16
+ path: string,
17
+ before: string,
18
+ after: string,
19
+ versions: MutationVersions,
20
+ publication: PublicationStatus,
21
+ ) {
22
+ const { diff, firstChangedLine } = generateDiffString(before, after);
23
+ const logicalBefore = normalizeLineEndings(before);
24
+ const logicalAfter = normalizeLineEndings(after);
25
+ const displayDiff =
26
+ logicalBefore === before && logicalAfter === after
27
+ ? diff
28
+ : generateDiffString(logicalBefore, logicalAfter).diff;
29
+ return {
30
+ diff: displayCarriageReturns(diff),
31
+ displayDiff: displayCarriageReturns(displayDiff),
32
+ firstChangedLine,
33
+ patch: generateUnifiedPatch(path, before, after),
34
+ publication,
35
+ ...versions,
36
+ };
19
37
  }
20
38
 
21
39
  /** Keep result-building failures distinct from file publication failures. */
22
- export function postProcessMutation<T>(tool: string, publication: PublicationStatus, build: () => T): T {
23
- try { return build(); } catch (error) {
24
- throw new FileMutationError("post_process", publication, `${tool} result generation failed; publication=${publication}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
25
- }
40
+ export function postProcessMutation<T>(
41
+ tool: string,
42
+ publication: PublicationStatus,
43
+ build: () => T,
44
+ ): T {
45
+ try {
46
+ return build();
47
+ } catch (error) {
48
+ throw new FileMutationError(
49
+ "post_process",
50
+ publication,
51
+ `${tool} result generation failed; publication=${publication}: ${errorMessage(error)}`,
52
+ { cause: error },
53
+ );
54
+ }
26
55
  }
27
56
 
28
- /** Append only to the summary block after the caller confirms anchor freshness. */
29
- export function appendMutationAnchors<T>(result: AgentToolResult<T>, anchors: string, publish: boolean): AgentToolResult<T> {
30
- return {
31
- ...result,
32
- content: result.content.map((block, index) => index === 0 && block.type === "text"
33
- ? { ...block, text: `${block.text}${publish ? anchors : ""}` } : block),
34
- };
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;
35
64
  }
36
65
 
37
- export function observedFreshness(result: AgentToolResult<unknown>): "unchanged" | "changed" | "unknown" {
38
- const versions = result.details as Partial<MutationVersions> | undefined;
39
- if (!versions?.publishedRevision || !versions.observedRevision) return "unknown";
40
- 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";
41
69
  }
42
70
 
43
- /** Finalize from the observed commit revision unless a later freshness check supplies the decision. */
44
- export function finalizeMutationResult<T>(
45
- result: AgentToolResult<T>,
46
- finalize: (result: AgentToolResult<T>, publishAnchors: boolean) => AgentToolResult<T>,
47
- publishAnchors = observedFreshness(result) === "unchanged",
48
- 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 = "",
49
84
  ): AgentToolResult<T> {
50
- try {
51
- const finalized = finalize(result, publishAnchors);
52
- return publishAnchors ? finalized : {
53
- ...finalized,
54
- content: [...finalized.content, { type: "text", text: staleNotice }],
55
- };
56
- } catch (error) {
57
- const publication = (result.details as { publication?: PublicationStatus } | undefined)?.publication ?? "UNKNOWN";
58
- throw new FileMutationError("post_process", publication, `Result generation failed; publication=${publication}. Re-read before retrying: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
59
- }
85
+ if (!fresh) {
86
+ return {
87
+ ...result,
88
+ content: [...result.content, { type: "text", text: staleTargetNotice(staleMarker) }],
89
+ };
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
+ };
60
98
  }
61
99
 
62
100
  /** Return compact changed-position anchors; selected context rows retain full content within the byte budget. */
63
101
  export function formatMutationAnchors(
64
- beforeLines: readonly string[], lines: readonly string[], indices: Iterable<number>, anchors: AnchorFormatter, heading: string,
65
- contentIndices?: ReadonlySet<number>,
102
+ beforeLines: readonly string[],
103
+ lines: readonly string[],
104
+ indices: Iterable<number>,
105
+ anchors: AnchorFormatter,
106
+ heading: string,
107
+ contentIndices?: ReadonlySet<number>,
66
108
  ): string {
67
- const notice = "\n… (additional anchors omitted: 16 KiB limit; use read for omitted positions)";
68
- const rows: string[] = [];
69
- let bytes = Buffer.byteLength(`\n${heading}\n`) + Buffer.byteLength(notice);
70
- let omitted = false;
71
- for (const index of indices) {
72
- const content = lines[index];
73
- // Compare source content, not short hashes: a collision must not suppress a changed row.
74
- if (beforeLines[index] === content) continue;
75
- const row = contentIndices?.has(index) ? anchors.row(index + 1, content) : anchors.token(index + 1, content);
76
- const rowBytes = Buffer.byteLength(row) + 1;
77
- if (bytes + rowBytes > 16 * 1024) {
78
- omitted = true;
79
- continue;
80
- }
81
- rows.push(row);
82
- bytes += rowBytes;
83
- }
84
- return rows.length || omitted ? `\n${heading}\n${rows.join("\n")}${omitted ? notice : ""}` : "";
109
+ const notice = `\n… (additional anchors omitted: ${formatKiB(MAX_BLOCK_BYTES)} limit; use read for omitted positions)`;
110
+ const prefix = `\n${heading}\n`;
111
+ let rows: string[] = [];
112
+ let bytes = Buffer.byteLength(prefix);
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
+ };
121
+ for (const index of indices) {
122
+ const content = lines[index];
123
+ // Compare source content, not short hashes: a collision must not suppress a changed row.
124
+ // Deletion successors (contentIndices) shifted into this position and must not be skipped.
125
+ if (beforeLines[index] === content && !contentIndices?.has(index)) continue;
126
+ const row = contentIndices?.has(index)
127
+ ? anchors.row(index + 1, content)
128
+ : anchors.token(index + 1, content);
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);
138
+ }
139
+ return rows.length || omitted ? `${prefix}${rows.join("\n")}${omitted ? notice : ""}` : "";
85
140
  }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Shared execution pipeline for the file mutation tools (edit, replace, write).
3
+ *
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.
10
+ *
11
+ * `runTextMutation` adds the read-modify-write sequence shared by edit and
12
+ * replace: snapshot bound to the bytes read, cancellation before apply and
13
+ * before write, revision-checked commit, and result generation that keeps the
14
+ * publication status on failure. Tools supply only the text transformation.
15
+ *
16
+ * @module pi-hashline-edit/pi
17
+ */
18
+
19
+ import { withFileMutationQueue, type ExtensionContext } from "@earendil-works/pi-coding-agent";
20
+ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
21
+ import type {
22
+ ActionFusionDetails,
23
+ createActionFusionExecutor,
24
+ ThenRunInput,
25
+ } from "./action-fusion.ts";
26
+ import { commitReplacement, readEditableSnapshot } from "./file-commit.ts";
27
+ import {
28
+ commitFreshness,
29
+ finalizeMutation,
30
+ generateMutationDetails,
31
+ postProcessMutation,
32
+ type MutationOutcome,
33
+ } from "./mutation-result.ts";
34
+ import { canonicalPath } from "./path.ts";
35
+ import { throwIfCancelled } from "./error-text.ts";
36
+
37
+ export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
38
+ export type MutationToolName = "edit" | "replace" | "write";
39
+
40
+ /** Result details shared by the read-modify-write tools. */
41
+ export type TextMutationDetails = ReturnType<typeof generateMutationDetails> & {
42
+ actionFusion?: ActionFusionDetails;
43
+ };
44
+
45
+ /** The file a mutation targets, resolved once per call. */
46
+ export interface MutationTarget {
47
+ readonly absolutePath: string;
48
+ /** The caller-supplied path, used in result text and diffs. */
49
+ readonly displayPath: string;
50
+ readonly signal: AbortSignal | undefined;
51
+ }
52
+
53
+ export interface MutationToolSpec<TParams extends { path: string }, TDetails> {
54
+ readonly cwd: string;
55
+ readonly fusion: ActionFusionExecutor | undefined;
56
+ /** Perform the mutation. Runs inside the file mutation queue. */
57
+ run(params: TParams, target: MutationTarget): Promise<MutationOutcome<TDetails>>;
58
+ }
59
+
60
+ export interface MutationCall<TParams, TDetails> {
61
+ readonly toolCallId: string;
62
+ /** Arguments already prepared and validated by Pi against the tool schema. */
63
+ readonly params: TParams & { then_run?: ThenRunInput };
64
+ readonly signal: AbortSignal | undefined;
65
+ readonly onUpdate: AgentToolUpdateCallback<TDetails> | undefined;
66
+ readonly ctx: ExtensionContext;
67
+ }
68
+
69
+ /** Queue and publish one validated mutation call, then run its then_run command when fused. */
70
+ export async function executeMutation<TParams extends { path: string }, TDetails>(
71
+ spec: MutationToolSpec<TParams, TDetails>,
72
+ call: MutationCall<TParams, TDetails>,
73
+ ): Promise<AgentToolResult<TDetails>> {
74
+ const { cwd, fusion } = spec;
75
+ const { toolCallId, signal, onUpdate, ctx } = call;
76
+ const { then_run, ...mutationParams } = call.params;
77
+ const absolutePath = canonicalPath(cwd, mutationParams.path);
78
+ const target: MutationTarget = { absolutePath, displayPath: mutationParams.path, signal };
79
+ const mutate = (): Promise<MutationOutcome<TDetails>> =>
80
+ withFileMutationQueue(absolutePath, () =>
81
+ spec.run(mutationParams as unknown as TParams, target),
82
+ );
83
+ if (!fusion) {
84
+ const outcome = await mutate();
85
+ return finalizeMutation(outcome, commitFreshness(outcome.commit) === "unchanged");
86
+ }
87
+ return fusion({
88
+ toolCallId,
89
+ absolutePath,
90
+ thenRun: then_run,
91
+ mutate,
92
+ signal,
93
+ ctx,
94
+ onUpdate,
95
+ });
96
+ }
97
+
98
+ /** A whole-file text transformation produced from one snapshot. */
99
+ export interface TextChange {
100
+ /** Complete replacement text; equal to the snapshot for a no-op. */
101
+ readonly text: string;
102
+ /** Fresh anchor report for the committed text. Called during result generation. */
103
+ anchors(): string;
104
+ /** First result line. Called during result generation. */
105
+ summary(): string;
106
+ }
107
+
108
+ /**
109
+ * Read-modify-write against the bytes read: the commit is rejected if the file
110
+ * changed since the snapshot, and result-generation failures keep publication.
111
+ */
112
+ export async function runTextMutation(
113
+ tool: Exclude<MutationToolName, "write">,
114
+ target: MutationTarget,
115
+ change: (currentText: string) => TextChange | Promise<TextChange>,
116
+ ): Promise<MutationOutcome<TextMutationDetails>> {
117
+ const { absolutePath, displayPath, signal } = target;
118
+
119
+ const { text: currentText, baseRevision } = await readEditableSnapshot(absolutePath, displayPath);
120
+ // Cancelled after read: don't transform; the file stays untouched.
121
+ throwIfCancelled(signal, `before apply; ${displayPath} was not changed.`);
122
+
123
+ const next = await change(currentText);
124
+
125
+ // Cancelled before write: don't touch the disk.
126
+ throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
127
+
128
+ const versions = await commitReplacement(
129
+ absolutePath,
130
+ displayPath,
131
+ next.text,
132
+ baseRevision,
133
+ signal,
134
+ );
135
+ let anchors = "";
136
+ const result = postProcessMutation(tool, versions.publication, () => {
137
+ const details = generateMutationDetails(
138
+ displayPath,
139
+ currentText,
140
+ next.text,
141
+ versions,
142
+ versions.publication,
143
+ );
144
+ anchors = next.anchors();
145
+ return {
146
+ content: [{ type: "text" as const, text: next.summary() }],
147
+ details,
148
+ };
149
+ });
150
+ return { result, commit: versions, anchors };
151
+ }
package/src/pi/path.ts CHANGED
@@ -7,16 +7,24 @@ const WINDOWS_SHELL_DRIVE = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i;
7
7
 
8
8
  /** Resolve model-supplied paths with the same input conventions as Pi's built-in file tools. */
9
9
  export function canonicalPath(cwd: string, path: string): string {
10
- let normalized = path.replace(UNICODE_SPACES, " ");
11
- if (normalized.startsWith("@")) normalized = normalized.slice(1);
12
- if (process.platform === "win32" && normalized.startsWith("/") && !normalized.startsWith("//") && !normalized.includes("\\")) {
13
- const match = WINDOWS_SHELL_DRIVE.exec(normalized);
14
- if (match) normalized = `${match[1]!.toUpperCase()}:\\${match[2]?.replaceAll("/", "\\") ?? ""}`;
15
- }
16
- if (normalized === "~") normalized = homedir();
17
- else if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\"))) {
18
- normalized = join(homedir(), normalized.slice(2));
19
- }
20
- if (normalized.startsWith("file://")) normalized = fileURLToPath(normalized);
21
- return isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);
10
+ let normalized = path.replace(UNICODE_SPACES, " ");
11
+ if (normalized.startsWith("@")) normalized = normalized.slice(1);
12
+ if (
13
+ process.platform === "win32" &&
14
+ normalized.startsWith("/") &&
15
+ !normalized.startsWith("//") &&
16
+ !normalized.includes("\\")
17
+ ) {
18
+ const match = WINDOWS_SHELL_DRIVE.exec(normalized);
19
+ if (match) normalized = `${match[1]!.toUpperCase()}:\\${match[2]?.replaceAll("/", "\\") ?? ""}`;
20
+ }
21
+ if (normalized === "~") normalized = homedir();
22
+ else if (
23
+ normalized.startsWith("~/") ||
24
+ (process.platform === "win32" && normalized.startsWith("~\\"))
25
+ ) {
26
+ normalized = join(homedir(), normalized.slice(2));
27
+ }
28
+ if (normalized.startsWith("file://")) normalized = fileURLToPath(normalized);
29
+ return isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);
22
30
  }