@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -5,8 +5,10 @@
5
5
  * prepared and validated the arguments: separating then_run, path resolution,
6
6
  * the shared file mutation queue, and the hand-off to Action Fusion or plain
7
7
  * finalization. Each tool
8
- * returns a typed `MutationOutcome` (result, commit facts, anchors); nothing
9
- * downstream reads publication or revisions back from result details.
8
+ * returns a typed `MutationOutcome` (commit facts, details, outcome facts);
9
+ * `finalizeMutation` alone turns it into the result, so nothing
10
+ * downstream reads publication or revisions back from result details. Every
11
+ * failure leaves as one report with the call's path, stage, and publication.
10
12
  *
11
13
  * `runTextMutation` adds the read-modify-write sequence shared by edit and
12
14
  * replace: snapshot bound to the bytes read, cancellation before apply and
@@ -18,138 +20,136 @@
18
20
 
19
21
  import { withFileMutationQueue, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
20
22
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
21
- import type {
22
- ActionFusionDetails,
23
- createActionFusionExecutor,
24
- MutationToolName,
25
- ThenRunInput,
26
- } from "./action-fusion.ts";
27
- import { commitReplacement, readEditableSnapshot } from "./file-commit.ts";
23
+ import type { createActionFusionExecutor, ThenRunInput } from "./action-fusion.ts";
24
+ import type { MutationToolName } from "./report-schema.ts";
25
+ import { commitFreshness, commitReplacement, readEditableSnapshot } from "./file-commit.ts";
28
26
  import {
29
- commitFreshness,
30
27
  finalizeMutation,
31
28
  generateMutationDetails,
32
29
  postProcessMutation,
33
30
  type MutationOutcome,
31
+ type MutationFinalDetails,
32
+ type MutationResultDetails,
33
+ type MutationFacts,
34
34
  } from "./mutation-result.ts";
35
35
  import { canonicalPath } from "./path.ts";
36
36
  import { throwIfCancelled } from "./error-text.ts";
37
+ import { runTool } from "./report.ts";
38
+ import type { OutputBudgetProvider, OutputBudgets } from "./budgets.ts";
37
39
 
38
40
  export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
39
41
 
40
42
  /** Result details shared by the read-modify-write tools. */
41
- export type TextMutationDetails = ReturnType<typeof generateMutationDetails> & {
42
- actionFusion?: ActionFusionDetails;
43
- };
43
+ export type TextMutationDetails = ReturnType<typeof generateMutationDetails>;
44
44
 
45
45
  /** The file a mutation targets, resolved once per call. */
46
46
  export interface MutationTarget {
47
47
  readonly absolutePath: string;
48
- /** The caller-supplied path, used in result text and diffs. */
49
- readonly displayPath: string;
50
48
  readonly signal: AbortSignal | undefined;
49
+ readonly budget: OutputBudgets;
51
50
  }
52
51
 
53
- export interface MutationToolSpec<TParams extends { path: string }, TDetails> {
52
+ interface MutationToolSpec<
53
+ TParams extends { path: string },
54
+ TDetails,
55
+ TTool extends MutationToolName,
56
+ > {
57
+ readonly tool: TTool;
54
58
  readonly cwd: string;
55
59
  readonly fusion: ActionFusionExecutor | undefined;
60
+ readonly budgets: OutputBudgetProvider;
56
61
  /** Perform the mutation. Runs inside the file mutation queue. */
57
- run(params: TParams, target: MutationTarget): Promise<MutationOutcome<TDetails>>;
62
+ run(
63
+ params: Omit<TParams, "then_run">,
64
+ target: MutationTarget,
65
+ ): Promise<MutationOutcome<TDetails, TTool>>;
58
66
  }
59
67
 
60
- export interface MutationCall<TParams, TDetails> {
68
+ interface MutationCall<TParams, TDetails> {
61
69
  readonly toolCallId: string;
62
70
  /** Arguments already prepared and validated by Pi against the tool schema. */
63
71
  readonly params: TParams & { then_run?: ThenRunInput };
64
72
  readonly signal: AbortSignal | undefined;
65
- readonly onUpdate: AgentToolUpdateCallback<TDetails> | undefined;
73
+ readonly onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined;
66
74
  readonly ctx: ExtensionToolContext;
67
75
  }
68
76
 
69
77
  /** 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>,
78
+ export async function executeMutation<
79
+ TParams extends { path: string },
80
+ TDetails extends object,
81
+ TTool extends MutationToolName,
82
+ >(
83
+ spec: MutationToolSpec<TParams, TDetails, TTool>,
72
84
  call: MutationCall<TParams, TDetails>,
73
- ): Promise<AgentToolResult<TDetails>> {
74
- const { cwd, fusion } = spec;
85
+ ): Promise<AgentToolResult<MutationFinalDetails<TDetails>>> {
86
+ const { cwd, fusion, tool } = spec;
75
87
  const { toolCallId, signal, onUpdate, ctx } = call;
76
88
  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,
89
+ const displayPath = mutationParams.path;
90
+ const budget = spec.budgets();
91
+ return runTool(tool, { path: displayPath, signal, budget }, async () => {
92
+ const absolutePath = canonicalPath(cwd, displayPath);
93
+ const target: MutationTarget = { absolutePath, signal, budget };
94
+ const mutate = (): Promise<MutationOutcome<TDetails, TTool>> =>
95
+ withFileMutationQueue(absolutePath, () => spec.run(mutationParams, target));
96
+ if (!fusion) {
97
+ const outcome = await mutate();
98
+ return finalizeMutation(
99
+ tool,
100
+ displayPath,
101
+ outcome,
102
+ commitFreshness(outcome.commit),
103
+ undefined,
104
+ budget,
105
+ );
106
+ }
107
+ return fusion({
108
+ toolCallId,
109
+ tool,
110
+ displayPath,
111
+ absolutePath,
112
+ thenRun: then_run,
113
+ budget,
114
+ mutate,
115
+ signal,
116
+ ctx,
117
+ onUpdate,
118
+ });
95
119
  });
96
120
  }
97
121
 
98
122
  /** A whole-file text transformation produced from one snapshot. */
99
- export interface TextChange {
123
+ export interface TextChange<TTool extends MutationToolName> {
100
124
  /** Complete replacement text; equal to the snapshot for a no-op. */
101
125
  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;
126
+ /** The tool's own outcome facts, such as replace's match count. */
127
+ readonly facts: MutationFacts<TTool>;
106
128
  }
107
129
 
108
130
  /**
109
131
  * Read-modify-write against the bytes read: the commit is rejected if the file
110
132
  * changed since the snapshot, and result-generation failures keep publication.
111
133
  */
112
- export async function runTextMutation(
113
- tool: Exclude<MutationToolName, "write">,
134
+ export async function runTextMutation<TTool extends MutationToolName>(
114
135
  target: MutationTarget,
115
- change: (currentText: string) => TextChange | Promise<TextChange>,
116
- ): Promise<MutationOutcome<TextMutationDetails>> {
117
- const { absolutePath, displayPath, signal } = target;
136
+ change: (currentText: string) => TextChange<TTool> | Promise<TextChange<TTool>>,
137
+ ): Promise<MutationOutcome<TextMutationDetails, TTool>> {
138
+ const { absolutePath, signal } = target;
118
139
 
119
- const { text: currentText, baseRevision } = await readEditableSnapshot(
120
- absolutePath,
121
- displayPath,
122
- signal,
123
- );
140
+ const { text: currentText, baseRevision } = await readEditableSnapshot(absolutePath, signal);
124
141
  // Cancelled after read: don't transform; the file stays untouched.
125
- throwIfCancelled(signal, `before apply; ${displayPath} was not changed.`);
142
+ throwIfCancelled(signal);
126
143
 
127
144
  const next = await change(currentText);
128
145
 
129
146
  // Cancelled before write: don't touch the disk.
130
- throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
147
+ throwIfCancelled(signal);
131
148
 
132
- const versions = await commitReplacement(
133
- absolutePath,
134
- displayPath,
135
- next.text,
136
- baseRevision,
137
- signal,
138
- );
139
- let anchors = "";
140
- const result = postProcessMutation(tool, versions.publication, () => {
141
- const details = generateMutationDetails(
142
- displayPath,
143
- currentText,
144
- next.text,
145
- versions,
146
- versions.publication,
147
- );
148
- anchors = next.anchors();
149
- return {
150
- content: [{ type: "text" as const, text: next.summary() }],
151
- details,
152
- };
153
- });
154
- return { result, commit: versions, anchors };
149
+ const commit = await commitReplacement(absolutePath, next.text, baseRevision, signal);
150
+ return postProcessMutation(commit.publication, () => ({
151
+ commit,
152
+ details: generateMutationDetails(currentText, next.text),
153
+ facts: next.facts,
154
+ }));
155
155
  }
@@ -0,0 +1,175 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
7
+ import { applyEdits } from "../core/apply.ts";
8
+ import { HashlineError } from "../core/errors.ts";
9
+ import { computeLineHash } from "../core/hash.ts";
10
+ import { createAnchorFormatter } from "./anchor-format.ts";
11
+ import { formatArgumentError } from "./argument-error.ts";
12
+ import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
13
+ import { DEFAULT_CONFIG } from "./config.ts";
14
+ import { makeEditOverride } from "./edit-tool.ts";
15
+ import { describeEditFailure } from "./failure-context.ts";
16
+ import { assembleGrepOutput } from "./grep-output.ts";
17
+ import { createOutputBudgetProvider } from "./model-budgets.ts";
18
+ import { describeFailure, decodeReport, reportOf } from "./report.ts";
19
+ import { decodeWorkerReply } from "./replace-worker-contract.ts";
20
+ import { restoreWorkerError } from "./regex-worker-contract.ts";
21
+ import { workerFailure } from "./report-cause.ts";
22
+ import { callTool } from "./tool-call.testing.ts";
23
+
24
+ const small = outputBudgetsFor(65_536);
25
+ const large = outputBudgetsFor(1_048_576);
26
+
27
+ function wrongHash(text: string): string {
28
+ const hash = computeLineHash(1, text, DEFAULT_CONFIG.hashLen);
29
+ return (hash[0] === "0" ? "1" : "0") + hash.slice(1);
30
+ }
31
+
32
+ test("byte budget size → uses MiB for whole MiB and KiB otherwise", () => {
33
+ for (const [bytes, expected] of [
34
+ [1024, "1 KiB"],
35
+ [1023 * 1024, "1023 KiB"],
36
+ [1024 * 1024, "1 MiB"],
37
+ [1025 * 1024, "1025 KiB"],
38
+ [4 * 1024 * 1024, "4 MiB"],
39
+ ] as const) {
40
+ assert.equal(formatByteSize(bytes), expected);
41
+ }
42
+ });
43
+
44
+ test("model budget grows → argument issues remain complete JSON with counted omissions", () => {
45
+ const issues = Array.from({ length: 100 }, (_, index) => ({
46
+ field: `edits[${index}].body`,
47
+ reason: "中文🙂".repeat(100),
48
+ fix: "Supply a line.",
49
+ }));
50
+ const reports = [outputBudgetsFor(1), small, large].map((budget) => {
51
+ const text = formatArgumentError(issues, false, budget);
52
+ assert.ok(Buffer.byteLength(text) <= budget.blockBytes);
53
+ const report = decodeReport(text, "edit");
54
+ assert.ok(report);
55
+ assert.equal((report.issues?.length ?? 0) + (report.omittedIssues ?? 0), issues.length);
56
+ return report;
57
+ });
58
+ assert.ok((reports[2].issues?.length ?? 0) > (reports[1].issues?.length ?? 0));
59
+ });
60
+
61
+ test("model row allowance grows → anchor failures return complete observations instead of omitted rows", () => {
62
+ const text = "中文🙂".repeat(800);
63
+ const applied = applyEdits(
64
+ text,
65
+ [{ op: "delete", anchor: { line: 1, hash: wrongHash(text) } }],
66
+ DEFAULT_CONFIG.hashLen,
67
+ 0,
68
+ );
69
+ assert.equal(applied.ok, false);
70
+ if (applied.ok) return;
71
+ const snapshot = { currentText: text, anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen) };
72
+ const reports = [small, large].map((budget) => {
73
+ const report = describeFailure(
74
+ "edit",
75
+ describeEditFailure(applied.failure, snapshot, false, budget),
76
+ { budget },
77
+ );
78
+ assert.equal(report.error, "ANCHOR_MISMATCH");
79
+ return report;
80
+ });
81
+ assert.ok(reports[0].failures?.[0].omitted);
82
+ assert.equal(reports[0].failures?.[0].observed, undefined);
83
+ assert.equal(reports[1].failures?.[0].observed, snapshot.anchors.row(1, text));
84
+ assert.equal(reports[1].failures?.[0].omitted, undefined);
85
+ for (const report of reports) {
86
+ assert.equal(report.publication, "NOT_PUBLISHED");
87
+ assert.ok(report.next?.includes("intended target"));
88
+ }
89
+ });
90
+
91
+ test("model budget grows → grep payload and diagnostics use that call's allowances", () => {
92
+ const payload = Array.from({ length: 3_000 }, () => "中文🙂".repeat(3)).join("\n");
93
+ const warning = "opening\n" + "中文🙂".repeat(800) + "\nfinal cause";
94
+ const outputs = [small, large].map((budget) =>
95
+ assembleGrepOutput({
96
+ formatted: {
97
+ blocks: [{ lines: payload.split("\n") }],
98
+ matches: 3_000,
99
+ files: 1,
100
+ },
101
+ warnings: [warning],
102
+ outputMode: "content",
103
+ matchLimitReached: false,
104
+ effectiveLimit: 3_000,
105
+ budget,
106
+ }),
107
+ );
108
+ assert.equal(outputs[0].facts.outputLimit, formatByteSize(small.grepBytes));
109
+ assert.equal(outputs[1].payload, payload);
110
+ assert.equal(outputs[1].facts.outputLimit, undefined);
111
+ assert.ok(Buffer.byteLength(outputs[0].facts.diagnostics!) <= small.fieldBytes);
112
+ assert.equal(outputs[1].facts.diagnostics, warning);
113
+ for (const output of outputs) {
114
+ assert.ok(output.facts.diagnostics?.startsWith("opening"));
115
+ assert.ok(output.facts.diagnostics?.endsWith("final cause"));
116
+ assert.ok(!output.facts.diagnostics?.includes("\uFFFD"));
117
+ }
118
+ });
119
+
120
+ test("worker error reaches the tool → text is bounded once using the selected model", () => {
121
+ const text = "中文🙂".repeat(800);
122
+ const reply = decodeWorkerReply(
123
+ workerFailure(new HashlineError("REGEX_WORKER_FAILED", text, { cause: new Error(text) })),
124
+ );
125
+ assert.ok(reply && "error" in reply);
126
+ const error = restoreWorkerError(reply.error);
127
+ const reports = [small, large].map((budget) => describeFailure("replace", error, { budget }));
128
+ assert.ok(Buffer.byteLength(reports[0].message!) <= small.fieldBytes);
129
+ assert.ok(Buffer.byteLength(reports[0].cause!.message) <= small.fieldBytes);
130
+ assert.equal(reports[1].message, text);
131
+ assert.equal(reports[1].cause?.message, text);
132
+ });
133
+
134
+ test("model switches while a mutation waits → failure uses its starting budget snapshot", async (t) => {
135
+ const dir = await mkdtemp(join(tmpdir(), "hashline-budget-"));
136
+ t.after(() => rm(dir, { recursive: true, force: true }));
137
+ const path = join(dir, "queued.txt");
138
+ const text = "中文🙂".repeat(800);
139
+ await writeFile(path, text);
140
+ let model = { provider: "local", id: "small", contextWindow: 65_536 };
141
+ const budgets = createOutputBudgetProvider(() => model);
142
+ const entered = Promise.withResolvers<void>();
143
+ const release = Promise.withResolvers<void>();
144
+ const holding = withFileMutationQueue(path, async () => {
145
+ entered.resolve();
146
+ await release.promise;
147
+ });
148
+ await entered.promise;
149
+ try {
150
+ const running = callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
151
+ path,
152
+ edits: [{ op: "delete", anchor: `1#${wrongHash(text)}` }],
153
+ });
154
+ model = { ...model, id: "large", contextWindow: 1_048_576 };
155
+ assert.equal(budgets().readBytes, large.readBytes);
156
+ release.resolve();
157
+ const report = reportOf(await running, "edit");
158
+ assert.ok(report?.failures?.[0].omitted);
159
+ assert.equal(report.failures[0].observed, undefined);
160
+ const next = reportOf(
161
+ await callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
162
+ path,
163
+ edits: [{ op: "delete", anchor: `1#${wrongHash(text)}` }],
164
+ }),
165
+ "edit",
166
+ );
167
+ assert.equal(
168
+ next?.failures?.[0].observed,
169
+ createAnchorFormatter(DEFAULT_CONFIG.hashLen).row(1, text),
170
+ );
171
+ } finally {
172
+ release.resolve();
173
+ await holding;
174
+ }
175
+ });
package/src/pi/path.ts CHANGED
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Path canonicalization and lossless re-serialization for cross-platform tool
3
+ * input.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+
1
8
  import { homedir } from "node:os";
