@criogaid/pi-hashline-edit 0.8.0 → 0.10.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 (118) hide show
  1. package/README.md +13 -10
  2. package/README.zh-CN.md +12 -9
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +118 -293
  7. package/src/core/apply.ts +63 -165
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/ranges.test.ts +16 -8
  16. package/src/core/ranges.ts +10 -6
  17. package/src/core/regex.ts +3 -4
  18. package/src/core/replace.test.ts +47 -1
  19. package/src/core/replace.ts +19 -13
  20. package/src/core/search-analysis.test.ts +24 -27
  21. package/src/core/search-analysis.ts +34 -65
  22. package/src/core/search-matrix.testing.ts +0 -2
  23. package/src/core/search.ts +1 -1
  24. package/src/core/text.test.ts +5 -5
  25. package/src/core/text.ts +5 -12
  26. package/src/core/types.ts +7 -43
  27. package/src/integration/config-registration.test.ts +2 -2
  28. package/src/integration/fusion-dispatch.test.ts +2 -5
  29. package/src/integration/grep-flags.test.ts +0 -14
  30. package/src/integration/grep-js-completeness.test.ts +34 -8
  31. package/src/integration/grep-line-candidates.test.ts +4 -8
  32. package/src/integration/grep-matrix.test.ts +3 -7
  33. package/src/integration/grep-path-matrix.test.ts +5 -5
  34. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  35. package/src/integration/grep-process-limits.test.ts +78 -0
  36. package/src/integration/grep-rg.test.ts +123 -25
  37. package/src/integration/grep-scan-budget.test.ts +2 -2
  38. package/src/integration/grep-translation.test.ts +12 -27
  39. package/src/integration/large-text.test.ts +1 -47
  40. package/src/integration/model-budget-lifecycle.test.ts +13 -3
  41. package/src/integration/mutation-file-types.testing.ts +1 -1
  42. package/src/integration/npm-package.testing.ts +1 -1
  43. package/src/integration/publication-read-changes.test.ts +125 -47
  44. package/src/integration/replace-worker-boundary.test.ts +21 -11
  45. package/src/integration/report-replay.test.ts +21 -23
  46. package/src/integration/utf8-errors.test.ts +1 -1
  47. package/src/pi/AGENTS.md +16 -16
  48. package/src/pi/action-fusion.test.ts +168 -300
  49. package/src/pi/action-fusion.ts +148 -111
  50. package/src/pi/anchor-format.test.ts +9 -9
  51. package/src/pi/anchor-format.ts +6 -8
  52. package/src/pi/argument-diagnostics.ts +52 -207
  53. package/src/pi/argument-error.ts +2 -1
  54. package/src/pi/argument-format.test.ts +20 -22
  55. package/src/pi/argument-validation.test.ts +382 -418
  56. package/src/pi/argument-validation.ts +5 -8
  57. package/src/pi/budgets.ts +5 -4
  58. package/src/pi/config.test.ts +5 -2
  59. package/src/pi/config.ts +4 -6
  60. package/src/pi/diagnostic-buffer.test.ts +12 -1
  61. package/src/pi/diagnostic-buffer.ts +1 -2
  62. package/src/pi/directory-sync.test.ts +0 -1
  63. package/src/pi/edit-tool.ts +173 -226
  64. package/src/pi/error-text.ts +4 -8
  65. package/src/pi/execute.test.ts +165 -266
  66. package/src/pi/failure-context.test.ts +144 -126
  67. package/src/pi/failure-context.ts +45 -94
  68. package/src/pi/failure-path.test.ts +168 -141
  69. package/src/pi/file-commit.test.ts +110 -53
  70. package/src/pi/file-commit.ts +90 -137
  71. package/src/pi/file-snapshot.test.ts +3 -5
  72. package/src/pi/fusion-card.test.ts +4 -1
  73. package/src/pi/fusion-card.ts +16 -24
  74. package/src/pi/grep-candidates.test.ts +2 -101
  75. package/src/pi/grep-candidates.ts +23 -69
  76. package/src/pi/grep-matrix.test.ts +2 -2
  77. package/src/pi/grep-order.test.ts +4 -4
  78. package/src/pi/grep-output.ts +62 -96
  79. package/src/pi/grep-render.ts +1 -1
  80. package/src/pi/grep-reread.ts +92 -0
  81. package/src/pi/grep-scope.ts +40 -42
  82. package/src/pi/grep-search.ts +22 -31
  83. package/src/pi/grep-tool.ts +55 -82
  84. package/src/pi/grep.test.ts +81 -46
  85. package/src/pi/model-budgets.test.ts +25 -23
  86. package/src/pi/model-budgets.ts +6 -38
  87. package/src/pi/mutation-result.test.ts +44 -35
  88. package/src/pi/mutation-result.ts +51 -20
  89. package/src/pi/mutation-runner.ts +126 -70
  90. package/src/pi/output-budgets.test.ts +38 -16
  91. package/src/pi/path.ts +1 -1
  92. package/src/pi/pi.test.ts +3 -1
  93. package/src/pi/read-tool.ts +5 -5
  94. package/src/pi/regex-worker-contract.ts +3 -13
  95. package/src/pi/regex-worker.ts +1 -10
  96. package/src/pi/registration.test.ts +82 -20
  97. package/src/pi/render.test.ts +79 -42
  98. package/src/pi/render.ts +69 -63
  99. package/src/pi/replace-regex.ts +14 -2
  100. package/src/pi/replace-tool.ts +22 -83
  101. package/src/pi/replace-worker.ts +1 -1
  102. package/src/pi/replace.test.ts +9 -5
  103. package/src/pi/report-cause.ts +3 -8
  104. package/src/pi/report-failure.testing.ts +1 -2
  105. package/src/pi/report-schema.ts +65 -81
  106. package/src/pi/report.test.ts +171 -25
  107. package/src/pi/report.ts +33 -87
  108. package/src/pi/result-safety.test.ts +177 -189
  109. package/src/pi/rg-process.test.ts +77 -63
  110. package/src/pi/rg-process.ts +48 -64
  111. package/src/pi/rg-regex.ts +40 -400
  112. package/src/pi/schema.ts +12 -0
  113. package/src/pi/text-stream.test.ts +0 -21
  114. package/src/pi/text-stream.ts +14 -21
  115. package/src/pi/write-tool.ts +33 -62
  116. package/src/pi/write.test.ts +1 -3
  117. package/src/testing/regex-translation-corpus.ts +12 -12
  118. package/src/pi/replace-worker-contract.ts +0 -10
