@criogaid/pi-hashline-edit 0.9.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 (110) hide show
  1. package/README.md +9 -10
  2. package/README.zh-CN.md +8 -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 +96 -271
  7. package/src/core/apply.ts +62 -169
  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/regex.ts +3 -4
  16. package/src/core/replace.test.ts +47 -1
  17. package/src/core/replace.ts +19 -13
  18. package/src/core/search-analysis.test.ts +24 -27
  19. package/src/core/search-analysis.ts +34 -65
  20. package/src/core/search-matrix.testing.ts +0 -2
  21. package/src/core/search.ts +1 -1
  22. package/src/core/text.test.ts +5 -5
  23. package/src/core/text.ts +5 -12
  24. package/src/core/types.ts +7 -43
  25. package/src/integration/fusion-dispatch.test.ts +2 -5
  26. package/src/integration/grep-flags.test.ts +0 -14
  27. package/src/integration/grep-js-completeness.test.ts +34 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -8
  29. package/src/integration/grep-matrix.test.ts +3 -7
  30. package/src/integration/grep-path-matrix.test.ts +5 -5
  31. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  32. package/src/integration/grep-process-limits.test.ts +78 -0
  33. package/src/integration/grep-rg.test.ts +118 -20
  34. package/src/integration/grep-scan-budget.test.ts +2 -2
  35. package/src/integration/grep-translation.test.ts +12 -27
  36. package/src/integration/large-text.test.ts +1 -47
  37. package/src/integration/model-budget-lifecycle.test.ts +2 -1
  38. package/src/integration/publication-read-changes.test.ts +123 -45
  39. package/src/integration/replace-worker-boundary.test.ts +21 -11
  40. package/src/integration/report-replay.test.ts +20 -22
  41. package/src/pi/AGENTS.md +15 -15
  42. package/src/pi/action-fusion.test.ts +164 -296
  43. package/src/pi/action-fusion.ts +148 -111
  44. package/src/pi/anchor-format.test.ts +9 -9
  45. package/src/pi/anchor-format.ts +6 -8
  46. package/src/pi/argument-diagnostics.ts +21 -25
  47. package/src/pi/argument-error.ts +2 -1
  48. package/src/pi/argument-validation.test.ts +129 -157
  49. package/src/pi/argument-validation.ts +5 -8
  50. package/src/pi/budgets.ts +5 -4
  51. package/src/pi/config.test.ts +5 -2
  52. package/src/pi/config.ts +4 -6
  53. package/src/pi/diagnostic-buffer.test.ts +12 -1
  54. package/src/pi/diagnostic-buffer.ts +1 -2
  55. package/src/pi/directory-sync.test.ts +0 -1
  56. package/src/pi/edit-tool.ts +46 -156
  57. package/src/pi/error-text.ts +4 -8
  58. package/src/pi/execute.test.ts +83 -196
  59. package/src/pi/failure-context.test.ts +144 -126
  60. package/src/pi/failure-context.ts +44 -93
  61. package/src/pi/failure-path.test.ts +168 -141
  62. package/src/pi/file-commit.test.ts +110 -53
  63. package/src/pi/file-commit.ts +90 -137
  64. package/src/pi/file-snapshot.test.ts +3 -5
  65. package/src/pi/fusion-card.test.ts +4 -1
  66. package/src/pi/fusion-card.ts +16 -24
  67. package/src/pi/grep-candidates.test.ts +2 -101
  68. package/src/pi/grep-candidates.ts +23 -69
  69. package/src/pi/grep-matrix.test.ts +2 -2
  70. package/src/pi/grep-order.test.ts +4 -4
  71. package/src/pi/grep-output.ts +62 -96
  72. package/src/pi/grep-render.ts +1 -1
  73. package/src/pi/grep-reread.ts +92 -0
  74. package/src/pi/grep-scope.ts +40 -42
  75. package/src/pi/grep-search.ts +22 -31
  76. package/src/pi/grep-tool.ts +55 -82
  77. package/src/pi/grep.test.ts +80 -45
  78. package/src/pi/model-budgets.test.ts +25 -23
  79. package/src/pi/model-budgets.ts +6 -38
  80. package/src/pi/mutation-result.test.ts +44 -35
  81. package/src/pi/mutation-result.ts +51 -20
  82. package/src/pi/mutation-runner.ts +126 -70
  83. package/src/pi/output-budgets.test.ts +36 -14
  84. package/src/pi/path.ts +1 -1
  85. package/src/pi/read-tool.ts +5 -5
  86. package/src/pi/regex-worker-contract.ts +3 -13
  87. package/src/pi/regex-worker.ts +1 -10
  88. package/src/pi/registration.test.ts +64 -36
  89. package/src/pi/render.test.ts +38 -28
  90. package/src/pi/render.ts +59 -63
  91. package/src/pi/replace-regex.ts +14 -2
  92. package/src/pi/replace-tool.ts +20 -82
  93. package/src/pi/replace-worker.ts +1 -1
  94. package/src/pi/replace.test.ts +9 -5
  95. package/src/pi/report-cause.ts +3 -8
  96. package/src/pi/report-failure.testing.ts +1 -2
  97. package/src/pi/report-schema.ts +62 -81
  98. package/src/pi/report.test.ts +171 -25
  99. package/src/pi/report.ts +33 -87
  100. package/src/pi/result-safety.test.ts +149 -176
  101. package/src/pi/rg-process.test.ts +77 -63
  102. package/src/pi/rg-process.ts +48 -64
  103. package/src/pi/rg-regex.ts +40 -400
  104. package/src/pi/schema.ts +12 -0
  105. package/src/pi/text-stream.test.ts +0 -21
  106. package/src/pi/text-stream.ts +14 -21
  107. package/src/pi/write-tool.ts +33 -62
  108. package/src/pi/write.test.ts +1 -3
  109. package/src/testing/regex-translation-corpus.ts +12 -12
  110. package/src/pi/replace-worker-contract.ts +0 -10