2
9
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
10
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -34,7 +41,9 @@ export function serializePath(cwd: string, path: string): string {
34
41
  const absolute = resolve(cwd, path);
35
42
  const rel = relative(cwd, absolute);
36
43
  const local = rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
37
- const candidate = local ? (sep === "\\" ? rel.replaceAll(sep, "/") : rel) : absolute;
44
+ // Windows accepts "/" too: one separator keeps paths alike inside and outside the cwd.
45
+ const native = local ? rel : absolute;
46
+ const candidate = sep === "\\" ? native.replaceAll(sep, "/") : native;
38
47
  // A file URL preserves names whose spaces are normalized on input, and keeps headers single-line.
39
48
  if (!/[\r\n]/.test(candidate)) {
40
49
  if (canonicalPath(cwd, candidate) === absolute) return candidate;
package/src/pi/pi.test.ts CHANGED
@@ -88,7 +88,7 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
88
88
  assert.match(read.content[0].text, /before/);
89
89
  await callTool(
90
90
  makeReplaceTool(dir, DEFAULT_CONFIG),
91
- { path: url, replacements: [{ find: "before", replace: "after" }] },
91
+ { path: url, replacements: [{ literal: true, find: "before", replace: "after" }] },
92
92
  { toolCallId: "replace", ctx },
93
93
  );
94
94
  await callTool(
@@ -104,14 +104,15 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
104
104
  { path: `@${url}`, pattern: "edited", literal: true },
105
105
  { toolCallId: "grep" },
106
106
  );
107
+ assert.equal(matches.content[0].type, "text");
107
108
  assert.match(matches.content[0].text, /edited/);
108
109
  assert.equal(await readFile(file, "utf8"), "edited\n");
109
110
  let commands = 0;
110
111
  const fusion = createActionFusionExecutor(async () => {
111
112
  commands++;
112
- return { status: "succeeded", output: "checked" };
113
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
113
114
  });
114
- const fused = await callTool(
115
+ await callTool(
115
116
  makeWriteOverride(dir, fusion),
116
117
  {
117
118
  path: `@${url}`,
@@ -121,8 +122,6 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
121
122
  },
122
123
  { toolCallId: "fused", ctx },
123
124
  );
124
- assert.ok(fused.details.actionFusion);
125
- assert.equal(fused.details.actionFusion.command, "succeeded");
126
125
  assert.equal(commands, 1);
127
126
  } finally {
128
127
  await rm(dir, { recursive: true, force: true });