@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
@@ -24,51 +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
38
  formatHeaderPath,
50
- renderMutationCall,
51
- renderMutationResult,
52
39
  type DiffCounts,
53
40
  } from "./render.ts";
54
41
  import {
55
- executeMutation,
42
+ mutationToolBase,
56
43
  runTextMutation,
57
44
  type ActionFusionExecutor,
58
45
  type MutationTarget,
59
- type TextMutationDetails,
60
46
  } from "./mutation-runner.ts";
61
- import type { MutationResultDetails } from "./mutation-result.ts";
62
47
  import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
63
- import {
64
- argumentItems,
65
- createArgumentPreparer,
66
- type ReportArgumentIssue,
67
- } from "./argument-validation.ts";
68
- type ReplaceDetails = MutationResultDetails<TextMutationDetails>;
69
- type ReplaceRenderContext = Parameters<
70
- NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
71
- >[2];
48
+ import { argumentItems, type ReportArgumentIssue } from "./argument-validation.ts";
72
49
 
73
50
  const replaceSchema = Type.Object(
74
51
  {
@@ -81,7 +58,7 @@ const replaceSchema = Type.Object(
81
58
  { additionalProperties: false },
82
59
  );
83
60
 
84
- type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
61
+ type ReplaceParams = Static<typeof replaceSchema>;
85
62
 
86
63
  /** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
87
64
  function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
@@ -98,10 +75,10 @@ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void
98
75
  const rules = argumentItems((args as { replacements?: unknown } | null)?.replacements);
99
76
  rules.forEach((rule, index) => {
100
77
  const { find, replace, literal, flags } = (rule ?? {}) as Record<string, unknown>;
78
+ const item = `replacements[${index}]`;
101
79
  const unwritable = typeof replace === "string" ? unwritableTextError(replace) : undefined;
102
- if (unwritable) report(`replacements[${index}].replace`, unwritable.message);
80
+ if (unwritable) report(`${item}.replace`, unwritable.message);
103
81
  if (flags !== undefined && typeof flags !== "string") return;
104
- const item = `replacements[${index}]`;
105
82
  checkRegexArguments(
106
83
  `${item}.flags`,
107
84
  flags,
@@ -118,59 +95,20 @@ export function makeReplaceTool(
118
95
  fusion?: ActionFusionExecutor,
119
96
  budgets: OutputBudgetProvider = defaultOutputBudgets,
120
97
  ) {
121
- const parameters = withThenRunSchema(replaceSchema, "replace", fusion !== undefined);
122
98
  return {
123
- name: "replace" as const,
124
- label: "replace",
125
- description: withThenRunDescription(
126
- "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.",
127
- fusion !== undefined,
128
- ),
129
- promptSnippet: "Replace matching text across a file",
130
- promptGuidelines: [...(fusion ? ACTION_FUSION_GUIDELINES : [])],
131
- parameters,
132
- prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments, budgets),
133
- renderShell: "default" as const,
134
-
135
- renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
136
- return renderMutationCall(args, theme, context, replaceHeader);
137
- },
138
-
139
- renderResult(
140
- result: Parameters<typeof renderMutationResult>[0],
141
- options: ToolRenderResultOptions,
142
- theme: Theme,
143
- context: ReplaceRenderContext,
144
- ) {
145
- return renderMutationResult(
146
- result,
147
- options,
148
- theme,
149
- context,
150
- "Replacing…",
151
- replaceHeader,
152
- "replace",
153
- );
154
- },
155
-
156
- async execute(
157
- toolCallId: string,
158
- params: ReplaceParams,
159
- signal: AbortSignal | undefined,
160
- onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
161
- ctx: ExtensionToolContext,
162
- ) {
163
- return executeMutation<ReplaceParams, TextMutationDetails, "replace">(
164
- {
165
- tool: "replace",
166
- cwd,
167
- fusion,
168
- budgets,
169
- run: (mutationParams, target) => runReplace(target, mutationParams.replacements, config),
170
- },
171
- { toolCallId, params, signal, onUpdate, ctx },
172
- );
173
- },
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),
174
112
  };
175
113
  }
176
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"),
@@ -128,13 +120,12 @@ const ANCHOR_FAILURE_SCHEMA = Type.Object(
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,45 +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),
289
+ facts: facts(["conflict"]),
304
290
  next: {
305
- default:
306
- "Merge overlapping edits into one edit per range, and insertions at one position into one insertion.",
291
+ default: "Merge them into one edit per range or position.",
307
292
  },
308
293
  },
309
294
  NO_MATCH: {
310
- facts: facts(["rule"]),
295
+ facts: facts(["unmatched"]),
311
296
  next: {
312
297
  default:
313
298
  "Verify the target text with read or grep; check case sensitivity or regex flags if applicable.",
314
299
  },
315
300
  },
316
301
  OVERLAPPING_MATCHES: {
317
- facts: facts(["rules", "offset"]),
318
- },
319
- REGEX_TIMEOUT: {
320
- facts: facts(["timeoutMs"]),
321
- },
322
- REGEX_WORKER_FAILED: {
323
- 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
+ },
324
307
  },
308
+ REGEX_TIMEOUT: { facts: facts(["timeoutMs"]) },
309
+ REGEX_WORKER_FAILED: { facts: facts([], ["exitCode"]) },
325
310
  TARGET_EXISTS: {
326
311
  facts: NONE,
327
312
  next: {
@@ -329,24 +314,17 @@ export const ERROR_DEFINITIONS = {
329
314
  'Check the path and read the existing file. Use mode "overwrite" only if replacing that file is intended.',
330
315
  },
331
316
  },
332
- NOT_REGULAR_FILE: { facts: NONE },
333
- MULTIPLE_HARD_LINKS: { facts: NONE },
334
- SYMLINK_UNRESOLVED: { facts: NONE },
335
- PUBLISH_FAILED: {
336
- facts: NONE,
337
- },
338
- POST_PROCESS_FAILED: {
339
- facts: NONE,
340
- },
341
- SEARCH_INCOMPLETE: {
342
- facts: facts(["diagnostics"], ["candidates", "scanLimit"]),
343
- },
344
- RIPGREP_FAILED: {
345
- facts: facts([], ["exitCode"]),
346
- },
347
- UNSUPPORTED_PATH: {
317
+ NOT_REGULAR_FILE: {
348
318
  facts: NONE,
319
+ next: { default: "Use the path of a regular file." },
349
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 },
350
328
  UNCLASSIFIED: { facts: NONE },
351
329
  } as const satisfies Record<
352
330
  string,
@@ -379,32 +357,40 @@ export const REREAD = "Read the file before further edits.";
379
357
  /** Once a mutation reached or may have reached the file, a retry could apply it twice. */
380
358
  export const PUBLICATION_NEXT = {
381
359
  PUBLISHED: `The change is saved; do not repeat it. ${REREAD}`,
382
- 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.",
383
362
  } as const satisfies Record<Exclude<PublicationStatus, "NOT_PUBLISHED">, string>;
384
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
+
385
369
  /**
386
370
  * Recovery after a successful result, by the first fact present in this order.
387
- * 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.
388
372
  */
389
- export const OUTCOME_NEXT = [
390
- ["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"],
391
376
  [
392
377
  "lineTooLong",
393
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.",
394
379
  ],
395
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."],
396
383
  ["matchLimit", "If you need more matches, raise limit to include rows after the last one shown."],
397
384
  [
398
385
  "literalPipe",
399
- "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.",
400
387
  ],
401
388
  [
402
389
  "scanLimit",
403
390
  "Narrow path or glob, or add text every match must contain, to search the remaining files.",
404
391
  ],
405
- ["outputLimit", "Narrow path, glob, or pattern to see the omitted output."],
406
392
  ["linePreviewLimit", "Read the full line before rewriting it from a partial preview."],
407
- ] as const satisfies readonly (readonly [FactName, string])[];
393
+ ];
408
394
 
409
395
  /** The report envelope and facts, in output order; `next` is always last. */
410
396
  export const REPORT_SCHEMA = Type.Object({
@@ -412,11 +398,10 @@ export const REPORT_SCHEMA = Type.Object({
412
398
  tool: Type.String(),
413
399
  path: opt(Type.Union([Type.String(), Type.Array(Type.String())])),
414
400
  publication: opt(PUBLICATION_SCHEMA),
415
- stage: opt(STAGE_SCHEMA),
416
401
  message: opt(Type.String()),
417
402
  cause: opt(CAUSE_SCHEMA),
418
403
  ...(Object.fromEntries(
419
- Object.entries(FACT_FIELDS).map(([name, schema]) => [name, Type.Optional(schema)]),
404
+ Object.entries(FACT_FIELDS).map(([name, schema]) => [name, opt(schema)]),
420
405
  ) as { [K in FactName]: ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>> }),
421
406
  next: opt(Type.String()),
422
407
  });
@@ -429,7 +414,7 @@ const SUCCESS_DEFINITIONS = {
429
414
  [
430
415
  "matches",
431
416
  "files",
432
- "candidates",
417
+ "scanned",
433
418
  "matchLimit",
434
419
  "scanLimit",
435
420
  "outputLimit",
@@ -445,7 +430,7 @@ const SUCCESS_DEFINITIONS = {
445
430
  } as const;
446
431
  export type ReportTool = keyof typeof SUCCESS_DEFINITIONS;
447
432
  /** Tools whose reports carry publication, freshness, and the then_run outcome. */
448
- export const MUTATION_TOOLS = ["edit", "replace", "write"] as const satisfies readonly ReportTool[];
433
+ const MUTATION_TOOLS = ["edit", "replace", "write"] as const satisfies readonly ReportTool[];
449
434
  export type MutationToolName = (typeof MUTATION_TOOLS)[number];
450
435
  /** Argument rejections may omit message; Pi supplies none for them. */
451
436
  const MESSAGE_OPTIONAL = "INVALID_ARGUMENTS" satisfies ErrorCode;
@@ -463,16 +448,12 @@ const MUTATION_WIRE_FIELDS = {
463
448
  then_run: REPORT_SCHEMA.properties.then_run,
464
449
  progressError: REPORT_SCHEMA.properties.progressError,
465
450
  };
466
- const FAILURE_WIRE_FIELDS = {
467
- stage: REPORT_SCHEMA.properties.stage,
468
- cause: REPORT_SCHEMA.properties.cause,
469
- };
470
451
  const FAILURE_SCHEMAS = ERROR_CODES.map((code) =>
471
452
  Type.Object(
472
453
  {
473
454
  ...COMMON_WIRE_FIELDS,
474
455
  ...MUTATION_WIRE_FIELDS,
475
- ...FAILURE_WIRE_FIELDS,
456
+ cause: REPORT_SCHEMA.properties.cause,
476
457
  error: Type.Literal(code),
477
458
  message: code === MESSAGE_OPTIONAL ? opt(Type.String()) : Type.String(),
478
459
  ...ERROR_DEFINITIONS[code].facts.properties,
@@ -517,7 +498,7 @@ export type SuccessReport = {
517
498
  export type FailureReport = {
518
499
  [C in ErrorCode]: ReportVariant<
519
500
  Envelope & { tool: ReportTool; error: C } & MutationFields &
520
- Fields<typeof FAILURE_WIRE_FIELDS> &
501
+ Pick<ReportFields, "cause"> &
521
502
  (C extends typeof MESSAGE_OPTIONAL ? { message?: string } : { message: string }) &
522
503
  Static<Definitions[C]["facts"]>
523
504
  >;