@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,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[],
@@ -24,50 +24,28 @@
24
24
  * @module pi-hashline-edit/pi
25
25
  */
26
26
 
27
- import {
28
- type ExtensionToolContext,
29
- type Theme,
30
- type ToolDefinition,
31
- type ToolRenderResultOptions,
32
- } from "@earendil-works/pi-coding-agent";
33
- import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
27
+ import type { Theme } from "@earendil-works/pi-coding-agent";
34
28
  import { Type, type Static } from "typebox";
35
29
  import { applyReplacements } from "../core/replace.ts";
36
30
  import { checkRegexArguments } from "../core/regex.ts";
37
31
  import { REPLACEMENTS_SCHEMA } from "../core/replace-schema.ts";
38
32
  import { runRegexReplacements } from "./replace-regex.ts";
39
33
  import { unwritableTextError } from "../core/text.ts";
40
- import {
41
- ACTION_FUSION_GUIDELINES,
42
- withThenRunDescription,
43
- withThenRunSchema,
44
- type ThenRunInput,
45
- } from "./action-fusion.ts";
46
34
  import type { HashlineEditConfig } from "./config.ts";
47
35
  import {
36
+ diffCardRenderers,
48
37
  formatDiffCounts,
49
- renderMutationCall,
50
- renderMutationResult,
38
+ formatHeaderPath,
51
39
  type DiffCounts,
52
40
  } from "./render.ts";
53
41
  import {
54
- executeMutation,
42
+ mutationToolBase,
55
43
  runTextMutation,
56
44
  type ActionFusionExecutor,
57
45
  type MutationTarget,
58
- type TextMutationDetails,
59
46
  } from "./mutation-runner.ts";
60
- import type { MutationResultDetails } from "./mutation-result.ts";
61
47
  import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
62
- import {
63
- argumentItems,
64
- createArgumentPreparer,
65
- type ReportArgumentIssue,
66
- } from "./argument-validation.ts";
67
- type ReplaceDetails = MutationResultDetails<TextMutationDetails>;
68
- type ReplaceRenderContext = Parameters<
69
- NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
70
- >[2];
48
+ import { argumentItems, type ReportArgumentIssue } from "./argument-validation.ts";
71
49
 
