@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,43 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { DEFAULT_OUTPUT_BUDGETS, MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
4
+ import { createOutputBudgetProvider } from "./model-budgets.ts";
5
+
6
+ test("unchanged model → budget calculation is lazy and reuses the immutable snapshot", () => {
7
+ let reads = 0;
8
+ let model = { provider: "local", id: "small", contextWindow: 65_536 };
9
+ const get = createOutputBudgetProvider(() => {
10
+ reads++;
11
+ return model;
12
+ });
13
+ assert.equal(reads, 0);
14
+ const first = get();
15
+ assert.ok(Object.isFrozen(first));
16
+ assert.equal(get(), first);
17
+ model = { ...model };
18
+ assert.equal(get(), first);
19
+ model = { ...model, id: "large", contextWindow: 1_048_576 };
20
+ const large = get();
21
+ assert.notEqual(large, first);
22
+ assert.ok(large.readBytes > first.readBytes);
23
+ assert.ok(large.blockBytes > first.blockBytes);
24
+ assert.ok(large.fieldBytes > first.fieldBytes);
25
+ assert.ok(large.grepPreviewUnits > first.grepPreviewUnits);
26
+ assert.equal(get(), large);
27
+ assert.ok(first.readBytes < large.readBytes);
28
+ model = { ...model, contextWindow: 65_536 };
29
+ assert.equal(get().readBytes, first.readBytes);
30
+ });
31
+
32
+ test("unknown or invalid model capacity → bounded defaults are used", () => {
33
+ for (const capacity of [undefined, 0, -1, NaN, Infinity, 2.5]) {
34
+ assert.equal(outputBudgetsFor(capacity), DEFAULT_OUTPUT_BUDGETS);
35
+ }
36
+ });
37
+
38
+ test("declared capacity beyond the explicit ceiling → content budgets cap at read.maxKiB's maximum", () => {
39
+ const capped = outputBudgetsFor(MAX_CONTENT_KIB * 1024 + 1);
40
+ assert.equal(capped.readBytes, MAX_CONTENT_KIB * 1024);
41
+ assert.equal(capped.grepBytes, MAX_CONTENT_KIB * 1024);
42
+ assert.equal(capped.blockBytes, (MAX_CONTENT_KIB * 1024) / 4);
43
+ });
@@ -0,0 +1,44 @@
1
+ /** Per-extension lazy budgets. Tool preparation and execution share the same provider. */
2
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { outputBudgetsFor, type OutputBudgetProvider, type OutputBudgets } from "./budgets.ts";
4
+
5
+ type BudgetModel = Pick<
6
+ NonNullable<ExtensionContext["model"]>,
7
+ "provider" | "id" | "contextWindow"
8
+ >;
9
+
10
+ /** Reuse the snapshot until selection or its declared capacity changes. No provider request is made. */
11
+ export function createOutputBudgetProvider(
12
+ readModel: () => BudgetModel | undefined,
13
+ ): OutputBudgetProvider {
14
+ let provider: string | undefined;
15
+ let id: string | undefined;
16
+ let contextWindow: number | undefined;
17
+ let cached: OutputBudgets | undefined;
18
+ return () => {
19
+ const model = readModel();
20
+ if (
21
+ cached === undefined ||
22
+ provider !== model?.provider ||
23
+ id !== model?.id ||
24
+ !Object.is(contextWindow, model?.contextWindow)
25
+ ) {
26
+ provider = model?.provider;
27
+ id = model?.id;
28
+ contextWindow = model?.contextWindow;
29
+ cached = outputBudgetsFor(contextWindow);
30
+ }
31
+ return cached;
32
+ };
33
+ }
34
+
35
+ /** Retain Pi's live context getter, including after session restore, without calculating on events. */
36
+ export function registerModelBudgets(pi: ExtensionAPI): OutputBudgetProvider {
37
+ let context: ExtensionContext | undefined;
38
+ const bind = (_event: unknown, ctx: ExtensionContext) => {
39
+ context = ctx;
40
+ };
41
+ pi.on("session_start", bind);
42
+ pi.on("model_select", bind);
43
+ return createOutputBudgetProvider(() => context?.model);
44
+ }
@@ -3,20 +3,20 @@ import { byteRevision } from "./file-commit.ts";
3
3
  import type { MutationOutcome } from "./mutation-result.ts";
4
4
 
5
5
  /** Build a completed overwrite fixture with matching published and observed bytes. */
6
- export function publishedMutation<T>(
6
+ export function publishedMutation<T extends object | undefined>(
7
7
  content: string,
8
8
  result: AgentToolResult<T>,
9
- anchors?: string,
10
- ): MutationOutcome<T> {
9
+ ): MutationOutcome<T extends object ? T : object> {
11
10
  const revision = byteRevision(content);
12
11
  return {
13
- result,
12
+ details: (result.details ?? {}) as T extends object ? T : object,
13
+ facts: {},
14
14
  commit: {
15
15
  publication: "PUBLISHED",
16
+ baseRevision: byteRevision("before\n"),
16
17
  publishedRevision: revision,
17
18
  observedRevision: revision,
18
19
  created: false,
19
20
  },
20
- anchors,
21
21
  };
22
22
  }
@@ -1,10 +1,28 @@
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 { formatMutationAnchors, generateMutationDetails } from "./mutation-result.ts";
5
- import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
4
+ import {
5
+ finalizeMutation,
6
+ generateMutationDetails,
7
+ type MutationFacts,
8
+ type MutationFinalDetails,
9
+ type MutationOutcome,
10
+ } from "./mutation-result.ts";
11
+ import { displayCarriageReturns } from "./anchor-format.ts";
6
12
  import { byteRevision } from "./file-commit.ts";
7
- import { MAX_BLOCK_BYTES } from "./budgets.ts";
13
+
14
+ // Checked by tsc; these callers must never run.
15
+ function invalidMutationConstruction(
16
+ replacement: MutationOutcome<object, "replace">,
17
+ result: MutationFinalDetails<{ diff: string }>,
18
+ ) {
19
+ // @ts-expect-error edit has no replacement-count fact.
20
+ const editFacts: MutationFacts<"edit"> = { matches: 1 };
21
+ // @ts-expect-error Replacement facts cannot be finalized as edit facts.
22
+ finalizeMutation("edit", "file.txt", replacement, { freshness: "unchanged" });
23
+ // @ts-expect-error A failed mutation has no diff details.
24
+ const diff: string = result.diff;
25
+ }
8
26
 
9
27
  for (const [name, before, after] of [
10
28
  ["LF", "guard\nold\ntail\n", "guard\nnew\ntail\n"],
@@ -36,74 +54,3 @@ for (const [name, before, after] of [
36
54
  });
37
55
  });
38
56
  }
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
- });
87
-
88
- test("compact mutation anchors have no row cap and stop at the byte budget", () => {
89
- const anchors = createAnchorFormatter(4);
90
- for (const count of [80, 3000]) {
91
- const lines = Array.from({ length: count }, (_, index) => `changed ${index}`);
92
- const report = formatMutationAnchors([], lines, lines.keys(), anchors, "Updated anchors:");
93
- const rows = report.match(/^\d+#[0-9A-Z]+$/gm) ?? [];
94
- assert.ok(rows.length > 40);
95
- assert.doesNotMatch(report, /│/);
96
- assert.ok(Buffer.byteLength(report) <= MAX_BLOCK_BYTES);
97
- if (count === 80) {
98
- assert.equal(rows.length, count);
99
- assert.doesNotMatch(report, /omitted/);
100
- } else {
101
- assert.ok(rows.length < count);
102
- assert.match(report, /additional anchors omitted/);
103
- }
104
- assert.deepEqual(
105
- rows,
106
- lines.slice(0, rows.length).map((line, index) => anchors.token(index + 1, line)),
107
- );
108
- }
109
- });
@@ -1,15 +1,41 @@
1
+ /**
2
+ * Mutation report building: details, diffs, and post-process outcome
3
+ * classification.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+
1
8
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
9
  import {
3
10
  FileMutationError,
4
11
  type CommitResult,
12
+ type FreshnessObservation,
5
13
  type MutationVersions,
6
- type PublicationStatus,
7
14
  } from "./file-commit.ts";
8
15
  import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
9
- import { displayCarriageReturns, type AnchorFormatter } from "./anchor-format.ts";
16
+ import { displayCarriageReturns } from "./anchor-format.ts";
10
17
  import { normalizeLineEndings } from "../core/lines.ts";
11
- import { errorMessage } from "../core/errors.ts";
12
- import { formatKiB, MAX_BLOCK_BYTES } from "./budgets.ts";
18
+ import type {
19
+ CommandStatus,
20
+ FailureReport,
21
+ MutationToolName,
22
+ PublicationStatus,
23
+ SuccessFacts,
24
+ SuccessReport,
25
+ } from "./report-schema.ts";
26
+ import { causeOf, reportResult, type ReportDetails } from "./report.ts";
27
+ import { DEFAULT_OUTPUT_BUDGETS, type OutputBudgets } from "./budgets.ts";
28
+ import type { ActionFusionDetails, ActionFusionProgress } from "./action-fusion.ts";
29
+
30
+ /** Final success carries tool details; final failure carries only its report. */
31
+ export type MutationFinalDetails<TDetails> =
32
+ | (TDetails & ReportDetails<SuccessReport> & { actionFusion?: ActionFusionDetails })
33
+ | (ReportDetails<FailureReport> & { actionFusion?: never });
34
+
35
+ /** Progress can precede the mutation and carries no final report yet. */
36
+ export type MutationResultDetails<TDetails> =
37
+ | MutationFinalDetails<TDetails>
38
+ | (Partial<TDetails> & { actionFusion: ActionFusionProgress });
13
39
 
14
40
  /** Keep byte-faithful diff/patch data and a separate preview of the shared logical text. */
15
41
  export function generateMutationDetails(
@@ -37,104 +63,65 @@ export function generateMutationDetails(
37
63
  }
38
64
 
39
65
  /** Keep result-building failures distinct from file publication failures. */
40
- export function postProcessMutation<T>(
41
- tool: string,
42
- publication: PublicationStatus,
43
- build: () => T,
44
- ): T {
66
+ export function postProcessMutation<T>(publication: PublicationStatus, build: () => T): T {
45
67
  try {
46
68
  return build();
47
69
  } catch (error) {
48
70
  throw new FileMutationError(
71
+ "POST_PROCESS_FAILED",
49
72
  "post_process",
50
73
  publication,
51
- `${tool} result generation failed; publication=${publication}: ${errorMessage(error)}`,
74
+ "Result generation failed.",
52
75
  { cause: error },
53
76
  );
54
77
  }
55
78
  }
56
79
 
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>;
80
+ /** The facts a mutation tool states about its own outcome. */
81
+ export type MutationFacts<TTool extends MutationToolName = MutationToolName> = {
82
+ [T in TTool]: SuccessFacts<T> & {
83
+ [K in Exclude<"matches" | "created", keyof SuccessFacts<T>>]?: never;
84
+ };
85
+ }[TTool];
86
+
87
+ /** A published (or no-op) mutation with its commit facts, before freshness is known. */
88
+ export interface MutationOutcome<TDetails, TTool extends MutationToolName = MutationToolName> {
60
89
  /** Publication and revisions from the commit layer; later steps never read them back from details. */
61
90
  readonly commit: CommitResult;
62
- /** Fresh anchor report for the committed text; absent for tools that never report anchors. */
63
- readonly anchors?: string;
64
- }
65
-
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";
91
+ readonly details: TDetails;
92
+ readonly facts: MutationFacts<TTool>;
69
93
  }
70
94
 
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.`;
95
+ /** What Action Fusion states about the command; it never restates file state. */
96
+ export interface CommandFacts {
97
+ readonly status: CommandStatus;
98
+ readonly output?: string;
99
+ /** A progress observer failed; command and file outcomes are unaffected. */
100
+ readonly progressError?: unknown;
74
101
  }
75
102
 
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 = "",
84
- ): AgentToolResult<T> {
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
- };
98
- }
99
-
100
- /** Return compact changed-position anchors; selected context rows retain full content within the byte budget. */
101
- export function formatMutationAnchors(
102
- beforeLines: readonly string[],
103
- lines: readonly string[],
104
- indices: Iterable<number>,
105
- anchors: AnchorFormatter,
106
- heading: string,
107
- contentIndices?: ReadonlySet<number>,
108
- ): string {
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 : ""}` : "";
103
+ /** Build the mutation report from commit, freshness, and command facts; the TUI uses its diff details. */
104
+ export function finalizeMutation<TDetails extends object, TTool extends MutationToolName>(
105
+ tool: TTool,
106
+ path: string,
107
+ { commit, details, facts }: MutationOutcome<TDetails, NoInfer<TTool>>,
108
+ observation: FreshnessObservation,
109
+ command?: CommandFacts,
110
+ budget: OutputBudgets = DEFAULT_OUTPUT_BUDGETS,
111
+ ): AgentToolResult<TDetails & ReportDetails<SuccessReport>> {
112
+ const fresh = observation.freshness === "unchanged";
113
+ // Tool-indexed facts preserve the correlation that object spread loses.
114
+ const report = {
115
+ tool,
116
+ path,
117
+ publication: commit.publication,
118
+ ...facts,
119
+ freshness: fresh ? undefined : observation.freshness,
120
+ freshnessError: causeOf(observation.error, budget.fieldBytes),
121
+ then_run: command
122
+ ? { status: command.status, ...(command.output ? { output: command.output } : {}) }
123
+ : undefined,
124
+ progressError: causeOf(command?.progressError, budget.fieldBytes),
125
+ } as SuccessReport;
126
+ return reportResult(report, [], details);
140
127
  }
@@ -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,43 +20,51 @@
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 { defaultOutputBudgets, type OutputBudgetProvider, type 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. */
48
+ /** The caller-supplied path, used in reports and diffs. */
49
49
  readonly displayPath: string;
50
50
  readonly signal: AbortSignal | undefined;
51
+ readonly budget: OutputBudgets;
51
52
  }
52
53
 
53
- export interface MutationToolSpec<TParams extends { path: string }, TDetails> {
54
+ export interface MutationToolSpec<
55
+ TParams extends { path: string },
56
+ TDetails,
57
+ TTool extends MutationToolName,
58
+ > {
59
+ readonly tool: TTool;
54
60
  readonly cwd: string;
55
61
  readonly fusion: ActionFusionExecutor | undefined;
62
+ readonly budgets?: OutputBudgetProvider;
56
63
  /** Perform the mutation. Runs inside the file mutation queue. */
57
- run(params: TParams, target: MutationTarget): Promise<MutationOutcome<TDetails>>;
64
+ run(
65
+ params: Omit<TParams, "then_run">,
66
+ target: MutationTarget,
67
+ ): Promise<MutationOutcome<TDetails, TTool>>;
58
68
  }
59
69
 
60
70
  export interface MutationCall<TParams, TDetails> {
@@ -62,94 +72,92 @@ export interface MutationCall<TParams, TDetails> {
62
72
  /** Arguments already prepared and validated by Pi against the tool schema. */
63
73
  readonly params: TParams & { then_run?: ThenRunInput };
64
74
  readonly signal: AbortSignal | undefined;
65
- readonly onUpdate: AgentToolUpdateCallback<TDetails> | undefined;
75
+ readonly onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined;
66
76
  readonly ctx: ExtensionToolContext;
67
77
  }
68
78
 
69
79
  /** 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>,
80
+ export async function executeMutation<
81
+ TParams extends { path: string },
82
+ TDetails extends object,
83
+ TTool extends MutationToolName,
84
+ >(
85
+ spec: MutationToolSpec<TParams, TDetails, TTool>,
72
86
  call: MutationCall<TParams, TDetails>,
73
- ): Promise<AgentToolResult<TDetails>> {
74
- const { cwd, fusion } = spec;
87
+ ): Promise<AgentToolResult<MutationFinalDetails<TDetails>>> {
88
+ const { cwd, fusion, tool } = spec;
75
89
  const { toolCallId, signal, onUpdate, ctx } = call;
76
90
  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,
91
+ const displayPath = mutationParams.path;
92
+ const budget = (spec.budgets ?? defaultOutputBudgets)();
93
+ return runTool(tool, { path: displayPath, mutation: true, signal, budget }, async () => {
94
+ const absolutePath = canonicalPath(cwd, displayPath);
95
+ const target: MutationTarget = { absolutePath, displayPath, signal, budget };
96
+ const mutate = (): Promise<MutationOutcome<TDetails, TTool>> =>
97
+ withFileMutationQueue(absolutePath, () => spec.run(mutationParams, target));
98
+ if (!fusion) {
99
+ const outcome = await mutate();
100
+ return finalizeMutation(
101
+ tool,
102
+ displayPath,
103
+ outcome,
104
+ commitFreshness(outcome.commit),
105
+ undefined,
106
+ budget,
107
+ );
108
+ }
109
+ return fusion({
110
+ toolCallId,
111
+ tool,
112
+ displayPath,
113
+ absolutePath,
114
+ thenRun: then_run,
115
+ budget,
116
+ mutate,
117
+ signal,
118
+ ctx,
119
+ onUpdate,
120
+ });
95
121
  });
96
122
  }
97
123
 
98
124
  /** A whole-file text transformation produced from one snapshot. */
99
- export interface TextChange {
125
+ export interface TextChange<TTool extends MutationToolName> {
100
126
  /** Complete replacement text; equal to the snapshot for a no-op. */
101
127
  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;
128
+ /** The tool's own outcome facts, such as replace's match count. */
129
+ readonly facts: MutationFacts<TTool>;
106
130
  }
107
131
 
108
132
  /**
109
133
  * Read-modify-write against the bytes read: the commit is rejected if the file
110
134
  * changed since the snapshot, and result-generation failures keep publication.
111
135
  */
112
- export async function runTextMutation(
113
- tool: Exclude<MutationToolName, "write">,
136
+ export async function runTextMutation<TTool extends MutationToolName>(
114
137
  target: MutationTarget,
115
- change: (currentText: string) => TextChange | Promise<TextChange>,
116
- ): Promise<MutationOutcome<TextMutationDetails>> {
138
+ change: (currentText: string) => TextChange<TTool> | Promise<TextChange<TTool>>,
139
+ ): Promise<MutationOutcome<TextMutationDetails, TTool>> {
117
140
  const { absolutePath, displayPath, signal } = target;
118
141
 
119
- const { text: currentText, baseRevision } = await readEditableSnapshot(
120
- absolutePath,
121
- displayPath,
122
- signal,
123
- );
142
+ const { text: currentText, baseRevision } = await readEditableSnapshot(absolutePath, signal);
124
143
  // Cancelled after read: don't transform; the file stays untouched.
125
- throwIfCancelled(signal, `before apply; ${displayPath} was not changed.`);
144
+ throwIfCancelled(signal);
126
145
 
127
146
  const next = await change(currentText);
128
147
 
129
148
  // Cancelled before write: don't touch the disk.
130
- throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
149
+ throwIfCancelled(signal);
131
150
 
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(
151
+ const commit = await commitReplacement(absolutePath, next.text, baseRevision, signal);
152
+ return postProcessMutation(commit.publication, () => ({
153
+ commit,
154
+ details: generateMutationDetails(
142
155
  displayPath,
143
156
  currentText,
144
157
  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 };
158
+ commit,
159
+ commit.publication,
160
+ ),
161
+ facts: next.facts,
162
+ }));
155
163
  }