@@ -73,19 +73,10 @@ export async function withRegexWorker<Input, Result, Output>(
73
73
  ),
74
74
  timeoutMs,
75
75
  );
76
- try {
77
- worker.postMessage(input);
78
- } catch (error) {
79
- fail(
80
- new HashlineError("REGEX_WORKER_FAILED", "Could not send the regex request.", {
81
- cause: error,
82
- }),
83
- );
84
- }
76
+ worker.postMessage(input);
85
77
  });
86
78
  });
87
79
  try {
88
- if (signal?.aborted) abort();
89
80
  return await execute(run);
90
81
  } finally {
91
82
  clear();
@@ -1,10 +1,7 @@
1
1
  import { rejectsArgument } from "./argument-error.testing.ts";
2
2
  import { createEditTool } from "@earendil-works/pi-coding-agent";
3
- import { validateToolArguments } from "@earendil-works/pi-ai";
4
- import {
5
- makeStrictJsonSchema,
6
- resolveJsonSchemaStrictSampling,
7
- } from "@earendil-works/pi-ai/api/constrained-sampling";
3
+ import { validateToolArguments, type Tool } from "@earendil-works/pi-ai";
4
+ import { makeStrictJsonSchema } from "@earendil-works/pi-ai/api/constrained-sampling";
8
5
  import { makeEditOverride } from "./edit-tool.ts";
9
6
  import { makeReadOverride } from "./read-tool.ts";
10
7
  import { loadConfig } from "./config.ts";
@@ -16,48 +13,79 @@ import assert from "node:assert/strict";
16
13
  import { test } from "node:test";
17
14
  import registerHashline from "../index.ts";
18
15
  import { initTheme } from "@earendil-works/pi-coding-agent";
19
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
16
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
20
17
  import { ProcessTerminal, TuiMainScreen } from "@earendil-works/pi-tui";
21
18
  import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
22
19
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
23
20
  import { computeLineHash } from "../core/hash.ts";
24
21
  import { callTool } from "./tool-call.testing.ts";
25
22
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
26
- import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
23
+ import type { ActionFusionProgress } from "./report-schema.ts";
27
24
  import { reportOf } from "./report.ts";
28
25
  import { formatByteSize } from "./budgets.ts";
29
26
  import { expectToolFailure } from "./report-failure.testing.ts";
27
+ import { STRICT_SAMPLING } from "./schema.ts";
30
28
 
31
- test("edit with or without Fusion → expose parameters usable by Pi strict sampling", () => {
32
- for (const fusion of [undefined, createActionFusionExecutor()]) {
33
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG, fusion);
34
- assert.deepEqual(tool.constrainedSampling, { type: "json_schema", strict: "prefer" });
35
- assert.equal(resolveJsonSchemaStrictSampling(tool, true), true);
36
- const strict = makeStrictJsonSchema(tool.parameters);
37
- assert.partialDeepStrictEqual(strict, {
38
- type: "object",
39
- additionalProperties: false,
40
- required: fusion ? ["path", "edits", "then_run"] : ["path", "edits"],
41
- properties: {
42
- edits: {
43
- type: "array",
44
- items: {
45
- type: "object",
46
- additionalProperties: false,
47
- required: ["action", "anchor", "end", "body", "before", "after"],
48
- properties: {
49
- anchor: { anyOf: [{ type: "string" }, { type: "null" }] },
50
- end: { anyOf: [{ type: "string" }, { type: "null" }] },
51
- body: { anyOf: [{ type: "array" }, { type: "null" }] },
52
- before: { anyOf: [{ type: "string" }, { type: "null" }] },
53
- after: { anyOf: [{ type: "string" }, { type: "null" }] },
54
- },
29
+ test("registered tools with or without Fusion → request strict sampling with convertible parameters", async (t) => {
30
+ await withDir(async (dir) => {
31
+ const previousCwd = process.cwd();
32
+ try {
33
+ await mkdir(join(dir, ".pi"));
34
+ process.chdir(dir);
35
+ for (const actionFusion of [false, true]) {
36
+ await writeFile(
37
+ join(dir, ".pi", "settings.json"),
38
+ JSON.stringify({ hashlineEdit: { enabled: true, actionFusion } }),
39
+ );
40
+ const tools: Tool[] = [];
41
+ const api: Pick<ExtensionAPI, "on" | "registerEntryRenderer" | "registerTool"> = {
42
+ on() {
43
+ return () => {};
55
44
  },
56
- },
57
- ...(fusion ? { then_run: { anyOf: [{ type: "object" }, { type: "null" }] } } : {}),
58
- },
59
- });
60
- }
45
+ registerEntryRenderer() {},
46
+ registerTool(tool) {
47
+ tools.push(tool);
48
+ },
49
+ };
50
+ // This fixture only registers tools; the three hooks cover every API call at registration.
51
+ registerHashline(api as ExtensionAPI);
52
+ assert.equal(tools.length, 5);
53
+ for (const tool of tools) {
54
+ await t.test(`${tool.name}/Fusion ${actionFusion} → supports strict sampling`, () => {
55
+ assert.deepEqual(tool.constrainedSampling, STRICT_SAMPLING);
56
+ const strict = makeStrictJsonSchema(tool.parameters);
57
+ if (tool.name === "edit") {
58
+ assert.partialDeepStrictEqual(strict, {
59
+ type: "object",
60
+ additionalProperties: false,
61
+ required: actionFusion ? ["path", "edits", "then_run"] : ["path", "edits"],
62
+ properties: {
63
+ edits: {
64
+ type: "array",
65
+ items: {
66
+ type: "object",
67
+ additionalProperties: false,
68
+ required: ["action", "anchor", "end", "body"],
69
+ properties: {
70
+ anchor: { anyOf: [{ type: "string" }, { type: "null" }] },
71
+ end: { anyOf: [{ type: "string" }, { type: "null" }] },
72
+ body: { anyOf: [{ type: "array" }, { type: "null" }] },
73
+ },
74
+ },
75
+ },
76
+ ...(actionFusion
77
+ ? { then_run: { anyOf: [{ type: "object" }, { type: "null" }] } }
78
+ : {}),
79
+ },
80
+ });
81
+ }
82
+ });
83
+ }
84
+ }
85
+ } finally {
86
+ process.chdir(previousCwd);
87
+ }
88
+ });
61
89
  });
62
90
 
63
91
  test("mutation cards use Fusion by default and explicit false removes command support", async () => {
@@ -11,11 +11,11 @@ import type { TSchema } from "typebox";
11
11
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
12
12
  import { makeEditOverride } from "./edit-tool.ts";
13
13
  import { makeReplaceTool } from "./replace-tool.ts";
14
- import { renderDiffPreview, renderMutationResult, reportLines } from "./render.ts";
14
+ import { diffCardRenderers, reportLines } from "./render.ts";
15
15
  import { withMutationStatus } from "./fusion-card.ts";
16
16
  import { makeWriteOverride } from "./write-tool.ts";
17
17
  import { generateMutationDetails } from "./mutation-result.ts";
18
- import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
18
+ import { createActionFusionExecutor } from "./action-fusion.ts";
19
19
  import { DEFAULT_CONFIG } from "./config.ts";
20
20
  import { toDisplayLines } from "./grep-render.ts";
21
21
  import { parseFileHeader } from "./grep-output.ts";
@@ -25,8 +25,8 @@ import { renderToolError } from "./render.ts";
25
25
  import { formatArgumentError } from "./argument-error.ts";
26
26
  import { makeGrepOverride } from "./grep-tool.ts";
27
27
  import { openTestSession } from "../testing/session.testing.ts";
28
- import type { SuccessReport } from "./report-schema.ts";
29
- import { renderReport, type Report } from "./report.ts";
28
+ import type { ActionFusionProgress, Report, SuccessReport } from "./report-schema.ts";
29
+ import { renderReport } from "./report.ts";
30
30
  import { DEFAULT_OUTPUT_BUDGETS, MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
31
31
 
32
32
  const mutationDetails = (
@@ -46,18 +46,16 @@ test("empty logical diff → render according to confirmed publication state", (
46
46
  assert.equal(diff.diff, "");
47
47
  for (const publication of ["PUBLISHED", "NOT_PUBLISHED", undefined] as const) {
48
48
  const output = stripVTControlCharacters(
49
- renderMutationResult(
50
- {
51
- content: [],
52
- details: { ...diff, report: { tool: "edit", publication } },
53
- },
54
- { isPartial: false, expanded: true },
55
- theme,
56
- { isError: false, args: {} },
57
- "Editing…",
58
- () => "",
59
- "edit",
60
- )
49
+ diffCardRenderers("edit", "Editing…", () => "")
50
+ .renderResult(
51
+ {
52
+ content: [],
53
+ details: { ...diff, report: { tool: "edit", publication } },
54
+ },
55
+ { isPartial: false, expanded: true },
56
+ theme,
57
+ { isError: false, args: {}, state: {} },
58
+ )
61
59
  .render(100)
62
60
  .join("\n"),
63
61
  );
@@ -119,8 +117,6 @@ test("partial edit actions → refresh per-action counts", () => {
119
117
  { action: "insert_before", anchor: "7#GH", body: ["before"] },
120
118
  { action: "insert_after", anchor: "9#JK", body: ["after"] },
121
119
  { action: "prepend", body: ["first"] },
122
- { action: "copy", anchor: "1#AB", before: "3#CD" },
123
- { action: "move", anchor: "3#CD", after: "5#EF" },
124
120
  ];
125
121
  let header: ReturnType<typeof tool.renderCall> | undefined;
126
122
  const context = { state: {} } as Parameters<typeof tool.renderCall>[2];
@@ -135,12 +131,10 @@ test("partial edit actions → refresh per-action counts", () => {
135
131
  };
136
132
  assert.match(render([edits[0], {}]), /unknown ×1/);
137
133
  const mixed = render(edits);
138
- assert.match(mixed, /9 ops:/);
134
+ assert.match(mixed, /7 ops:/);
139
135
  for (const [kind, count] of [
140
136
  ["replace", 2],
141
137
  ["delete", 1],
142
- ["copy", 1],
143
- ["move", 1],
144
138
  ["insert_before", 1],
145
139
  ["insert_after", 1],
146
140
  ["append", 1],
@@ -151,7 +145,7 @@ test("partial edit actions → refresh per-action counts", () => {
151
145
  assert.doesNotMatch(mixed, /unknown/);
152
146
  const single = render([edits[0]]);
153
147
  assert.match(single, /1 op: replace ×1/);
154
- assert.doesNotMatch(single, /append|copy|delete|insert_before|insert_after|move|prepend/);
148
+ assert.doesNotMatch(single, /append|delete|insert_before|insert_after|prepend/);
155
149
  assert.match(
156
150
  render([null, { action: "rep" }, { action: "__proto__" }, { action: { toString: null } }]),
157
151
  /4 ops: unknown ×4/,
@@ -260,12 +254,20 @@ test("unfused write errors retain the native full diagnostic", () => {
260
254
  initTheme("dark");
261
255
  const tool = withMutationStatus(makeWriteOverride(process.cwd()));
262
256
  const args = { path: "a.txt", content: "new", mode: "overwrite" as const };
257
+ const diagnostic = "write failed\nimportant detail";
263
258
  const context: any = { args, state: {}, isPartial: false, isError: true, invalidate() {} };
264
259
  const card = tool.renderCall!(args, theme, context);
265
260
  tool.renderResult!(
266
261
  {
267
- content: [{ type: "text", text: "write failed\nimportant detail" }],
268
- details: {},
262
+ content: [{ type: "text", text: diagnostic }],
263
+ details: {
264
+ report: {
265
+ tool: "write",
266
+ error: "FILESYSTEM_ERROR",
267
+ publication: "NOT_PUBLISHED",
268
+ message: diagnostic,
269
+ },
270
+ },
269
271
  },
270
272
  { isPartial: false, expanded: false },
271
273
  theme,
@@ -316,7 +318,13 @@ test("diff previews retain standalone CR and literal control-picture characters"
316
318
  );
317
319
  assert.match(result.render(160).join("\n"), /␍/);
318
320
  }
319
- assert.match(renderDiffPreview("-1 old␍\n+1 new␍", true, theme), /␍/);
321
+ const preview = diffCardRenderers("edit", "Editing…", () => "").renderResult(
322
+ { content: [], details: { diff: "-1 old␍\n+1 new␍" } },
323
+ { isPartial: false, expanded: true },
324
+ theme,
325
+ { isError: false, args: {}, state: {} },
326
+ );
327
+ assert.match(preview.render(160).join("\n"), /␍/);
320
328
  });
321
329
 
322
330
  test("150,000 rows in one grep group → renders every row with shared indentation folded", () => {
@@ -393,12 +401,12 @@ test("all tools render argument issues as field diagnostics while preserving mod
393
401
  for (const tool of tools) {
394
402
  for (const fused of [false, true]) {
395
403
  const args = {
396
- path: "unused.txt",
404
+ path: tool.name === "grep" ? ["unused.txt"] : "unused.txt",
397
405
  content: "unused",
398
406
  mode: "create" as const,
399
407
  edits: [{ action: "append" as const, body: ["unused"] }],
400
408
  replacements: [{ literal: true, find: "unused", replace: "unused" }],
401
- pattern: "unused",
409
+ pattern: ["unused"],
402
410
  literal: true,
403
411
  unexpected: true,
404
412
  ...(fused ? { then_run: { command: "must-not-run" } } : {}),
@@ -426,7 +434,9 @@ test("all tools render argument issues as field diagnostics while preserving mod
426
434
  showImages: false,
427
435
  isError: true,
428
436
  };
429
- const call = tool.renderCall?.(args, theme, context);
437
+ // Pi passes unvalidated arguments to renderers after erasing their tool-specific types.
438
+ const renderCall = tool.renderCall as ToolDefinition<TSchema>["renderCall"];
439
+ const call = renderCall?.(args, theme, context);
430
440
  // Pi supplies no tool-specific details when argument validation fails.
431
441
  const renderError = tool.renderResult as NonNullable<
432
442
  ToolDefinition<TSchema, undefined>["renderResult"]
package/src/pi/render.ts CHANGED
@@ -17,9 +17,8 @@ import {
17
17
  } from "@earendil-works/pi-coding-agent";
18
18
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
19
19
  import { Text, type Component } from "@earendil-works/pi-tui";
20
- import type { ActionFusionProgress } from "./action-fusion.ts";
21
- import type { MutationToolName, ReportTool } from "./report-schema.ts";
22
- import { renderReport, reportEntries, reportOf, type Report, detailsReport } from "./report.ts";
20
+ import type { MutationToolName, Report, ReportTool } from "./report-schema.ts";
21
+ import { renderReport, reportEntries, reportOf, detailsReport } from "./report.ts";
23
22
 
24
23
  /** Max diff lines shown when a result is rendered collapsed. */
25
24
  const MAX_COLLAPSED_DIFF_LINES = 24;
@@ -30,10 +29,10 @@ const MAX_COLLAPSED_OUTPUT_LINES = 15;
30
29
  * Render a pi-format diff (`+N`/`-N`/` N` content) for the TUI, reusing pi's
31
30
  * built-in renderer: semantic diff colors plus intra-line (word-level) change
32
31
  * highlighting on single-line modifications. When not expanded, collapse to the
33
- * first 24 rendered lines with an overflow marker — truncating after rendering
32
+ * first rendered lines with an overflow marker — truncating after rendering
34
33
  * keeps `-`/`+` pairs intact so the intra-line highlight never dangles.
35
34
  */
36
- export function renderDiffPreview(diff: string, expanded: boolean, theme: Theme): string {
35
+ function renderDiffPreview(diff: string, expanded: boolean, theme: Theme): string {
37
36
  const rendered = renderDiff(diff);
38
37
  if (expanded) return rendered;
39
38
  const allLines = rendered.split("\n");
@@ -100,30 +99,17 @@ export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
100
99
  */
101
100
  function publishDiffCounts(
102
101
  diff: string | undefined,
103
- context: { state?: MutationRenderState },
102
+ context: { state: MutationRenderState },
104
103
  refreshHeader: (counts: DiffCounts) => void,
105
104
  ): void {
106
- if (!diff || !context?.state) return;
105
+ if (!diff) return;
107
106
  const counts = countDiffLines(diff);
108
- const prev: DiffCounts | undefined = context.state.diffCounts;
107
+ const prev = context.state.diffCounts;
109
108
  context.state.diffCounts = counts;
110
109
  if (!prev || prev.added !== counts.added || prev.removed !== counts.removed)
111
110
  refreshHeader(counts);
112
111
  }
113
112
 
114
- /** Reuse the call component and retain it for the result's in-place count refresh. */
115
- export function renderMutationCall<TArgs>(
116
- args: TArgs,
117
- theme: Theme,
118
- context: { lastComponent?: Component; state?: MutationRenderState },
119
- header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
120
- ): Text {
121
- const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
122
- if (context?.state) context.state.callText = text;
123
- text.setText(header(args, theme, context?.state?.diffCounts));
124
- return text;
125
- }
126
-
127
113
  /** Render a bounded preview; expanding reveals every supplied line. */
128
114
  export function renderOutputPreview(
129
115
  lines: readonly string[],
@@ -167,7 +153,10 @@ function factLines(key: string, value: unknown, theme: Theme, indent = ""): stri
167
153
  }
168
154
 
169
155
  /** Highlight field issues. */
170
- function argumentLines(report: Report, theme: Theme): string[] {
156
+ function argumentLines(
157
+ report: Extract<Report, { error: "INVALID_ARGUMENTS" }>,
158
+ theme: Theme,
159
+ ): string[] {
171
160
  const lines = [theme.fg("error", theme.bold(`Invalid arguments · ${report.tool} not executed`))];
172
161
  // Keep source omission notices ahead of the bounded collapsed preview.
173
162
  if (report.schemaLimited)
@@ -176,7 +165,7 @@ function argumentLines(report: Report, theme: Theme): string[] {
176
165
  );
177
166
  if (report.omittedIssues)
178
167
  lines.push(theme.fg("warning", `${report.omittedIssues} issues omitted from diagnostic.`));
179
- for (const { field, reason, fix } of report.issues ?? []) {
168
+ for (const { field, reason, fix } of report.issues) {
180
169
  const [first, ...rest] = reason.split("\n");
181
170
  lines.push(`${theme.fg("accent", theme.bold(field))}: ${theme.fg("error", first)}`);
182
171
  for (const line of rest) lines.push(` ${theme.fg("error", line)}`);
@@ -186,7 +175,7 @@ function argumentLines(report: Report, theme: Theme): string[] {
186
175
  }
187
176
 
188
177
  /** Fields every card shows in its own header or call line. */
189
- const ENVELOPE_FIELDS = ["error", "tool", "path", "publication", "stage", "message", "next"];
178
+ const HEADER_FIELDS = ["error", "tool", "path", "publication", "message", "next"];
190
179
 
191
180
  /**
192
181
  * The one TUI presentation of a report: for a failure, a header with the code,
@@ -207,16 +196,13 @@ export function reportLines(
207
196
  lines.push(theme.fg("error", theme.bold(`${report.error} · ${report.tool}${target}`)));
208
197
  if (report.publication !== undefined)
209
198
  lines.push(
210
- theme.fg(
211
- report.publication === "NOT_PUBLISHED" ? "dim" : "warning",
212
- `${report.publication}${report.stage === undefined ? "" : ` · ${report.stage}`}`,
213
- ),
199
+ theme.fg(report.publication === "NOT_PUBLISHED" ? "dim" : "warning", report.publication),
214
200
  );
215
201
  if (report.message !== undefined)
216
202
  for (const line of report.message.split("\n")) lines.push(theme.fg("error", line));
217
203
  }
218
204
  for (const [key, value] of reportEntries(report)) {
219
- if (ENVELOPE_FIELDS.includes(key) || shown.has(key)) continue;
205
+ if (HEADER_FIELDS.includes(key) || shown.has(key)) continue;
220
206
  for (const line of factLines(key, value, theme)) lines.push(line);
221
207
  }
222
208
  if (report.next !== undefined) lines.push(`${theme.fg("dim", "next:")} ${report.next}`);
@@ -258,41 +244,51 @@ export function renderToolError(
258
244
  }
259
245
 
260
246
  /** Facts a mutation card presents another way: the command card owns then_run. */
261
- const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
247
+ export const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
262
248
 
263
- /** Render mutation status or a diff, refreshing the call header's counts in place. */
264
- export function renderMutationResult<TArgs>(
265
- result: AgentToolResult<
266
- | {
267
- diff?: string;
268
- report?: Report;
269
- actionFusion?: Partial<Pick<ActionFusionProgress, "mutationCompleted">>;
270
- }
271
- | undefined
272
- >,
273
- { isPartial, expanded }: ToolRenderResultOptions,
274
- theme: Theme,
275
- context: { isError: boolean; args: TArgs; state?: MutationRenderState },
249
+ /** The cards of a tool that shows a diff (edit, replace); each supplies only its header and pending text. */
250
+ export function diffCardRenderers<TArgs>(
251
+ tool: MutationToolName,
276
252
  pending: string,
277
253
  header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
278
- tool: MutationToolName,
279
- ): Text {
280
- if (isPartial && result.details?.actionFusion?.mutationCompleted !== true)
281
- return new Text(theme.fg("warning", pending), 0, 0);
282
- if (context.isError) return renderToolError(result, tool, theme, expanded);
283
- const diff = result.details?.diff;
284
- // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
285
- publishDiffCounts(diff, context, (counts) => {
286
- context.state?.callText?.setText(header(context.args, theme, counts));
287
- });
288
- const { report } = splitReport(result);
289
- const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
290
- const emptyDiff =
291
- report?.publication === "NOT_PUBLISHED"
292
- ? "No net change"
293
- : report?.publication === "PUBLISHED"
294
- ? "Updated; no logical line diff"
295
- : "No diff available";
296
- const body = diff ? renderDiffPreview(diff, expanded, theme) : theme.fg("success", emptyDiff);
297
- return new Text([body, ...facts].join("\n"), 0, 0);
254
+ ) {
255
+ return {
256
+ /** Reuse the call component and retain it for the result's in-place count refresh. */
257
+ renderCall(
258
+ args: TArgs,
259
+ theme: Theme,
260
+ context: { lastComponent?: Component; state: MutationRenderState },
261
+ ) {
262
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
263
+ context.state.callText = text;
264
+ text.setText(header(args, theme, context.state.diffCounts));
265
+ return text;
266
+ },
267
+ /** Render mutation status or a diff, refreshing the call header's counts in place. */
268
+ renderResult(
269
+ result: AgentToolResult<{ diff?: string; report?: Report } | undefined>,
270
+ { isPartial, expanded }: ToolRenderResultOptions,
271
+ theme: Theme,
272
+ context: { isError: boolean; args: TArgs; state: MutationRenderState },
273
+ ) {
274
+ // withMutationStatus has already cleared isPartial once a fused mutation completed.
275
+ if (isPartial) return new Text(theme.fg("warning", pending), 0, 0);
276
+ if (context.isError) return renderToolError(result, tool, theme, expanded);
277
+ const diff = result.details?.diff;
278
+ // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
279
+ publishDiffCounts(diff, context, (counts) => {
280
+ context.state.callText?.setText(header(context.args, theme, counts));
281
+ });
282
+ const { report } = splitReport(result);
283
+ const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
284
+ const emptyDiff =
285
+ report?.publication === "NOT_PUBLISHED"
286
+ ? "No net change"
287
+ : report?.publication === "PUBLISHED"
288
+ ? "Updated; no logical line diff"
289
+ : "No diff available";
290
+ const body = diff ? renderDiffPreview(diff, expanded, theme) : theme.fg("success", emptyDiff);
291
+ return new Text([body, ...facts].join("\n"), 0, 0);
292
+ },
293
+ };
298
294
  }
@@ -1,8 +1,20 @@
1
1
  /** Run a validated replacement batch through the shared isolated regex lifecycle. */
2
- import type { Replacement, ReplacementResult } from "../core/replace-schema.ts";
3
- import { decodeWorkerReply, type ReplacementRequest } from "./replace-worker-contract.ts";
2
+ import {
3
+ REPLACEMENT_RESULT_SCHEMA,
4
+ type Replacement,
5
+ type ReplacementResult,
6
+ } from "../core/replace-schema.ts";
7
+ import { workerReplyDecoder } from "./regex-worker-contract.ts";
4
8
  import { withRegexWorker } from "./regex-worker.ts";
5
9
 
10
+ export interface ReplacementRequest {
11
+ readonly source: string;
12
+ readonly rules: readonly Replacement[];
13
+ }
14
+
15
+ /** Shared worker errors are checked by the host. */
16
+ export const decodeWorkerReply = workerReplyDecoder(REPLACEMENT_RESULT_SCHEMA);
17
+
6
18
  export function runRegexReplacements(
7
19
  source: string,
8
20
  rules: readonly Replacement[],