72
50
  const replaceSchema = Type.Object(
73
51
  {
@@ -80,12 +58,12 @@ const replaceSchema = Type.Object(
80
58
  { additionalProperties: false },
81
59
  );
82
60
 
83
- type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
61
+ type ReplaceParams = Static<typeof replaceSchema>;
84
62
 
85
63
  /** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
86
64
  function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
87
65
  let t = theme.fg("toolTitle", theme.bold("replace "));
88
- t += theme.fg("accent", args.path);
66
+ t += formatHeaderPath(args.path, theme);
89
67
  const count = args.replacements?.length ?? 0;
90
68
  t += theme.fg("dim", ` — ${count} rule${count === 1 ? "" : "s"}`);
91
69
  if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
@@ -97,10 +75,10 @@ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void
97
75
  const rules = argumentItems((args as { replacements?: unknown } | null)?.replacements);
98
76
  rules.forEach((rule, index) => {
99
77
  const { find, replace, literal, flags } = (rule ?? {}) as Record<string, unknown>;
78
+ const item = `replacements[${index}]`;
100
79
  const unwritable = typeof replace === "string" ? unwritableTextError(replace) : undefined;
101
- if (unwritable) report(`replacements[${index}].replace`, unwritable.message);
80
+ if (unwritable) report(`${item}.replace`, unwritable.message);
102
81
  if (flags !== undefined && typeof flags !== "string") return;
103
- const item = `replacements[${index}]`;
104
82
  checkRegexArguments(
105
83
  `${item}.flags`,
106
84
  flags,
@@ -117,59 +95,20 @@ export function makeReplaceTool(
117
95
  fusion?: ActionFusionExecutor,
118
96
  budgets: OutputBudgetProvider = defaultOutputBudgets,
119
97
  ) {
120
- const parameters = withThenRunSchema(replaceSchema, "replace", fusion !== undefined);
121
98
  return {
122
- name: "replace" as const,
123
- label: "replace",
124
- description: withThenRunDescription(
125
- "Replace every match of one or more literal or JavaScript-regex rules in a file. Rules swap only their matched fragments in one call, without line anchors. Use edit instead for inserting, deleting, or rewriting whole lines. Overlapping matches or a rule with no match reject the whole call.",
126
- fusion !== undefined,
127
- ),
128
- promptSnippet: "Replace matching text across a file",
129
- promptGuidelines: [...(fusion ? ACTION_FUSION_GUIDELINES : [])],
130
- parameters,
131
- prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments, budgets),
132
- renderShell: "default" as const,
133
-
134
- renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
135
- return renderMutationCall(args, theme, context, replaceHeader);
136
- },
137
-
138
- renderResult(
139
- result: Parameters<typeof renderMutationResult>[0],
140
- options: ToolRenderResultOptions,
141
- theme: Theme,
142
- context: ReplaceRenderContext,
143
- ) {
144
- return renderMutationResult(
145
- result,
146
- options,
147
- theme,
148
- context,
149
- "Replacing…",
150
- replaceHeader,
151
- "replace",
152
- );
153
- },
154
-
155
- async execute(
156
- toolCallId: string,
157
- params: ReplaceParams,
158
- signal: AbortSignal | undefined,
159
- onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
160
- ctx: ExtensionToolContext,
161
- ) {
162
- return executeMutation<ReplaceParams, TextMutationDetails, "replace">(
163
- {
164
- tool: "replace",
165
- cwd,
166
- fusion,
167
- budgets,
168
- run: (mutationParams, target) => runReplace(target, mutationParams.replacements, config),
169
- },
170
- { toolCallId, params, signal, onUpdate, ctx },
171
- );
172
- },
99
+ ...mutationToolBase({
100
+ tool: "replace",
101
+ cwd,
102
+ fusion,
103
+ budgets,
104
+ schema: replaceSchema,
105
+ description:
106
+ "Replace every match of one or more literal or JavaScript-regex rules in a file. Rules swap only their matched fragments in one call, without line anchors. Use edit instead for inserting, deleting, or rewriting whole lines. Overlapping matches or a rule with no match reject the whole call.",
107
+ promptSnippet: "Replace matching text across a file",
108
+ check: checkReplaceArguments,
109
+ run: (params, target) => runReplace(target, params.replacements, config),
110
+ }),
111
+ ...diffCardRenderers("replace", "Replacing…", replaceHeader),
173
112
  };
174
113
  }
175
114
 
@@ -1,6 +1,6 @@
1
1
  import { parentPort } from "node:worker_threads";
2
2
  import { applyReplacements } from "../core/replace.ts";
3
- import type { ReplacementRequest } from "./replace-worker-contract.ts";
3
+ import type { ReplacementRequest } from "./replace-regex.ts";
4
4
  // report-cause.ts only: the worker runs on plain jiti without the host's typebox mapping.
5
5
  import { workerFailure } from "./report-cause.ts";
6
6
 
@@ -107,8 +107,6 @@ test("replace rejects unwritable text and invalid regex before reading a missing
107
107
  withDir(async (dir) => {
108
108
  const file = join(dir, "missing.txt");
109
109
  const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
110
- const valid = { path: file, replacements: [{ find: "x", replace: "y", literal: false }] };
111
- assert.equal(tool.prepareArguments(valid), valid);
112
110
  for (const [rule, expected] of [
113
111
  [
114
112
  { literal: true, find: "x", replace: "\0" },
@@ -224,6 +222,9 @@ test("mixed literal and regex batches share raw offsets after CRLF normalization
224
222
  });
225
223
  assert.equal(failed.isError, true);
226
224
  assert.equal(reportOf(failed, "replace")?.error, "OVERLAPPING_MATCHES");
225
+ assert.deepEqual(reportOf(failed, "replace")?.conflict, ["replacements[0]", "replacements[1]"]);
226
+ assert.equal(reportOf(failed, "replace")?.line, 2);
227
+ assert.ok(reportOf(failed, "replace")?.next);
227
228
  assert.equal(await readFile(file, "utf8"), before);
228
229
  }));
229
230
 
@@ -342,7 +343,8 @@ test("replace finds no matches → returns failure and leaves file untouched", a
342
343
  });
343
344
  assert.equal(failed.isError, true);
344
345
  assert.equal(reportOf(failed, "replace")?.error, "NO_MATCH");
345
- assert.equal(reportOf(failed, "replace")?.rule, 0);
346
+ assert.deepEqual(reportOf(failed, "replace")?.unmatched, ["replacements[0]"]);
347
+ assert.equal(reportOf(failed, "replace")?.publication, "NOT_PUBLISHED");
346
348
  assert.equal(await readFile(f, "utf-8"), "a\nb\n", "file untouched on 0-match failure");
347
349
  });
348
350
  });
@@ -385,7 +387,9 @@ test("replace header retains the rule count when a long path wraps", () => {
385
387
  { literal: true, find: "third", replace: "fourth" },
386
388
  ],
387
389
  };
388
- const header = tool.renderCall(args, stubTheme, {} as Parameters<typeof tool.renderCall>[2]);
390
+ const header = tool.renderCall(args, stubTheme, {
391
+ state: {},
392
+ } as Parameters<typeof tool.renderCall>[2]);
389
393
  assert.match(header.render(120).join("\n"), /2 rules/);
390
394
  assert.match(header.render(80).join("\n"), /2\s+rules/);
391
395
  });
@@ -575,7 +579,7 @@ test("successful batches run one command against the complete result", async ()
575
579
  const tool = makeReplaceTool(
576
580
  dir,
577
581
  DEFAULT_CONFIG,
578
- createActionFusionExecutor(async (_toolCallId, input) => {
582
+ createActionFusionExecutor(async (input) => {
579
583
  assert.equal(input.command, "check");
580
584
  commands++;
581
585
  assert.equal(await readFile(file, "utf8"), "bar baz");
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Cause transport shared by reports and the replacement worker, without Pi runtime imports.
3
- * The worker loads this module on plain jiti, which lacks the host's typebox
2
+ * Cause transport shared by reports and the regex workers, without Pi runtime imports.
3
+ * Workers load this module on plain jiti, which lacks the host's typebox
4
4
  * mapping, so it must not import typebox at runtime.
5
5
  * External boundaries validate cause data before restoreCause.
6
6
  */
@@ -39,9 +39,9 @@ function boundedCause(data: Cause, maxBytes: number): Cause {
39
39
  ...data,
40
40
  message: boundedText(data.message, maxBytes),
41
41
  ...(data.cause ? { cause: boundedCause(data.cause, maxBytes) } : {}),
42
- ...(data.errors ? { errors: data.errors.map((inner) => boundedCause(inner, maxBytes)) } : {}),
43
42
  };
44
43
  }
44
+
45
45
  /**
46
46
  * A failure a regex worker transports: its code ties the facts that code requires.
47
47
  * The host still validates every reply (regex-worker-contract.ts) before trusting it.
@@ -89,15 +89,10 @@ export function causeOf(
89
89
  if (error instanceof RestoredCause) return boundedCause(error.data, maxBytes);
90
90
  const errno = errnoCode(error);
91
91
  const nested = error instanceof Error ? causeOf(error.cause, maxBytes, seen) : undefined;
92
- const errors =
93
- error instanceof AggregateError
94
- ? error.errors.flatMap((inner: unknown) => causeOf(inner, maxBytes, seen) ?? [])
95
- : [];
96
92
  return {
97
93
  ...(error instanceof HashlineError ? { error: error.errorCode } : {}),
98
94
  ...(errno === undefined ? {} : { code: errno }),
99
95
  message: boundedText(errorMessage(error), maxBytes),
100
96
  ...(nested ? { cause: nested } : {}),
101
- ...(errors.length ? { errors } : {}),
102
97
  };
103
98
  }
@@ -1,7 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
- import type { ErrorCode } from "../core/errors.ts";
4
- import type { Report } from "./report-schema.ts";
3
+ import type { ErrorCode, Report } from "./report-schema.ts";
5
4
  import { detailsReport } from "./report.ts";
6
5
 
7
6
  /** Assert execution failures through the returned model/TUI report, without changing tool semantics. */
@@ -6,11 +6,11 @@
6
6
  * One report describes every result of every tool, success or failure. A
7
7
  * failure report is the entire result; a success report follows the tool's
8
8
  * content payload (read rows, grep rows). Each field has one
9
- * owning layer (README "Reports"), so no fact can be stated twice. report.ts
9
+ * owning layer, so no fact can be stated twice. report.ts
10
10
  * omits the call's tool and path from result text; render.ts uses the full report for the TUI.
11
11
  *
12
12
  * Types derive from these schemas. src/core imports only types from this module,
13
- * so engines stay independent of Pi. The worker loads TypeBox at its data boundary.
13
+ * so engines stay independent of Pi. Workers do not load TypeBox; the host validates their replies.
14
14
  *
15
15
  * @module pi-hashline-edit/pi
16
16
  */
@@ -25,11 +25,10 @@ export const CAUSE_SCHEMA = Type.Cyclic(
25
25
  {
26
26
  Cause: Type.Object(
27
27
  {
28
- error: Type.Optional(Type.String({ description: "Error code of a classified cause." })),
29
- code: Type.Optional(Type.String({ description: "Node errno code, such as EACCES." })),
28
+ error: opt(Type.String({ description: "Error code of a classified cause." })),
29
+ code: opt(Type.String({ description: "Node errno code, such as EACCES." })),
30
30
  message: Type.String(),
31
- cause: Type.Optional(Type.Ref("Cause")),
32
- errors: Type.Optional(Type.Array(Type.Ref("Cause"))),
31
+ cause: opt(Type.Ref("Cause")),
33
32
  },
34
33
  { additionalProperties: false },
35
34
  ),
@@ -45,13 +44,6 @@ const PUBLICATION_SCHEMA = Type.Union([
45
44
  ]);
46
45
  export type PublicationStatus = Static<typeof PUBLICATION_SCHEMA>;
47
46
 
48
- const STAGE_SCHEMA = Type.Union([
49
- Type.Literal("prepare"),
50
- Type.Literal("commit"),
51
- Type.Literal("post_process"),
52
- ]);
53
- export type MutationStage = Static<typeof STAGE_SCHEMA>;
54
-
55
47
  const FRESHNESS_SCHEMA = Type.Union([
56
48
  Type.Literal("unchanged"),
57
49
  Type.Literal("changed"),
@@ -121,20 +113,19 @@ export type ActionFusionProgress = Static<typeof ACTION_FUSION_PROGRESS_SCHEMA>;
121
113
  const ANCHOR_FAILURE_SCHEMA = Type.Object(
122
114
  {
123
115
  field: Type.String(),
124
- op: Type.String(),
116
+ action: Type.String(),
125
117
  cited: Type.String(),
126
118
  result: Type.Union([
127
119
  Type.Literal("shifted"),
128
120
  Type.Literal("ambiguous"),
129
121
  Type.Literal("unresolved"),
130
122
  ]),
131
- search: opt(Type.Union([Type.Literal("local window"), Type.Literal("full file")])),
132
123
  candidate: opt(Type.String()),
133
124
  content: opt(Type.String()),
134
125
  candidates: opt(Type.Array(Type.String())),
135
126
  omittedCandidates: opt(Type.Integer({ minimum: 1 })),
136
127
  observed: opt(Type.String()),
137
- omitted: opt(
128
+ notShown: opt(
138
129
  Type.String({ description: "Why content (shifted) or observed (unresolved) is absent." }),
139
130
  ),
140
131
  },
@@ -167,13 +158,12 @@ const FACT_FIELDS = {
167
158
  schemaLimited: Type.Literal(true, {
168
159
  description: "A native diagnostic allowance was reached; more issues may exist.",
169
160
  }),
170
- // A missing path among several (grep).
171
- missing: Type.String(),
161
+ missing: Type.Array(Type.String(), {
162
+ description: "Resolved paths that do not exist; shows where a relative path led.",
163
+ }),
172
164
  // Anchor verification (failure-context.ts).
173
165
  failures: Type.Array(ANCHOR_FAILURE_SCHEMA),
174
166
  omittedFailures: count("Failures omitted from the byte budget."),
175
- matched: Type.Array(Type.String()),
176
- omittedMatched: count("Matched anchors omitted from the byte budget."),
177
167
  candidateNeighborhoods: Type.Array(
178
168
  Type.Object(
179
169
  { lines: Type.String(), rows: Type.Array(Type.String()) },
@@ -181,10 +171,14 @@ const FACT_FIELDS = {
181
171
  ),
182
172
  ),
183
173
  omittedNeighborhoodRows: count("Neighborhood rows omitted from the byte budget."),
184
- // Replacement rules (core/replace.ts, replace-regex.ts).
185
- rule: Type.Integer({ minimum: 0 }),
186
- rules: Type.Array(Type.Integer({ minimum: 0 })),
187
- offset: Type.Integer({ minimum: 0 }),
174
+ // Overlap (core/apply.ts, core/replace.ts).
175
+ conflict: Type.Array(Type.String(), {
176
+ description: "The first conflicting pair of inputs found; more conflicts may exist.",
177
+ }),
178
+ // Replacement rules (core/replace.ts).
179
+ unmatched: Type.Array(Type.String(), { description: "Rules that match nothing." }),
180
+ line: Type.Integer({ minimum: 1, description: "Line where the conflicting match starts." }),
181
+ // Regex workers (regex-worker.ts).
188
182
  timeoutMs: Type.Integer({ minimum: 1 }),
189
183
  exitCode: Type.Union([Type.Integer(), Type.Null()]),
190
184
  // read outcome; `outputLimit` below is shared with grep.
@@ -204,7 +198,7 @@ const FACT_FIELDS = {
204
198
  // grep outcome; `matches` is also replace's match count.
205
199
  matches: Type.Integer({ minimum: 0 }),
206
200
  files: Type.Integer({ minimum: 0 }),
207
- candidates: Type.Union([Type.Literal("files"), Type.Literal("all")], {
201
+ scanned: Type.Union([Type.Literal("files"), Type.Literal("all")], {
208
202
  description:
209
203
  "Without line candidates, the files searched whole: those containing text every match needs, or every file in scope.",
210
204
  }),
@@ -244,7 +238,7 @@ function facts<const R extends readonly FactName[], const O extends readonly Fac
244
238
  ) {
245
239
  const properties: TProperties = {};
246
240
  for (const name of required) properties[name] = FACT_FIELDS[name];
247
- for (const name of optional ?? []) properties[name] = Type.Optional(FACT_FIELDS[name]);
241
+ for (const name of optional ?? []) properties[name] = opt(FACT_FIELDS[name]);
248
242
  // A single mapped property set preserves required keys in TypeBox's static inference.
249
243
  return Type.Object(
250
244
  properties as {
@@ -256,7 +250,6 @@ function facts<const R extends readonly FactName[], const O extends readonly Fac
256
250
  );
257
251
  }
258
252
  const NONE = facts([]);
259
- const MATCHED = ["matched", "omittedMatched"] as const;
260
253
 
261
254
  /**
262
255
  * Each error code: its facts and its recovery. `next.default` is the code's
@@ -264,9 +257,7 @@ const MATCHED = ["matched", "omittedMatched"] as const;
264
257
  * Once a mutation reached or may have reached the file, PUBLICATION_NEXT replaces them.
265
258
  */
266
259
  export const ERROR_DEFINITIONS = {
267
- INVALID_ARGUMENTS: {
268
- facts: facts(["issues"], ["omittedIssues", "schemaLimited"]),
269
- },
260
+ INVALID_ARGUMENTS: { facts: facts(["issues"], ["omittedIssues", "schemaLimited"]) },
270
261
  OPERATION_ABORTED: { facts: NONE },
271
262
  PATH_NOT_FOUND: {
272
263
  facts: facts([], ["missing"]),
@@ -283,42 +274,39 @@ export const ERROR_DEFINITIONS = {
283
274
  },
284
275
  UNSUPPORTED_ENCODING: { facts: NONE },
285
276
  UNSUPPORTED_TEXT: { facts: NONE },
286
- INVALID_UNICODE: {
287
- facts: NONE,
288
- },
277
+ INVALID_UNICODE: { facts: NONE },
289
278
  ANCHOR_MISMATCH: {
290
279
  facts: facts(
291
280
  ["failures"],
292
- ["omittedFailures", ...MATCHED, "candidateNeighborhoods", "omittedNeighborhoodRows"],
281
+ ["omittedFailures", "candidateNeighborhoods", "omittedNeighborhoodRows"],
293
282
  ),
294
283
  next: {
295
284
  default:
296
- "Before reusing a candidate or observed anchor, confirm it is the intended target; use read or grep for omitted rows, out-of-range lines, or more context. Retries verify every anchor again.",
285
+ "Confirm a candidate or observed anchor is the intended target before reusing it; otherwise use read or grep.",
297
286
  },
298
287
  },
299
- INVALID_RANGE: {
300
- facts: facts([], MATCHED),
301
- },
302
288
  OVERLAPPING_EDITS: {
303
- facts: facts([], MATCHED),
304
- next: { default: "Merge overlapping edits into one edit per range." },
289
+ facts: facts(["conflict"]),
290
+ next: {
291
+ default: "Merge them into one edit per range or position.",
292
+ },
305
293
  },
306
294
  NO_MATCH: {
307
- facts: facts(["rule"]),
295
+ facts: facts(["unmatched"]),
308
296
  next: {
309
297
  default:
310
298
  "Verify the target text with read or grep; check case sensitivity or regex flags if applicable.",
311
299
  },
312
300
  },
313
301
  OVERLAPPING_MATCHES: {
314
- facts: facts(["rules", "offset"]),
315
- },
316
- REGEX_TIMEOUT: {
317
- facts: facts(["timeoutMs"]),
318
- },
319
- REGEX_WORKER_FAILED: {
320
- facts: facts([], ["exitCode"]),
302
+ facts: facts(["conflict", "line"]),
303
+ next: {
304
+ default:
305
+ "Change the conflicting rules so their matches do not overlap, or merge them into one rule.",
306
+ },
321
307
  },
308
+ REGEX_TIMEOUT: { facts: facts(["timeoutMs"]) },
309
+ REGEX_WORKER_FAILED: { facts: facts([], ["exitCode"]) },
322
310
  TARGET_EXISTS: {
323
311
  facts: NONE,
324
312
  next: {
@@ -326,24 +314,17 @@ export const ERROR_DEFINITIONS = {
326
314
  'Check the path and read the existing file. Use mode "overwrite" only if replacing that file is intended.',
327
315
  },
328
316
  },
329
- NOT_REGULAR_FILE: { facts: NONE },
330
- MULTIPLE_HARD_LINKS: { facts: NONE },
331
- SYMLINK_UNRESOLVED: { facts: NONE },
332
- PUBLISH_FAILED: {
333
- facts: NONE,
334
- },
335
- POST_PROCESS_FAILED: {
336
- facts: NONE,
337
- },
338
- SEARCH_INCOMPLETE: {
339
- facts: facts(["diagnostics"], ["candidates", "scanLimit"]),
340
- },
341
- RIPGREP_FAILED: {
342
- facts: facts([], ["exitCode"]),
343
- },
344
- UNSUPPORTED_PATH: {
317
+ NOT_REGULAR_FILE: {
345
318
  facts: NONE,
319
+ next: { default: "Use the path of a regular file." },
346
320
  },
321
+ MULTIPLE_HARD_LINKS: { facts: NONE },
322
+ SYMLINK_UNRESOLVED: { facts: NONE },
323
+ PUBLISH_FAILED: { facts: NONE },
324
+ POST_PROCESS_FAILED: { facts: NONE },
325
+ SEARCH_INCOMPLETE: { facts: facts(["diagnostics"], ["scanned", "scanLimit"]) },
326
+ RIPGREP_FAILED: { facts: NONE },
327
+ UNSUPPORTED_PATH: { facts: NONE },
347
328
  UNCLASSIFIED: { facts: NONE },
348
329
  } as const satisfies Record<
349
330
  string,
@@ -376,32 +357,40 @@ export const REREAD = "Read the file before further edits.";
376
357
  /** Once a mutation reached or may have reached the file, a retry could apply it twice. */
377
358
  export const PUBLICATION_NEXT = {
378
359
  PUBLISHED: `The change is saved; do not repeat it. ${REREAD}`,
379
- UNKNOWN: `The change may already be applied; do not repeat it. ${REREAD}`,
360
+ UNKNOWN:
361
+ "The change may or may not be saved. Read the file, and repeat the change only if it is missing.",
380
362
  } as const satisfies Record<Exclude<PublicationStatus, "NOT_PUBLISHED">, string>;
381
363
 
364
+ /** One fact's recovery; `except` is a value of that fact which needs none. */
365
+ type OutcomeRule = {
366
+ [F in FactName]: readonly [fact: F, next: string, except?: Static<(typeof FACT_FIELDS)[F]>];
367
+ }[FactName];
368
+
382
369
  /**
383
370
  * Recovery after a successful result, by the first fact present in this order.
384
- * A fact absent from this list needs no recovery beyond itself.
371
+ * A fact absent from this list, or holding the value its rule excepts, needs no recovery beyond itself.
385
372
  */
386
- export const OUTCOME_NEXT = [
387
- ["freshness", REREAD],
373
+ export const OUTCOME_NEXT: readonly OutcomeRule[] = [
374
+ // A file that no longer exists has no anchors to refresh.
375
+ ["freshness", REREAD, "missing"],
388
376
  [
389
377
  "lineTooLong",
390
378
  "Inspect the line in chunks with bash, or use replace for a known literal or regex change; a smaller limit cannot split a line.",
391
379
  ],
392
380
  ["pagination", "If you need more lines, set offset to pagination.nextOffset."],
381
+ // Ahead of matchLimit: once the byte budget cuts the output, raising limit shows nothing more.
382
+ ["outputLimit", "Narrow path, glob, or pattern to see the omitted output."],
393
383
  ["matchLimit", "If you need more matches, raise limit to include rows after the last one shown."],
394
384
  [
395
385
  "literalPipe",
396
- "If you meant alternatives, pass them as a pattern array. Otherwise, keep literal matching.",
386
+ "If you meant alternatives, give each as its own pattern item. Otherwise, keep literal matching.",
397
387
  ],
398
388
  [
399
389
  "scanLimit",
400
390
  "Narrow path or glob, or add text every match must contain, to search the remaining files.",
401
391
  ],
402
- ["outputLimit", "Narrow path, glob, or pattern to see the omitted output."],
403
392
  ["linePreviewLimit", "Read the full line before rewriting it from a partial preview."],
404
- ] as const satisfies readonly (readonly [FactName, string])[];
393
+ ];
405
394
 
406
395
  /** The report envelope and facts, in output order; `next` is always last. */
407
396
  export const REPORT_SCHEMA = Type.Object({
@@ -409,11 +398,10 @@ export const REPORT_SCHEMA = Type.Object({
409
398
  tool: Type.String(),
410
399
  path: opt(Type.Union([Type.String(), Type.Array(Type.String())])),
411
400
  publication: opt(PUBLICATION_SCHEMA),
412
- stage: opt(STAGE_SCHEMA),
413
401
  message: opt(Type.String()),
414
402
  cause: opt(CAUSE_SCHEMA),
415
403
  ...(Object.fromEntries(
416
- Object.entries(FACT_FIELDS).map(([name, schema]) => [name, Type.Optional(schema)]),
404
+ Object.entries(FACT_FIELDS).map(([name, schema]) => [name, opt(schema)]),
417
405
  ) as { [K in FactName]: ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>> }),
418
406
  next: opt(Type.String()),
419
407
  });
@@ -426,7 +414,7 @@ const SUCCESS_DEFINITIONS = {
426
414
  [
427
415
  "matches",
428
416
  "files",
429
- "candidates",
417
+ "scanned",
430
418
  "matchLimit",
431
419
  "scanLimit",
432
420
  "outputLimit",
@@ -442,7 +430,7 @@ const SUCCESS_DEFINITIONS = {
442
430
  } as const;
443
431
  export type ReportTool = keyof typeof SUCCESS_DEFINITIONS;
444
432
  /** Tools whose reports carry publication, freshness, and the then_run outcome. */
445
- export const MUTATION_TOOLS = ["edit", "replace", "write"] as const satisfies readonly ReportTool[];
433
+ const MUTATION_TOOLS = ["edit", "replace", "write"] as const satisfies readonly ReportTool[];
446
434
  export type MutationToolName = (typeof MUTATION_TOOLS)[number];
447
435
  /** Argument rejections may omit message; Pi supplies none for them. */
448
436
  const MESSAGE_OPTIONAL = "INVALID_ARGUMENTS" satisfies ErrorCode;
@@ -460,16 +448,12 @@ const MUTATION_WIRE_FIELDS = {
460
448
  then_run: REPORT_SCHEMA.properties.then_run,
461
449
  progressError: REPORT_SCHEMA.properties.progressError,
462
450
  };
463
- const FAILURE_WIRE_FIELDS = {
464
- stage: REPORT_SCHEMA.properties.stage,
465
- cause: REPORT_SCHEMA.properties.cause,
466
- };
467
451
  const FAILURE_SCHEMAS = ERROR_CODES.map((code) =>
468
452
  Type.Object(
469
453
  {
470
454
  ...COMMON_WIRE_FIELDS,
471
455
  ...MUTATION_WIRE_FIELDS,
472
- ...FAILURE_WIRE_FIELDS,
456
+ cause: REPORT_SCHEMA.properties.cause,
473
457
  error: Type.Literal(code),
474
458
  message: code === MESSAGE_OPTIONAL ? opt(Type.String()) : Type.String(),
475
459
  ...ERROR_DEFINITIONS[code].facts.properties,
@@ -514,7 +498,7 @@ export type SuccessReport = {
514
498
  export type FailureReport = {
515
499
  [C in ErrorCode]: ReportVariant<
516
500
  Envelope & { tool: ReportTool; error: C } & MutationFields &
517
- Fields<typeof FAILURE_WIRE_FIELDS> &
501
+ Pick<ReportFields, "cause"> &
518
502
  (C extends typeof MESSAGE_OPTIONAL ? { message?: string } : { message: string }) &
519
503
  Static<Definitions[C]["facts"]>
520
504
  >;