@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  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.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -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. */
@@ -12,7 +11,15 @@ export async function expectToolFailure(
12
11
  ): Promise<Report> {
13
12
  const result = await pending;
14
13
  assert.equal(result.isError, true);
15
- const report = detailsReport(result.details);
14
+ const details = result.details;
15
+ assert.ok(typeof details === "object" && details !== null && "report" in details);
16
+ const value = details.report;
17
+ assert.ok(typeof value === "object" && value !== null && "tool" in value);
18
+ const tool = (["read", "grep", "edit", "replace", "write"] as const).find(
19
+ (name) => name === value.tool,
20
+ );
21
+ assert.ok(tool);
22
+ const report = detailsReport(details, tool);
16
23
  assert.ok(report);
17
24
  assert.equal(report.error, code);
18
25
  inspect?.(report);
@@ -6,16 +6,17 @@
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
  */
17
17
 
18
- import { Type, type Static, type TObject, type TProperties } from "typebox";
18
+ import { Type, type Static, type TObject, type TProperties, type TSchema } from "typebox";
19
+ import { literalUnion } from "./schema.ts";
19
20
 
20
21
  const count = (description: string) => Type.Integer({ minimum: 1, description });
21
22
  const opt = Type.Optional;
@@ -25,11 +26,10 @@ export const CAUSE_SCHEMA = Type.Cyclic(
25
26
  {
26
27
  Cause: Type.Object(
27
28
  {
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." })),
29
+ error: opt(Type.String({ description: "Error code of a classified cause." })),
30
+ code: opt(Type.String({ description: "Node errno code, such as EACCES." })),
30
31
  message: Type.String(),
31
- cause: Type.Optional(Type.Ref("Cause")),
32
- errors: Type.Optional(Type.Array(Type.Ref("Cause"))),
32
+ cause: opt(Type.Ref("Cause")),
33
33
  },
34
34
  { additionalProperties: false },
35
35
  ),
@@ -45,13 +45,6 @@ const PUBLICATION_SCHEMA = Type.Union([
45
45
  ]);
46
46
  export type PublicationStatus = Static<typeof PUBLICATION_SCHEMA>;
47
47
 
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
48
  const FRESHNESS_SCHEMA = Type.Union([
56
49
  Type.Literal("unchanged"),
57
50
  Type.Literal("changed"),
@@ -128,13 +121,12 @@ const ANCHOR_FAILURE_SCHEMA = Type.Object(
128
121
  Type.Literal("ambiguous"),
129
122
  Type.Literal("unresolved"),
130
123
  ]),
131
- search: opt(Type.Union([Type.Literal("local window"), Type.Literal("full file")])),
132
124
  candidate: opt(Type.String()),
133
125
  content: opt(Type.String()),
134
126
  candidates: opt(Type.Array(Type.String())),
135
127
  omittedCandidates: opt(Type.Integer({ minimum: 1 })),
136
128
  observed: opt(Type.String()),
137
- omitted: opt(
129
+ notShown: opt(
138
130
  Type.String({ description: "Why content (shifted) or observed (unresolved) is absent." }),
139
131
  ),
140
132
  },
@@ -156,86 +148,191 @@ const ARGUMENT_ISSUE_SCHEMA = Type.Object(
156
148
  );
157
149
  export type ArgumentIssue = Static<typeof ARGUMENT_ISSUE_SCHEMA>;
158
150
 
151
+ /**
152
+ * Every fact carries its schema and its audience contract here. Model-visible
153
+ * facts must also state the decision their value changes; TUI-only facts omit it.
154
+ */
155
+ type FactAudience = "model" | "tui";
156
+ type FactDefinition<T extends TSchema = TSchema> = {
157
+ schema: T;
158
+ audience: FactAudience;
159
+ decision?: string;
160
+ };
161
+
162
+ function modelFact<T extends TSchema, const D extends string>(
163
+ schema: T,
164
+ decision: D extends "" ? never : D,
165
+ ): FactDefinition<T> {
166
+ return { schema, audience: "model", decision };
167
+ }
168
+
169
+ function tuiFact<T extends TSchema>(schema: T): FactDefinition<T> {
170
+ return { schema, audience: "tui" };
171
+ }
172
+
159
173
  /**
160
174
  * Every fact a report can carry beside the envelope, in output order: failure
161
175
  * facts first, then each tool's outcome, freshness, and the command.
162
176
  */
163
177
  const FACT_FIELDS = {
164
178
  // Argument rejection (argument-error.ts).
165
- issues: Type.Array(ARGUMENT_ISSUE_SCHEMA),
166
- omittedIssues: count("Issues omitted from the byte budget."),
167
- schemaLimited: Type.Literal(true, {
168
- description: "A native diagnostic allowance was reached; more issues may exist.",
169
- }),
170
- // A missing path among several (grep).
171
- missing: Type.String(),
179
+ issues: modelFact(
180
+ Type.Array(ARGUMENT_ISSUE_SCHEMA),
181
+ "Correct the reported argument issues before retrying.",
182
+ ),
183
+ omittedIssues: modelFact(
184
+ count("Issues omitted from the byte budget."),
185
+ "Know that the bounded argument report is incomplete.",
186
+ ),
187
+ schemaLimited: modelFact(
188
+ Type.Literal(true, {
189
+ description: "A native diagnostic allowance was reached; more issues may exist.",
190
+ }),
191
+ "Know that native validation may have omitted additional issues.",
192
+ ),
193
+ missing: modelFact(
194
+ Type.Array(Type.String(), {
195
+ description: "Resolved paths that do not exist; shows where a relative path led.",
196
+ }),
197
+ "Use the resolved missing paths to correct the target or choose create mode.",
198
+ ),
199
+
172
200
  // Anchor verification (failure-context.ts).
173
- failures: Type.Array(ANCHOR_FAILURE_SCHEMA),
174
- 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
- candidateNeighborhoods: Type.Array(
178
- Type.Object(
179
- { lines: Type.String(), rows: Type.Array(Type.String()) },
180
- { additionalProperties: false },
201
+ failures: modelFact(
202
+ Type.Array(ANCHOR_FAILURE_SCHEMA),
203
+ "Choose a verified anchor or reread before retrying.",
204
+ ),
205
+ omittedFailures: modelFact(
206
+ count("Failures omitted from the byte budget."),
207
+ "Know that anchor evidence is incomplete.",
208
+ ),
209
+ candidateNeighborhoods: modelFact(
210
+ Type.Array(
211
+ Type.Object(
212
+ { lines: Type.String(), rows: Type.Array(Type.String()) },
213
+ { additionalProperties: false },
214
+ ),
181
215
  ),
216
+ "Inspect the observed neighborhoods before selecting an ambiguous anchor.",
182
217
  ),
183
- 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 }),
188
- timeoutMs: Type.Integer({ minimum: 1 }),
189
- exitCode: Type.Union([Type.Integer(), Type.Null()]),
190
- // read outcome; `outputLimit` below is shared with grep.
191
- pagination: Type.Object(
192
- {
193
- start: Type.Integer(),
194
- end: Type.Integer(),
195
- totalLines: Type.Integer(),
196
- nextOffset: Type.Integer(),
197
- },
198
- { additionalProperties: false },
218
+ omittedNeighborhoodRows: modelFact(
219
+ count("Neighborhood rows omitted from the byte budget."),
220
+ "Know that candidate context is incomplete.",
199
221
  ),
200
- lineTooLong: Type.Object(
201
- { line: Type.Integer(), limit: Type.String() },
202
- { additionalProperties: false },
222
+
223
+ // Overlap (core/apply.ts, core/replace.ts).
224
+ conflict: modelFact(
225
+ Type.Array(Type.String(), {
226
+ description: "The first conflicting pair of inputs found; more conflicts may exist.",
227
+ }),
228
+ "Merge or separate the conflicting edits or rules before retrying.",
229
+ ),
230
+
231
+ // Replacement rules (core/replace.ts).
232
+ unmatched: modelFact(
233
+ Type.Array(Type.String(), { description: "Rules that match nothing." }),
234
+ "Correct the target rules using read or grep before retrying.",
235
+ ),
236
+ line: modelFact(
237
+ Type.Integer({ minimum: 1, description: "Line where the conflicting match starts." }),
238
+ "Locate the first conflicting match when correcting the request.",
239
+ ),
240
+
241
+ // Regex workers (regex-worker.ts).
242
+ timeoutMs: modelFact(
243
+ Type.Integer({ minimum: 1 }),
244
+ "Narrow or simplify the timed-out pattern before retrying.",
245
+ ),
246
+ exitCode: tuiFact(Type.Union([Type.Integer(), Type.Null()])),
247
+
248
+ // read outcome; outputLimit below is shared with grep.
249
+ nextOffset: modelFact(Type.Integer({ minimum: 1 }), "Use nextOffset to continue reading."),
250
+ lineTooLong: modelFact(
251
+ Type.String({ description: "Byte limit that prevented the first selected line from fitting." }),
252
+ "Inspect the oversized line with an appropriate tool before editing it.",
253
+ ),
254
+
255
+ // grep outcome; matches is also replace's match count.
256
+ matches: modelFact(
257
+ Type.Integer({ minimum: 0 }),
258
+ "Change the pattern or scope when zero; otherwise check the total against the rows shown or the replacements intended.",
259
+ ),
260
+ files: modelFact(
261
+ Type.Integer({ minimum: 0 }),
262
+ "Know how many files matched when the payload does not show every file.",
263
+ ),
264
+ matchLimit: modelFact(
265
+ Type.Integer({ minimum: 1, description: "The match limit that stopped the search." }),
266
+ "Raise the limit when more matches are needed.",
267
+ ),
268
+ scanLimit: modelFact(
269
+ Type.String({
270
+ description:
271
+ "Bytes of files read when every file was a candidate; later files were not searched.",
272
+ }),
273
+ "Narrow the search or add text every match must contain to search the remaining files.",
274
+ ),
275
+ outputLimit: modelFact(
276
+ Type.String({ description: "The output byte budget that cut the result." }),
277
+ "Narrow the scope to see omitted output.",
203
278
  ),
204
- // grep outcome; `matches` is also replace's match count.
205
- matches: Type.Integer({ minimum: 0 }),
206
- files: Type.Integer({ minimum: 0 }),
207
- candidates: Type.Union([Type.Literal("files"), Type.Literal("all")], {
208
- description:
209
- "Without line candidates, the files searched whole: those containing text every match needs, or every file in scope.",
210
- }),
211
- matchLimit: Type.Integer({ minimum: 1, description: "The match limit that stopped the search." }),
212
- scanLimit: Type.String({
213
- description:
214
- "Bytes of files read when every file was a candidate; later files were not searched.",
215
- }),
216
- outputLimit: Type.String({ description: "The output byte budget that cut the result." }),
217
- linePreviewLimit: Type.Integer({ description: "UTF-16 units kept in a cut line preview." }),
218
- invalidUtf8: Type.Array(Type.String(), {
219
- description: "Files shown as plain previews; their rows are not edit anchors.",
220
- }),
221
- diagnostics: Type.String({ description: "Search diagnostics; results cover confirmed matches." }),
222
- literalPipe: Type.Literal(true, {
223
- description: "A literal pattern contains |, which matches only the | character.",
224
- }),
225
- // Mutation outcome.
226
- created: Type.Literal(true),
279
+ linePreviewLimit: modelFact(
280
+ Type.Integer({ description: "UTF-16 units kept in a cut line preview." }),
281
+ "Read the full line before rewriting it from a partial preview.",
282
+ ),
283
+ invalidUtf8: modelFact(
284
+ Type.Array(Type.String(), {
285
+ description: "Files shown as plain previews; their rows are not edit anchors.",
286
+ }),
287
+ "Do not use malformed preview rows as edit anchors.",
288
+ ),
289
+ diagnostics: modelFact(
290
+ Type.String({ description: "Search diagnostics; results cover confirmed matches." }),
291
+ "Treat the result as confirmed matches only; remove the stated cause or narrow the scope to search what was missed.",
292
+ ),
293
+ literalPipe: modelFact(
294
+ Type.Literal(true, {
295
+ description: "A literal pattern contains |, which matches only the | character.",
296
+ }),
297
+ "Separate pattern alternatives or keep the pattern literal.",
298
+ ),
299
+
227
300
  // Commit-layer observation after publication.
228
- freshness: FRESHNESS_SCHEMA,
229
- freshnessError: CAUSE_SCHEMA,
301
+ freshness: modelFact(
302
+ FRESHNESS_SCHEMA,
303
+ "Read the file before further edits when the current content is not known to be unchanged.",
304
+ ),
305
+ freshnessError: modelFact(
306
+ CAUSE_SCHEMA,
307
+ "Use the freshness recovery instruction when the post-commit observation failed.",
308
+ ),
309
+
230
310
  // Action Fusion.
231
- then_run: Type.Object(
232
- { status: COMMAND_STATUS_SCHEMA, output: opt(Type.String()) },
233
- { additionalProperties: false },
311
+ then_run: modelFact(
312
+ Type.Object(
313
+ { status: COMMAND_STATUS_SCHEMA, output: opt(Type.String()) },
314
+ { additionalProperties: false },
315
+ ),
316
+ "Act on the failure the output shows, and run the command separately when it did not run.",
234
317
  ),
235
- progressError: CAUSE_SCHEMA,
236
- } satisfies TProperties;
318
+ progressError: tuiFact(CAUSE_SCHEMA),
319
+ } as const satisfies Record<string, FactDefinition>;
237
320
 
238
321
  type FactName = keyof typeof FACT_FIELDS;
322
+ type FactSchema<Name extends FactName> = (typeof FACT_FIELDS)[Name]["schema"];
323
+ type TuiOnlyFactName = {
324
+ [Name in FactName]: (typeof FACT_FIELDS)[Name]["audience"] extends "tui" ? Name : never;
325
+ }[FactName];
326
+ export type ModelOmittedField = "tool" | "path" | TuiOnlyFactName;
327
+
328
+ /** Fields whose values are kept for TUI/host but omitted from model text. */
329
+ export const MODEL_OMITTED_FIELDS: ReadonlySet<ModelOmittedField> = new Set<ModelOmittedField>([
330
+ "tool",
331
+ "path",
332
+ ...Object.entries(FACT_FIELDS)
333
+ .filter(([, definition]) => definition.audience === "tui")
334
+ .map(([name]) => name as TuiOnlyFactName),
335
+ ]);
239
336
 
240
337
  /** Facts of one code: the named fields, each optional unless listed as required. */
241
338
  function facts<const R extends readonly FactName[], const O extends readonly FactName[] = []>(
@@ -243,20 +340,19 @@ function facts<const R extends readonly FactName[], const O extends readonly Fac
243
340
  optional?: O,
244
341
  ) {
245
342
  const properties: TProperties = {};
246
- for (const name of required) properties[name] = FACT_FIELDS[name];
247
- for (const name of optional ?? []) properties[name] = Type.Optional(FACT_FIELDS[name]);
343
+ for (const name of required) properties[name] = FACT_FIELDS[name].schema;
344
+ for (const name of optional ?? []) properties[name] = opt(FACT_FIELDS[name].schema);
248
345
  // A single mapped property set preserves required keys in TypeBox's static inference.
249
346
  return Type.Object(
250
347
  properties as {
251
348
  [K in R[number] | O[number]]: K extends R[number]
252
- ? (typeof FACT_FIELDS)[K]
253
- : ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>>;
349
+ ? FactSchema<K>
350
+ : ReturnType<typeof Type.Optional<FactSchema<K>>>;
254
351
  },
255
352
  { additionalProperties: false },
256
353
  );
257
354
  }
258
355
  const NONE = facts([]);
259
- const MATCHED = ["matched", "omittedMatched"] as const;
260
356
 
261
357
  /**
262
358
  * Each error code: its facts and its recovery. `next.default` is the code's
@@ -264,9 +360,7 @@ const MATCHED = ["matched", "omittedMatched"] as const;
264
360
  * Once a mutation reached or may have reached the file, PUBLICATION_NEXT replaces them.
265
361
  */
266
362
  export const ERROR_DEFINITIONS = {
267
- INVALID_ARGUMENTS: {
268
- facts: facts(["issues"], ["omittedIssues", "schemaLimited"]),
269
- },
363
+ INVALID_ARGUMENTS: { facts: facts(["issues"], ["omittedIssues", "schemaLimited"]) },
270
364
  OPERATION_ABORTED: { facts: NONE },
271
365
  PATH_NOT_FOUND: {
272
366
  facts: facts([], ["missing"]),
@@ -283,45 +377,39 @@ export const ERROR_DEFINITIONS = {
283
377
  },
284
378
  UNSUPPORTED_ENCODING: { facts: NONE },
285
379
  UNSUPPORTED_TEXT: { facts: NONE },
286
- INVALID_UNICODE: {
287
- facts: NONE,
288
- },
380
+ INVALID_UNICODE: { facts: NONE },
289
381
  ANCHOR_MISMATCH: {
290
382
  facts: facts(
291
383
  ["failures"],
292
- ["omittedFailures", ...MATCHED, "candidateNeighborhoods", "omittedNeighborhoodRows"],
384
+ ["omittedFailures", "candidateNeighborhoods", "omittedNeighborhoodRows"],
293
385
  ),
294
386
  next: {
295
387
  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.",
388
+ "Confirm a candidate or observed anchor is the intended target before reusing it; otherwise use read or grep.",
297
389
  },
298
390
  },
299
- INVALID_RANGE: {
300
- facts: facts([], MATCHED),
301
- },
302
391
  OVERLAPPING_EDITS: {
303
- facts: facts([], MATCHED),
392
+ facts: facts(["conflict"]),
304
393
  next: {
305
- default:
306
- "Merge overlapping edits into one edit per range, and insertions at one position into one insertion.",
394
+ default: "Merge them into one edit per range or position.",
307
395
  },
308
396
  },
309
397
  NO_MATCH: {
310
- facts: facts(["rule"]),
398
+ facts: facts(["unmatched"]),
311
399
  next: {
312
400
  default:
313
401
  "Verify the target text with read or grep; check case sensitivity or regex flags if applicable.",
314
402
  },
315
403
  },
316
404
  OVERLAPPING_MATCHES: {
317
- facts: facts(["rules", "offset"]),
318
- },
319
- REGEX_TIMEOUT: {
320
- facts: facts(["timeoutMs"]),
321
- },
322
- REGEX_WORKER_FAILED: {
323
- facts: facts([], ["exitCode"]),
405
+ facts: facts(["conflict", "line"]),
406
+ next: {
407
+ default:
408
+ "Change the conflicting rules so their matches do not overlap, or merge them into one rule.",
409
+ },
324
410
  },
411
+ REGEX_TIMEOUT: { facts: facts(["timeoutMs"]) },
412
+ REGEX_WORKER_FAILED: { facts: facts([], ["exitCode"]) },
325
413
  TARGET_EXISTS: {
326
414
  facts: NONE,
327
415
  next: {
@@ -329,24 +417,17 @@ export const ERROR_DEFINITIONS = {
329
417
  'Check the path and read the existing file. Use mode "overwrite" only if replacing that file is intended.',
330
418
  },
331
419
  },
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: {
420
+ NOT_REGULAR_FILE: {
348
421
  facts: NONE,
422
+ next: { default: "Use the path of a regular file." },
349
423
  },
424
+ MULTIPLE_HARD_LINKS: { facts: NONE },
425
+ SYMLINK_UNRESOLVED: { facts: NONE },
426
+ PUBLISH_FAILED: { facts: NONE },
427
+ POST_PROCESS_FAILED: { facts: NONE },
428
+ SEARCH_INCOMPLETE: { facts: facts(["diagnostics"], ["scanLimit"]) },
429
+ RIPGREP_FAILED: { facts: NONE },
430
+ UNSUPPORTED_PATH: { facts: NONE },
350
431
  UNCLASSIFIED: { facts: NONE },
351
432
  } as const satisfies Record<
352
433
  string,
@@ -374,62 +455,75 @@ export const NEXT_GUIDELINE =
374
455
  "When a tool report includes next, follow it for that result; it takes precedence over these guidelines.";
375
456
 
376
457
  /** Text shared by success and failure: a file whose current anchors are unknown must be read first. */
377
- export const REREAD = "Read the file before further edits.";
458
+ const REREAD = "Read the file before further edits.";
378
459
 
379
460
  /** Once a mutation reached or may have reached the file, a retry could apply it twice. */
380
461
  export const PUBLICATION_NEXT = {
381
462
  PUBLISHED: `The change is saved; do not repeat it. ${REREAD}`,
382
- UNKNOWN: `The change may already be applied; do not repeat it. ${REREAD}`,
463
+ UNKNOWN:
464
+ "The change may or may not be saved. Read the file, and repeat the change only if it is missing.",
383
465
  } as const satisfies Record<Exclude<PublicationStatus, "NOT_PUBLISHED">, string>;
384
466
 
467
+ /** One fact's recovery; `except` is a value of that fact which needs none. */
468
+ type OutcomeRule =
469
+ | {
470
+ [F in FactName]: readonly [fact: F, next: string, except?: Static<FactSchema<F>>];
471
+ }[FactName]
472
+ | readonly [fact: "publication", next: string, except?: PublicationStatus];
473
+
385
474
  /**
386
475
  * 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.
476
+ * A fact absent from this list, or holding the value its rule excepts, needs no recovery beyond itself.
388
477
  */
389
- export const OUTCOME_NEXT = [
390
- ["freshness", REREAD],
478
+ export const OUTCOME_NEXT: readonly OutcomeRule[] = [
479
+ // A file that no longer exists has no anchors to refresh.
480
+ ["freshness", REREAD, "missing"],
481
+ [
482
+ "publication",
483
+ "The file already has this content; nothing was written, so do not repeat the call.",
484
+ "PUBLISHED",
485
+ ],
391
486
  [
392
487
  "lineTooLong",
393
488
  "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
489
  ],
395
- ["pagination", "If you need more lines, set offset to pagination.nextOffset."],
490
+ ["nextOffset", "If you need more lines, set offset to nextOffset."],
491
+ // Ahead of matchLimit: once the byte budget cuts the output, raising limit shows nothing more.
492
+ ["outputLimit", "Narrow path, glob, or pattern to see the omitted output."],
396
493
  ["matchLimit", "If you need more matches, raise limit to include rows after the last one shown."],
397
494
  [
398
495
  "literalPipe",
399
- "If you meant alternatives, pass them as a pattern array. Otherwise, keep literal matching.",
496
+ "If you meant alternatives, give each as its own pattern item. Otherwise, keep literal matching.",
400
497
  ],
401
498
  [
402
499
  "scanLimit",
403
500
  "Narrow path or glob, or add text every match must contain, to search the remaining files.",
404
501
  ],
405
- ["outputLimit", "Narrow path, glob, or pattern to see the omitted output."],
406
502
  ["linePreviewLimit", "Read the full line before rewriting it from a partial preview."],
407
- ] as const satisfies readonly (readonly [FactName, string])[];
503
+ ];
408
504
 
409
505
  /** The report envelope and facts, in output order; `next` is always last. */
410
506
  export const REPORT_SCHEMA = Type.Object({
411
- error: opt(Type.Union(ERROR_CODES.map((code) => Type.Literal(code)))),
507
+ error: opt(literalUnion(ERROR_CODES)),
412
508
  tool: Type.String(),
413
509
  path: opt(Type.Union([Type.String(), Type.Array(Type.String())])),
414
510
  publication: opt(PUBLICATION_SCHEMA),
415
- stage: opt(STAGE_SCHEMA),
416
511
  message: opt(Type.String()),
417
512
  cause: opt(CAUSE_SCHEMA),
418
513
  ...(Object.fromEntries(
419
- Object.entries(FACT_FIELDS).map(([name, schema]) => [name, Type.Optional(schema)]),
420
- ) as { [K in FactName]: ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>> }),
514
+ Object.entries(FACT_FIELDS).map(([name, definition]) => [name, opt(definition.schema)]),
515
+ ) as { [K in FactName]: ReturnType<typeof Type.Optional<FactSchema<K>>> }),
421
516
  next: opt(Type.String()),
422
517
  });
423
- type ReportFields = Omit<Static<typeof REPORT_SCHEMA>, "error"> & { error?: ErrorCode };
518
+ type ReportFields = Static<typeof REPORT_SCHEMA>;
424
519
 
425
520
  const SUCCESS_DEFINITIONS = {
426
- read: facts([], ["pagination", "outputLimit", "lineTooLong"]),
521
+ read: facts([], ["nextOffset", "outputLimit", "lineTooLong"]),
427
522
  grep: facts(
428
523
  [],
429
524
  [
430
525
  "matches",
431
526
  "files",
432
- "candidates",
433
527
  "matchLimit",
434
528
  "scanLimit",
435
529
  "outputLimit",
@@ -441,16 +535,16 @@ const SUCCESS_DEFINITIONS = {
441
535
  ),
442
536
  edit: facts([]),
443
537
  replace: facts([], ["matches"]),
444
- write: facts([], ["created"]),
538
+ write: facts([]),
445
539
  } as const;
446
540
  export type ReportTool = keyof typeof SUCCESS_DEFINITIONS;
447
541
  /** Tools whose reports carry publication, freshness, and the then_run outcome. */
448
- export const MUTATION_TOOLS = ["edit", "replace", "write"] as const satisfies readonly ReportTool[];
542
+ const MUTATION_TOOLS = ["edit", "replace", "write"] as const satisfies readonly ReportTool[];
449
543
  export type MutationToolName = (typeof MUTATION_TOOLS)[number];
450
544
  /** Argument rejections may omit message; Pi supplies none for them. */
451
545
  const MESSAGE_OPTIONAL = "INVALID_ARGUMENTS" satisfies ErrorCode;
452
546
 
453
- const TOOL_SCHEMA = Type.Union(Object.keys(SUCCESS_DEFINITIONS).map((tool) => Type.Literal(tool)));
547
+ const TOOL_SCHEMA = literalUnion(Object.keys(SUCCESS_DEFINITIONS) as ReportTool[]);
454
548
  const COMMON_WIRE_FIELDS = {
455
549
  tool: TOOL_SCHEMA,
456
550
  path: REPORT_SCHEMA.properties.path,
@@ -463,16 +557,12 @@ const MUTATION_WIRE_FIELDS = {
463
557
  then_run: REPORT_SCHEMA.properties.then_run,
464
558
  progressError: REPORT_SCHEMA.properties.progressError,
465
559
  };
466
- const FAILURE_WIRE_FIELDS = {
467
- stage: REPORT_SCHEMA.properties.stage,
468
- cause: REPORT_SCHEMA.properties.cause,
469
- };
470
560
  const FAILURE_SCHEMAS = ERROR_CODES.map((code) =>
471
561
  Type.Object(
472
562
  {
473
563
  ...COMMON_WIRE_FIELDS,
474
564
  ...MUTATION_WIRE_FIELDS,
475
- ...FAILURE_WIRE_FIELDS,
565
+ cause: REPORT_SCHEMA.properties.cause,
476
566
  error: Type.Literal(code),
477
567
  message: code === MESSAGE_OPTIONAL ? opt(Type.String()) : Type.String(),
478
568
  ...ERROR_DEFINITIONS[code].facts.properties,
@@ -494,6 +584,19 @@ const SUCCESS_SCHEMAS = Object.entries(SUCCESS_DEFINITIONS).map(([tool, schema])
494
584
  /** Closed records after the originating call supplies the tool; failure facts remain code-specific. */
495
585
  export const WIRE_REPORT_SCHEMA = Type.Union([...FAILURE_SCHEMAS, ...SUCCESS_SCHEMAS]);
496
586
 
587
+ type SuccessFactNames = {
588
+ [Tool in ReportTool]: keyof Static<(typeof SUCCESS_DEFINITIONS)[Tool]>;
589
+ }[ReportTool] &
590
+ string;
591
+ type ErrorFactNames = {
592
+ [Code in ErrorCode]: keyof Static<(typeof ERROR_DEFINITIONS)[Code]["facts"]>;
593
+ }[ErrorCode] &
594
+ string;
595
+ type MutationWireFactNames = keyof Fields<typeof MUTATION_WIRE_FIELDS> & string;
596
+ type UnusedFactNames = Exclude<FactName, SuccessFactNames | ErrorFactNames | MutationWireFactNames>;
597
+ // Compilation fails here, naming the fact, when no tool, code, or mutation field carries it.
598
+ ({}) satisfies Record<UnusedFactNames, never>;
599
+
497
600
  // Static counterparts of the per-tool and per-code wire schemas above, built from the same fields.
498
601
  type Fields<P extends TProperties> = Static<TObject<P>>;
499
602
  type Envelope = Omit<Fields<typeof COMMON_WIRE_FIELDS>, "tool">;
@@ -517,7 +620,7 @@ export type SuccessReport = {
517
620
  export type FailureReport = {
518
621
  [C in ErrorCode]: ReportVariant<
519
622
  Envelope & { tool: ReportTool; error: C } & MutationFields &
520
- Fields<typeof FAILURE_WIRE_FIELDS> &
623
+ Pick<ReportFields, "cause"> &
521
624
  (C extends typeof MESSAGE_OPTIONAL ? { message?: string } : { message: string }) &
522
625
  Static<Definitions[C]["facts"]>
523
626
  >;