@@ -1,46 +1,55 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { generateDiffString } from "@earendil-works/pi-coding-agent";
4
- import {
5
- commandText,
6
- finalizeMutation,
7
- generateMutationDetails,
8
- type MutationFacts,
9
- type MutationFinalDetails,
10
- type MutationOutcome,
11
- } from "./mutation-result.ts";
4
+ import { generateMutationDetails } from "./mutation-result.ts";
12
5
  import { displayCarriageReturns } from "./anchor-format.ts";
13
- import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
6
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { createActionFusionExecutor } from "./action-fusion.ts";
10
+ import { makeWriteOverride } from "./write-tool.ts";
11
+ import { makeReplaceTool } from "./replace-tool.ts";
12
+ import type { SuccessReport } from "./report-schema.ts";
13
+ import { callTool, createToolContext } from "./tool-call.testing.ts";
14
+ import { reportOf } from "./report.ts";
14
15
 
15
- // Checked by tsc; these callers must never run.
16
- function invalidMutationConstruction(
17
- replacement: MutationOutcome<object, "replace">,
18
- result: MutationFinalDetails<{ diff: string }>,
16
+ // Checked by tsc at the report and tool boundaries; these callers must never run.
17
+ function invalidMutationResults(
18
+ replacement: Extract<SuccessReport, { tool: "replace" }>,
19
+ result: Awaited<ReturnType<ReturnType<typeof makeReplaceTool>["execute"]>>,
19
20
  ) {
20
- // @ts-expect-error edit has no replacement-count fact.
21
- const editFacts: MutationFacts<"edit"> = { matches: 1 };
22
- finalizeMutation(
23
- "edit",
24
- "file.txt",
25
- // @ts-expect-error Replacement facts cannot be finalized as edit facts.
26
- replacement,
27
- { freshness: "unchanged" },
28
- undefined,
29
- DEFAULT_OUTPUT_BUDGETS,
30
- );
31
- // @ts-expect-error A failed mutation has no diff details.
32
- const diff: string = result.diff;
21
+ // @ts-expect-error Edit reports cannot carry replacement counts.
22
+ const countedEdit: Extract<SuccessReport, { tool: "edit" }> = { tool: "edit", matches: 1 };
23
+ // @ts-expect-error A replacement report cannot be used as an edit report.
24
+ const edit: Extract<SuccessReport, { tool: "edit" }> = replacement;
25
+ // @ts-expect-error A possibly failed tool result has no guaranteed diff.
26
+ const diff: string = result.details.diff;
33
27
  }
34
28
 
35
- test("command content includes images → report text joins only text blocks", () => {
36
- assert.equal(
37
- commandText([
38
- { type: "text", text: "first" },
39
- { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" },
40
- { type: "text", text: "second" },
41
- ]),
42
- "first\nsecond",
43
- );
29
+ test("command content includes images → report text joins only text blocks", async (t) => {
30
+ const dir = await mkdtemp(join(tmpdir(), "hashline-command-content-"));
31
+ try {
32
+ const path = join(dir, "file.txt");
33
+ const fusion = createActionFusionExecutor(async () => ({
34
+ status: "succeeded",
35
+ result: {
36
+ content: [
37
+ { type: "text", text: "first" },
38
+ { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" },
39
+ { type: "text", text: "second" },
40
+ ],
41
+ },
42
+ }));
43
+ const result = await callTool(
44
+ makeWriteOverride(dir, fusion),
45
+ { path, content: "saved\n", mode: "create", then_run: { command: "check" } },
46
+ { ctx: await createToolContext(dir, t) },
47
+ );
48
+ assert.equal(reportOf(result, "write")?.then_run?.output, "first\nsecond");
49
+ assert.equal(await readFile(path, "utf8"), "saved\n");
50
+ } finally {
51
+ await rm(dir, { recursive: true, force: true });
52
+ }
44
53
  });
45
54
 
46
55
  for (const [name, before, after] of [
@@ -1,6 +1,5 @@
1
1
  /**
2
- * Mutation report building: details, diffs, and post-process outcome
3
- * classification.
2
+ * Mutation report building: details, diffs, and failure classification.
4
3
  *
5
4
  * @module pi-hashline-edit/pi
6
5
  */
@@ -9,19 +8,26 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
9
8
  import { FileMutationError, type CommitResult, type FreshnessObservation } from "./file-commit.ts";
10
9
  import { generateDiffString } from "@earendil-works/pi-coding-agent";
11
10
  import { displayCarriageReturns } from "./anchor-format.ts";
11
+ import { errorMessage } from "../core/errors.ts";
12
12
  import { normalizeLineEndings } from "../core/lines.ts";
13
13
  import type {
14
+ ActionFusionProgress,
14
15
  CommandResult,
15
16
  CommandStatus,
16
17
  FailureReport,
17
18
  MutationToolName,
18
- PublicationStatus,
19
+ ReportTool,
19
20
  SuccessFacts,
20
21
  SuccessReport,
21
22
  } from "./report-schema.ts";
22
- import { causeOf, reportResult, type ReportDetails } from "./report.ts";
23
+ import {
24
+ describeFailure,
25
+ reportResult,
26
+ type FailureContext,
27
+ type ReportDetails,
28
+ } from "./report.ts";
29
+ import { causeOf } from "./report-cause.ts";
23
30
  import type { OutputBudgets } from "./budgets.ts";
24
- import type { ActionFusionProgress } from "./action-fusion.ts";
25
31
 
26
32
  /** Final success carries tool details; final failure carries only its report; neither carries progress. */
27
33
  export type MutationFinalDetails<TDetails> =
@@ -39,21 +45,6 @@ export function generateMutationDetails(before: string, after: string) {
39
45
  return { diff: displayCarriageReturns(diff) };
40
46
  }
41
47
 
42
- /** Keep result-building failures distinct from file publication failures. */
43
- export function postProcessMutation<T>(publication: PublicationStatus, build: () => T): T {
44
- try {
45
- return build();
46
- } catch (error) {
47
- throw new FileMutationError(
48
- "POST_PROCESS_FAILED",
49
- "post_process",
50
- publication,
51
- "Result generation failed.",
52
- { cause: error },
53
- );
54
- }
55
- }
56
-
57
48
  /** The facts a mutation tool states about its own outcome. */
58
49
  export type MutationFacts<TTool extends MutationToolName = MutationToolName> = {
59
50
  [T in TTool]: SuccessFacts<T> & {
@@ -86,6 +77,46 @@ export interface CommandFacts {
86
77
  readonly progressError?: unknown;
87
78
  }
88
79
 
80
+ /**
81
+ * A mutation that did not complete, so its then_run command never ran. Action
82
+ * Fusion owns the command status; the mutation's own failure stays unchanged.
83
+ */
84
+ export class CommandNotRun extends Error {
85
+ readonly status: Extract<CommandStatus, "skipped" | "cancelled">;
86
+ /** A progress observer failed; the mutation's failure is unaffected. */
87
+ readonly progressError: unknown;
88
+
89
+ constructor(
90
+ error: unknown,
91
+ status: Extract<CommandStatus, "skipped" | "cancelled">,
92
+ progressError?: unknown,
93
+ ) {
94
+ super(errorMessage(error), { cause: error });
95
+ this.name = "CommandNotRun";
96
+ this.status = status;
97
+ this.progressError = progressError;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Classify a mutation tool's failure with what only a mutation states: what it published and,
103
+ * when the call was fused, why its command never ran.
104
+ */
105
+ export function describeMutationFailure(
106
+ tool: ReportTool,
107
+ caught: unknown,
108
+ context: FailureContext,
109
+ ): FailureReport {
110
+ const command = caught instanceof CommandNotRun ? caught : undefined;
111
+ // The mutation's own failure, unchanged.
112
+ const error = command ? command.cause : caught;
113
+ return describeFailure(tool, error, context, {
114
+ publication: error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED",
115
+ then_run: command ? { status: command.status } : undefined,
116
+ progressError: causeOf(command?.progressError, context.budget.fieldBytes),
117
+ });
118
+ }
119
+
89
120
  /** Build the mutation report from commit, freshness, and command facts; the TUI uses its diff details. */
90
121
  export function finalizeMutation<TDetails extends object, TTool extends MutationToolName>(
91
122
  tool: TTool,
@@ -1,14 +1,19 @@
1
1
  /**
2
2
  * Shared execution pipeline for the file mutation tools (edit, replace, write).
3
3
  *
4
+ * `mutationToolBase` assembles the definition every mutation tool shares:
5
+ * then_run's field, description, and guideline when Action Fusion is on,
6
+ * argument preparation, strict sampling, and execution. Each tool supplies its schema, text,
7
+ * semantic checks, and `run`, and adds its own renderers.
8
+ *
4
9
  * Owns the sequencing every mutation tool must keep identical once Pi has
5
10
  * 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` (commit facts, details, outcome facts);
9
- * `finalizeMutation` alone turns it into the result, so nothing
11
+ * the shared file mutation queue, the hand-off to Action Fusion, and
12
+ * finalization. Each tool returns a typed `MutationOutcome` (commit facts,
13
+ * details, outcome facts); Action Fusion returns facts too, and this module's
14
+ * single `finalizeMutation` call turns them into the result, so nothing
10
15
  * downstream reads publication or revisions back from result details. Every
11
- * failure leaves as one report with the call's path, stage, and publication.
16
+ * failure leaves as one report with the call's path and publication.
12
17
  *
13
18
  * `runTextMutation` adds the read-modify-write sequence shared by edit and
14
19
  * replace: snapshot bound to the bytes read, cancellation before apply and
@@ -20,13 +25,27 @@
20
25
 
21
26
  import { withFileMutationQueue, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
22
27
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
23
- import type { createActionFusionExecutor, ThenRunInput } from "./action-fusion.ts";
28
+ import type { Static, TObject, TProperties } from "typebox";
29
+ import {
30
+ ACTION_FUSION_GUIDELINES,
31
+ withThenRunDescription,
32
+ withThenRunSchema,
33
+ type createActionFusionExecutor,
34
+ type FusedMutation,
35
+ type ThenRunInput,
36
+ } from "./action-fusion.ts";
37
+ import { createArgumentPreparer, type CheckArguments } from "./argument-validation.ts";
24
38
  import type { MutationToolName } from "./report-schema.ts";
25
- import { commitFreshness, commitReplacement, readEditableSnapshot } from "./file-commit.ts";
26
39
  import {
40
+ commitFile,
41
+ commitFreshness,
42
+ FileMutationError,
43
+ readEditableSnapshot,
44
+ } from "./file-commit.ts";
45
+ import {
46
+ describeMutationFailure,
27
47
  finalizeMutation,
28
48
  generateMutationDetails,
29
- postProcessMutation,
30
49
  type MutationOutcome,
31
50
  type MutationFinalDetails,
32
51
  type MutationResultDetails,
@@ -36,11 +55,12 @@ import { canonicalPath } from "./path.ts";
36
55
  import { throwIfCancelled } from "./error-text.ts";
37
56
  import { runTool } from "./report.ts";
38
57
  import type { OutputBudgetProvider, OutputBudgets } from "./budgets.ts";
58
+ import { STRICT_SAMPLING } from "./schema.ts";
39
59
 
40
60
  export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
41
61
 
42
62
  /** Result details shared by the read-modify-write tools. */
43
- export type TextMutationDetails = ReturnType<typeof generateMutationDetails>;
63
+ type TextMutationDetails = ReturnType<typeof generateMutationDetails>;
44
64
 
45
65
  /** The file a mutation targets, resolved once per call. */
46
66
  export interface MutationTarget {
@@ -49,78 +69,100 @@ export interface MutationTarget {
49
69
  readonly budget: OutputBudgets;
50
70
  }
51
71
 
52
- interface MutationToolSpec<
53
- TParams extends { path: string },
54
- TDetails,
55
- TTool extends MutationToolName,
56
- > {
72
+ /** A mutation tool's own parameters; `execute` separates then_run. */
73
+ type MutationParams<P extends TProperties> = Static<TObject<P>> & { readonly path: string };
74
+
75
+ /** What a mutation tool supplies to the shared definition; renderers stay with the tool. */
76
+ interface MutationToolSpec<P extends TProperties, TDetails, TTool extends MutationToolName> {
57
77
  readonly tool: TTool;
58
78
  readonly cwd: string;
59
79
  readonly fusion: ActionFusionExecutor | undefined;
60
80
  readonly budgets: OutputBudgetProvider;
81
+ /** Parameters without then_run, which Action Fusion adds. */
82
+ readonly schema: TObject<P>;
83
+ readonly description: string;
84
+ readonly promptSnippet: string;
85
+ readonly promptGuidelines?: readonly string[];
86
+ /** Semantic argument checks the schema cannot express. */
87
+ readonly check?: CheckArguments;
61
88
  /** Perform the mutation. Runs inside the file mutation queue. */
62
89
  run(
63
- params: Omit<TParams, "then_run">,
90
+ params: Omit<MutationParams<P>, "then_run">,
64
91
  target: MutationTarget,
65
92
  ): Promise<MutationOutcome<TDetails, TTool>>;
66
93
  }
67
94
 
68
- interface MutationCall<TParams, TDetails> {
69
- readonly toolCallId: string;
70
- /** Arguments already prepared and validated by Pi against the tool schema. */
71
- readonly params: TParams & { then_run?: ThenRunInput };
72
- readonly signal: AbortSignal | undefined;
73
- readonly onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined;
74
- readonly ctx: ExtensionToolContext;
75
- }
76
-
77
- /** Queue and publish one validated mutation call, then run its then_run command when fused. */
78
- export async function executeMutation<
79
- TParams extends { path: string },
95
+ /**
96
+ * The definition every mutation tool shares. Action Fusion adds then_run to the
97
+ * schema, description, and guidelines only when it is on; arguments are prepared
98
+ * against the parameters Pi registers; `execute` queues and publishes one
99
+ * validated call, then runs its then_run command when fused.
100
+ */
101
+ export function mutationToolBase<
102
+ P extends TProperties,
80
103
  TDetails extends object,
81
104
  TTool extends MutationToolName,
82
- >(
83
- spec: MutationToolSpec<TParams, TDetails, TTool>,
84
- call: MutationCall<TParams, TDetails>,
85
- ): Promise<AgentToolResult<MutationFinalDetails<TDetails>>> {
86
- const { cwd, fusion, tool } = spec;
87
- const { toolCallId, signal, onUpdate, ctx } = call;
88
- const { then_run, ...mutationParams } = call.params;
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(
105
+ >(spec: MutationToolSpec<P, TDetails, TTool>) {
106
+ const { tool, cwd, schema, fusion, budgets } = spec;
107
+ const actionFusion = fusion !== undefined;
108
+ const parameters = withThenRunSchema(schema, tool, actionFusion);
109
+ return {
110
+ name: tool,
111
+ label: tool,
112
+ description: withThenRunDescription(spec.description, actionFusion),
113
+ promptSnippet: spec.promptSnippet,
114
+ promptGuidelines: [
115
+ ...(spec.promptGuidelines ?? []),
116
+ ...(actionFusion ? ACTION_FUSION_GUIDELINES : []),
117
+ ],
118
+ parameters,
119
+ prepareArguments: createArgumentPreparer(tool, parameters, spec.check, budgets),
120
+ constrainedSampling: STRICT_SAMPLING,
121
+ renderShell: "default" as const,
122
+ execute(
123
+ toolCallId: string,
124
+ params: MutationParams<P> & { then_run?: ThenRunInput },
125
+ signal: AbortSignal | undefined,
126
+ onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined,
127
+ ctx: ExtensionToolContext,
128
+ ): Promise<AgentToolResult<MutationFinalDetails<TDetails>>> {
129
+ const { then_run, ...mutationParams } = params;
130
+ const displayPath = mutationParams.path;
131
+ const budget = budgets();
132
+ return runTool(
99
133
  tool,
100
- displayPath,
101
- outcome,
102
- commitFreshness(outcome.commit),
103
- undefined,
104
- budget,
134
+ { path: displayPath, signal, budget },
135
+ async () => {
136
+ const absolutePath = canonicalPath(cwd, displayPath);
137
+ const target: MutationTarget = { absolutePath, signal, budget };
138
+ const mutate = (): Promise<MutationOutcome<TDetails, TTool>> =>
139
+ withFileMutationQueue(absolutePath, () => spec.run(mutationParams, target));
140
+ const settled: FusedMutation<TDetails, TTool> = fusion
141
+ ? await fusion({
142
+ toolCallId,
143
+ absolutePath,
144
+ thenRun: then_run,
145
+ mutate,
146
+ signal,
147
+ ctx,
148
+ onUpdate,
149
+ })
150
+ : await mutate().then((outcome) => ({
151
+ outcome,
152
+ observation: commitFreshness(outcome.commit),
153
+ }));
154
+ const { outcome, observation, command, terminate } = settled;
155
+ const result = finalizeMutation(tool, displayPath, outcome, observation, command, budget);
156
+ return terminate === undefined ? result : { ...result, terminate };
157
+ },
158
+ describeMutationFailure,
105
159
  );
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
- });
119
- });
160
+ },
161
+ };
120
162
  }
121
163
 
122
164
  /** A whole-file text transformation produced from one snapshot. */
123
- export interface TextChange<TTool extends MutationToolName> {
165
+ interface TextChange<TTool extends MutationToolName> {
124
166
  /** Complete replacement text; equal to the snapshot for a no-op. */
125
167
  readonly text: string;
126
168
  /** The tool's own outcome facts, such as replace's match count. */
@@ -146,10 +188,24 @@ export async function runTextMutation<TTool extends MutationToolName>(
146
188
  // Cancelled before write: don't touch the disk.
147
189
  throwIfCancelled(signal);
148
190
 
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
- }));
191
+ const commit = await commitFile(absolutePath, next.text, {
192
+ mode: "overwrite",
193
+ baseRevision,
194
+ signal,
195
+ });
196
+ try {
197
+ return {
198
+ commit,
199
+ details: generateMutationDetails(currentText, next.text),
200
+ facts: next.facts,
201
+ };
202
+ } catch (error) {
203
+ // Keep result-building failures distinct from file publication failures.
204
+ throw new FileMutationError(
205
+ "POST_PROCESS_FAILED",
206
+ commit.publication,
207
+ "Result generation failed.",
208
+ { cause: error },
209
+ );
210
+ }
155
211
  }
@@ -7,6 +7,7 @@ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
7
7
  import { applyEdits } from "../core/apply.ts";
8
8
  import { HashlineError } from "../core/errors.ts";
9
9
  import { computeLineHash } from "../core/hash.ts";
10
+ import { openTestSession } from "../testing/session.testing.ts";
10
11
  import { createAnchorFormatter } from "./anchor-format.ts";
11
12
  import { formatArgumentError } from "./argument-error.ts";
12
13
  import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
@@ -14,9 +15,10 @@ import { DEFAULT_CONFIG } from "./config.ts";
14
15
  import { makeEditOverride } from "./edit-tool.ts";
15
16
  import { describeEditFailure } from "./failure-context.ts";
16
17
  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";
18
+ import { registerModelBudgets } from "./model-budgets.ts";
19
+ import { describeMutationFailure } from "./mutation-result.ts";
20
+ import { decodeReport, reportOf } from "./report.ts";
21
+ import { decodeWorkerReply } from "./replace-regex.ts";
20
22
  import { restoreWorkerError } from "./regex-worker-contract.ts";
21
23
  import { workerFailure } from "./report-cause.ts";
22
24
  import { callTool } from "./tool-call.testing.ts";
@@ -29,8 +31,15 @@ function wrongHash(text: string): string {
29
31
  return (hash[0] === "0" ? "1" : "0") + hash.slice(1);
30
32
  }
31
33
 
32
- test("byte budget size → uses MiB for whole MiB and KiB otherwise", () => {
34
+ test("byte budget sizes include fractional KiB → round to one decimal and preserve whole units", () => {
33
35
  for (const [bytes, expected] of [
36
+ [outputBudgetsFor(200_000).readBytes, "195.3 KiB"],
37
+ [outputBudgetsFor(200_000).blockBytes, "48.8 KiB"],
38
+ [outputBudgetsFor(200_000).fieldBytes, "12.2 KiB"],
39
+ [16 * 1024, "16 KiB"],
40
+ [50 * 1024, "50 KiB"],
41
+ [256 * 1024, "256 KiB"],
42
+ [64 * 1024 * 1024, "64 MiB"],
34
43
  [1024, "1 KiB"],
35
44
  [1023 * 1024, "1023 KiB"],
36
45
  [1024 * 1024, "1 MiB"],
@@ -70,18 +79,20 @@ test("model row allowance grows → anchor failures return complete observations
70
79
  if (applied.ok) return;
71
80
  const snapshot = { currentText: text, anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen) };
72
81
  const reports = [small, large].map((budget) => {
73
- const report = describeFailure(
82
+ const report = describeMutationFailure(
74
83
  "edit",
75
- describeEditFailure(applied.failure, snapshot, false, budget),
76
- { budget },
84
+ describeEditFailure(snapshot.currentText, applied.failures, snapshot.anchors, budget),
85
+ {
86
+ budget,
87
+ },
77
88
  );
78
89
  assert.equal(report.error, "ANCHOR_MISMATCH");
79
90
  return report;
80
91
  });
81
- assert.ok(reports[0].failures?.[0].omitted);
92
+ assert.ok(reports[0].failures?.[0].notShown);
82
93
  assert.equal(reports[0].failures?.[0].observed, undefined);
83
94
  assert.equal(reports[1].failures?.[0].observed, snapshot.anchors.row(1, text));
84
- assert.equal(reports[1].failures?.[0].omitted, undefined);
95
+ assert.equal(reports[1].failures?.[0].notShown, undefined);
85
96
  for (const report of reports) {
86
97
  assert.equal(report.publication, "NOT_PUBLISHED");
87
98
  assert.ok(report.next?.includes("intended target"));
@@ -99,6 +110,7 @@ test("model budget grows → grep payload and diagnostics use that call's allowa
99
110
  files: 1,
100
111
  },
101
112
  warnings: [warning],
113
+ searchFacts: {},
102
114
  outputMode: "content",
103
115
  matchLimitReached: false,
104
116
  effectiveLimit: 3_000,
@@ -124,7 +136,9 @@ test("worker error reaches the tool → text is bounded once using the selected
124
136
  );
125
137
  assert.ok(reply && "error" in reply);
126
138
  const error = restoreWorkerError(reply.error);
127
- const reports = [small, large].map((budget) => describeFailure("replace", error, { budget }));
139
+ const reports = [small, large].map((budget) =>
140
+ describeMutationFailure("replace", error, { budget }),
141
+ );
128
142
  assert.ok(Buffer.byteLength(reports[0].message!) <= small.fieldBytes);
129
143
  assert.ok(Buffer.byteLength(reports[0].cause!.message) <= small.fieldBytes);
130
144
  assert.equal(reports[1].message, text);
@@ -137,8 +151,16 @@ test("model switches while a mutation waits → failure uses its starting budget
137
151
  const path = join(dir, "queued.txt");
138
152
  const text = "中文🙂".repeat(800);
139
153
  await writeFile(path, text);
140
- let model = { provider: "local", id: "small", contextWindow: 65_536 };
141
- const budgets = createOutputBudgetProvider(() => model);
154
+ let budgets: ReturnType<typeof registerModelBudgets> | undefined;
155
+ const { session, model } = await openTestSession(t, {
156
+ cwd: dir,
157
+ tools: [],
158
+ configure(pi) {
159
+ budgets = registerModelBudgets(pi);
160
+ },
161
+ });
162
+ assert.ok(budgets);
163
+ await session.setModel({ ...model, id: "small", contextWindow: 65_536 });
142
164
  const entered = Promise.withResolvers<void>();
143
165
  const release = Promise.withResolvers<void>();
144
166
  const holding = withFileMutationQueue(path, async () => {
@@ -149,18 +171,18 @@ test("model switches while a mutation waits → failure uses its starting budget
149
171
  try {
150
172
  const running = callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
151
173
  path,
152
- edits: [{ op: "delete", anchor: `1#${wrongHash(text)}` }],
174
+ edits: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
153
175
  });
154
- model = { ...model, id: "large", contextWindow: 1_048_576 };
176
+ await session.setModel({ ...model, id: "large", contextWindow: 1_048_576 });
155
177
  assert.equal(budgets().readBytes, large.readBytes);
156
178
  release.resolve();
157
179
  const report = reportOf(await running, "edit");
158
- assert.ok(report?.failures?.[0].omitted);
180
+ assert.ok(report?.failures?.[0].notShown);
159
181
  assert.equal(report.failures[0].observed, undefined);
160
182
  const next = reportOf(
161
183
  await callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
162
184
  path,
163
- edits: [{ op: "delete", anchor: `1#${wrongHash(text)}` }],
185
+ edits: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
164
186
  }),
165
187
  "edit",
166
188
  );
package/src/pi/path.ts CHANGED
@@ -23,7 +23,7 @@ export function canonicalPath(cwd: string, path: string): string {
23
23
  !normalized.includes("\\")
24
24
  ) {
25
25
  const match = WINDOWS_SHELL_DRIVE.exec(normalized);
26
- if (match) normalized = `${match[1]!.toUpperCase()}:\\${match[2]?.replaceAll("/", "\\") ?? ""}`;
26
+ if (match) normalized = `${match[1].toUpperCase()}:\\${match[2]?.replaceAll("/", "\\") ?? ""}`;
27
27
  }
28
28
  if (normalized === "~") normalized = homedir();
29
29
  else if (
package/src/pi/pi.test.ts CHANGED
@@ -95,7 +95,9 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
95
95
  makeEditOverride(dir, DEFAULT_CONFIG),
96
96
  {
97
97
  path: `@${url}`,
98
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "after", 4)}`, body: ["edited"] }],
98
+ edits: [
99
+ { action: "replace", anchor: `1#${computeLineHash(1, "after", 4)}`, body: ["edited"] },
100
+ ],
99
101
  },
100
102
  { toolCallId: "edit", ctx },
101
103
  );
@@ -27,7 +27,7 @@ import { scanTextLines } from "./text-stream.ts";
27
27
  import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
28
28
  import { canonicalPath, serializePath } from "./path.ts";
29
29
  import { renderToolError, reportLines, splitReport } from "./render.ts";
30
- import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
30
+ import { POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
31
31
  import { errnoCode } from "../core/errors.ts";
32
32
  import { throwIfCancelled } from "./error-text.ts";
33
33
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
@@ -66,7 +66,6 @@ const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no traili
66
66
  */
67
67
  function renderReadBody(raw: string, path: string, theme: Theme): string {
68
68
  const lines = raw.split("\n");
69
- if (lines.length === 0) return "";
70
69
  const out: string[] = [];
71
70
 
72
71
  // Header: "<path> · <N> lines", optionally followed by " (from line <offset>)"
@@ -99,7 +98,7 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
99
98
  } else {
100
99
  rendered = detabbed.map((l) => theme.fg("toolOutput", l));
101
100
  }
102
- for (let i = 0; i < rendered.length && i < lineNos.length; i++) {
101
+ for (let i = 0; i < rendered.length; i++) {
103
102
  out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
104
103
  }
105
104
 
@@ -147,6 +146,7 @@ export function makeReadOverride(
147
146
  promptSnippet: "Read files with editable line anchors",
148
147
  parameters: parameters as typeof builtin.parameters,
149
148
  prepareArguments: createArgumentPreparer("read", parameters, undefined, budgets),
149
+ constrainedSampling: STRICT_SAMPLING,
150
150
  renderShell: "default" as const,
151
151
 
152
152
  renderCall: builtin.renderCall,
@@ -154,7 +154,7 @@ export function makeReadOverride(
154
154
  renderResult(result, options, theme, context) {
155
155
  const { isPartial, expanded } = options;
156
156
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
157
- if (context?.isError) return renderToolError(result, "read", theme, expanded);
157
+ if (context.isError) return renderToolError(result, "read", theme, expanded);
158
158
  const { content, report } = splitReport(result);
159
159
  if (result.details?.nativeRead)
160
160
  return builtin.renderResult!({ ...result, content }, options, theme, context);
@@ -164,7 +164,7 @@ export function makeReadOverride(
164
164
  const raw = content[0]?.type === "text" ? content[0].text : "";
165
165
  return new Text(
166
166
  [
167
- renderReadBody(raw, String(context?.args?.path ?? ""), theme),
167
+ renderReadBody(raw, String(context.args?.path ?? ""), theme),
168
168
  ...(report ? reportLines(report, theme) : []),
169
169
  ].join("\n"),
170
170
  0,