@criogaid/pi-hashline-edit 0.10.0 → 0.12.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 (103) hide show
  1. package/README.md +21 -7
  2. package/README.zh-CN.md +22 -8
  3. package/package.json +7 -6
  4. package/src/core/AGENTS.md +2 -2
  5. package/src/core/apply.test.ts +4 -4
  6. package/src/core/apply.ts +3 -3
  7. package/src/core/character-set.test.ts +2 -3
  8. package/src/core/character-set.ts +1 -1
  9. package/src/core/ranges.test.ts +2 -1
  10. package/src/core/ranges.ts +1 -1
  11. package/src/core/regex.ts +6 -2
  12. package/src/core/replace.test.ts +51 -0
  13. package/src/core/replace.ts +10 -4
  14. package/src/core/types.ts +1 -1
  15. package/src/index.ts +9 -9
  16. package/src/integration/config-registration.test.ts +8 -10
  17. package/src/integration/fusion-dispatch.test.ts +2 -2
  18. package/src/integration/grep-errors.test.ts +3 -3
  19. package/src/integration/grep-flags.test.ts +5 -5
  20. package/src/integration/grep-js-completeness.test.ts +12 -11
  21. package/src/integration/grep-line-candidates.test.ts +5 -3
  22. package/src/integration/grep-matrix.test.ts +5 -4
  23. package/src/integration/grep-order.test.ts +4 -4
  24. package/src/integration/grep-path-matrix.test.ts +5 -4
  25. package/src/integration/grep-prefilter-coverage.test.ts +17 -5
  26. package/src/integration/grep-process-limits.test.ts +2 -4
  27. package/src/integration/grep-regex.test.ts +10 -10
  28. package/src/integration/grep-rg.test.ts +93 -48
  29. package/src/integration/grep-scan-budget.test.ts +8 -8
  30. package/src/integration/grep-translation.test.ts +8 -7
  31. package/src/integration/large-text.test.ts +5 -5
  32. package/src/integration/model-budget-lifecycle.test.ts +9 -9
  33. package/src/integration/mutation-file-types.testing.ts +4 -4
  34. package/src/integration/npm-package.test.ts +12 -10
  35. package/src/integration/npm-package.testing.ts +151 -4
  36. package/src/integration/publication-read-changes.test.ts +54 -54
  37. package/src/integration/read-changes.test.ts +4 -4
  38. package/src/integration/replace-worker-boundary.test.ts +1 -1
  39. package/src/integration/report-replay.test.ts +9 -6
  40. package/src/integration/utf8-errors.test.ts +4 -4
  41. package/src/pi/AGENTS.md +13 -12
  42. package/src/pi/action-fusion.test.ts +125 -105
  43. package/src/pi/action-fusion.testing.ts +38 -0
  44. package/src/pi/action-fusion.ts +9 -21
  45. package/src/pi/argument-diagnostics.ts +4 -3
  46. package/src/pi/argument-format.test.ts +19 -18
  47. package/src/pi/argument-validation.test.ts +281 -139
  48. package/src/pi/argument-validation.ts +21 -31
  49. package/src/pi/budgets.ts +1 -4
  50. package/src/pi/codemode.test.ts +7 -2
  51. package/src/pi/config.test.ts +2 -1
  52. package/src/pi/config.ts +8 -3
  53. package/src/pi/diagnostic-buffer.test.ts +23 -13
  54. package/src/pi/edit-tool.ts +48 -63
  55. package/src/pi/error-text.ts +7 -2
  56. package/src/pi/execute.test.ts +178 -157
  57. package/src/pi/failure-context.test.ts +5 -4
  58. package/src/pi/failure-context.ts +1 -1
  59. package/src/pi/failure-path.test.ts +37 -37
  60. package/src/pi/file-commit.test.ts +47 -19
  61. package/src/pi/file-commit.ts +36 -9
  62. package/src/pi/fusion-card.test.ts +22 -21
  63. package/src/pi/fusion-card.ts +9 -5
  64. package/src/pi/grep-candidates.test.ts +18 -20
  65. package/src/pi/grep-candidates.ts +13 -17
  66. package/src/pi/grep-matrix.test.ts +3 -3
  67. package/src/pi/grep-order.test.ts +12 -11
  68. package/src/pi/grep-output.ts +45 -17
  69. package/src/pi/grep-reread.ts +7 -2
  70. package/src/pi/grep-rg.testing.ts +70 -0
  71. package/src/pi/grep-scope.ts +10 -10
  72. package/src/pi/grep-search.ts +8 -11
  73. package/src/pi/grep-tool.ts +40 -53
  74. package/src/pi/grep.test.ts +141 -116
  75. package/src/pi/model-budgets.test.ts +2 -1
  76. package/src/pi/mutation-outcome.testing.ts +0 -1
  77. package/src/pi/mutation-result.test.ts +8 -8
  78. package/src/pi/mutation-result.ts +1 -1
  79. package/src/pi/mutation-runner.ts +10 -6
  80. package/src/pi/output-budgets.test.ts +53 -31
  81. package/src/pi/pi.test.ts +18 -13
  82. package/src/pi/read-tool.ts +13 -18
  83. package/src/pi/read.test.ts +67 -41
  84. package/src/pi/registration.test.ts +25 -19
  85. package/src/pi/render.test.ts +94 -32
  86. package/src/pi/render.ts +7 -4
  87. package/src/pi/replace-regex.ts +1 -1
  88. package/src/pi/replace-tool.ts +6 -16
  89. package/src/pi/replace.test.ts +45 -34
  90. package/src/pi/report-failure.testing.ts +9 -1
  91. package/src/pi/report-schema.ts +225 -86
  92. package/src/pi/report.test.ts +81 -87
  93. package/src/pi/report.ts +35 -22
  94. package/src/pi/result-safety.test.ts +121 -100
  95. package/src/pi/rg-process.test.ts +2 -2
  96. package/src/pi/rg-process.ts +9 -15
  97. package/src/pi/rg-regex.test.ts +13 -0
  98. package/src/pi/rg-regex.ts +2 -2
  99. package/src/pi/schema.ts +23 -0
  100. package/src/pi/tool-factories.testing.ts +59 -0
  101. package/src/pi/write-tool.ts +9 -15
  102. package/src/pi/write.test.ts +30 -31
  103. package/src/testing/run-tests.ts +1 -1
@@ -15,7 +15,8 @@
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;
@@ -147,89 +148,191 @@ const ARGUMENT_ISSUE_SCHEMA = Type.Object(
147
148
  );
148
149
  export type ArgumentIssue = Static<typeof ARGUMENT_ISSUE_SCHEMA>;
149
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
+
150
173
  /**
151
174
  * Every fact a report can carry beside the envelope, in output order: failure
152
175
  * facts first, then each tool's outcome, freshness, and the command.
153
176
  */
154
177
  const FACT_FIELDS = {
155
178
  // Argument rejection (argument-error.ts).
156
- issues: Type.Array(ARGUMENT_ISSUE_SCHEMA),
157
- omittedIssues: count("Issues omitted from the byte budget."),
158
- schemaLimited: Type.Literal(true, {
159
- description: "A native diagnostic allowance was reached; more issues may exist.",
160
- }),
161
- missing: Type.Array(Type.String(), {
162
- description: "Resolved paths that do not exist; shows where a relative path led.",
163
- }),
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
+
164
200
  // Anchor verification (failure-context.ts).
165
- failures: Type.Array(ANCHOR_FAILURE_SCHEMA),
166
- omittedFailures: count("Failures omitted from the byte budget."),
167
- candidateNeighborhoods: Type.Array(
168
- Type.Object(
169
- { lines: Type.String(), rows: Type.Array(Type.String()) },
170
- { 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
+ ),
171
215
  ),
216
+ "Inspect the observed neighborhoods before selecting an ambiguous anchor.",
217
+ ),
218
+ omittedNeighborhoodRows: modelFact(
219
+ count("Neighborhood rows omitted from the byte budget."),
220
+ "Know that candidate context is incomplete.",
172
221
  ),
173
- omittedNeighborhoodRows: count("Neighborhood rows omitted from the byte budget."),
222
+
174
223
  // 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
- }),
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
+
178
231
  // 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." }),
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
+
181
241
  // Regex workers (regex-worker.ts).
182
- timeoutMs: Type.Integer({ minimum: 1 }),
183
- exitCode: Type.Union([Type.Integer(), Type.Null()]),
184
- // read outcome; `outputLimit` below is shared with grep.
185
- pagination: Type.Object(
186
- {
187
- start: Type.Integer(),
188
- end: Type.Integer(),
189
- totalLines: Type.Integer(),
190
- nextOffset: Type.Integer(),
191
- },
192
- { additionalProperties: false },
242
+ timeoutMs: modelFact(
243
+ Type.Integer({ minimum: 1 }),
244
+ "Narrow or simplify the timed-out pattern before retrying.",
193
245
  ),
194
- lineTooLong: Type.Object(
195
- { line: Type.Integer(), limit: Type.String() },
196
- { additionalProperties: false },
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.",
197
253
  ),
198
- // grep outcome; `matches` is also replace's match count.
199
- matches: Type.Integer({ minimum: 0 }),
200
- files: Type.Integer({ minimum: 0 }),
201
- scanned: Type.Union([Type.Literal("files"), Type.Literal("all")], {
202
- description:
203
- "Without line candidates, the files searched whole: those containing text every match needs, or every file in scope.",
204
- }),
205
- matchLimit: Type.Integer({ minimum: 1, description: "The match limit that stopped the search." }),
206
- scanLimit: Type.String({
207
- description:
208
- "Bytes of files read when every file was a candidate; later files were not searched.",
209
- }),
210
- outputLimit: Type.String({ description: "The output byte budget that cut the result." }),
211
- linePreviewLimit: Type.Integer({ description: "UTF-16 units kept in a cut line preview." }),
212
- invalidUtf8: Type.Array(Type.String(), {
213
- description: "Files shown as plain previews; their rows are not edit anchors.",
214
- }),
215
- diagnostics: Type.String({ description: "Search diagnostics; results cover confirmed matches." }),
216
- literalPipe: Type.Literal(true, {
217
- description: "A literal pattern contains |, which matches only the | character.",
218
- }),
219
- // Mutation outcome.
220
- created: Type.Literal(true),
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
+ "Remove context or narrow the scope to see omitted output.",
278
+ ),
279
+ linePreviewLimit: modelFact(
280
+ Type.Integer({ description: "UTF-16 units kept in a cut line preview." }),
281
+ "Inspect the full line with a tool that supports its encoding before rewriting 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
+
221
300
  // Commit-layer observation after publication.
222
- freshness: FRESHNESS_SCHEMA,
223
- 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
+
224
310
  // Action Fusion.
225
- then_run: Type.Object(
226
- { status: COMMAND_STATUS_SCHEMA, output: opt(Type.String()) },
227
- { 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.",
228
317
  ),
229
- progressError: CAUSE_SCHEMA,
230
- } satisfies TProperties;
318
+ progressError: tuiFact(CAUSE_SCHEMA),
319
+ } as const satisfies Record<string, FactDefinition>;
231
320
 
232
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
+ ]);
233
336
 
234
337
  /** Facts of one code: the named fields, each optional unless listed as required. */
235
338
  function facts<const R extends readonly FactName[], const O extends readonly FactName[] = []>(
@@ -237,14 +340,14 @@ function facts<const R extends readonly FactName[], const O extends readonly Fac
237
340
  optional?: O,
238
341
  ) {
239
342
  const properties: TProperties = {};
240
- for (const name of required) properties[name] = FACT_FIELDS[name];
241
- for (const name of optional ?? []) properties[name] = opt(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);
242
345
  // A single mapped property set preserves required keys in TypeBox's static inference.
243
346
  return Type.Object(
244
347
  properties as {
245
348
  [K in R[number] | O[number]]: K extends R[number]
246
- ? (typeof FACT_FIELDS)[K]
247
- : ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>>;
349
+ ? FactSchema<K>
350
+ : ReturnType<typeof Type.Optional<FactSchema<K>>>;
248
351
  },
249
352
  { additionalProperties: false },
250
353
  );
@@ -288,7 +391,7 @@ export const ERROR_DEFINITIONS = {
288
391
  OVERLAPPING_EDITS: {
289
392
  facts: facts(["conflict"]),
290
393
  next: {
291
- default: "Merge them into one edit per range or position.",
394
+ default: "Merge them into one step per range or position.",
292
395
  },
293
396
  },
294
397
  NO_MATCH: {
@@ -322,7 +425,7 @@ export const ERROR_DEFINITIONS = {
322
425
  SYMLINK_UNRESOLVED: { facts: NONE },
323
426
  PUBLISH_FAILED: { facts: NONE },
324
427
  POST_PROCESS_FAILED: { facts: NONE },
325
- SEARCH_INCOMPLETE: { facts: facts(["diagnostics"], ["scanned", "scanLimit"]) },
428
+ SEARCH_INCOMPLETE: { facts: facts(["diagnostics"], ["scanLimit"]) },
326
429
  RIPGREP_FAILED: { facts: NONE },
327
430
  UNSUPPORTED_PATH: { facts: NONE },
328
431
  UNCLASSIFIED: { facts: NONE },
@@ -352,7 +455,7 @@ export const NEXT_GUIDELINE =
352
455
  "When a tool report includes next, follow it for that result; it takes precedence over these guidelines.";
353
456
 
354
457
  /** Text shared by success and failure: a file whose current anchors are unknown must be read first. */
355
- export const REREAD = "Read the file before further edits.";
458
+ const REREAD = "Read the file before further edits.";
356
459
 
357
460
  /** Once a mutation reached or may have reached the file, a retry could apply it twice. */
358
461
  export const PUBLICATION_NEXT = {
@@ -361,10 +464,26 @@ export const PUBLICATION_NEXT = {
361
464
  "The change may or may not be saved. Read the file, and repeat the change only if it is missing.",
362
465
  } as const satisfies Record<Exclude<PublicationStatus, "NOT_PUBLISHED">, string>;
363
466
 
467
+ /** The byte budget cut a grep payload: context rows go first, and without them only a narrower search helps. */
468
+ const OUTPUT_LIMIT_NEXT = {
469
+ default: "Narrow path, glob, or pattern to see the omitted output.",
470
+ contextRows: "Set context to 0 to see more of the omitted matches.",
471
+ } as const;
472
+
473
+ /** Recovery alternatives the producing layer may select for a successful result. */
474
+ export type OutcomeVariant = Exclude<keyof typeof OUTPUT_LIMIT_NEXT, "default">;
475
+
476
+ /** One recovery, or a default with the named alternatives its producer may select. */
477
+ type OutcomeNext =
478
+ | string
479
+ | ({ readonly default: string } & Partial<Record<OutcomeVariant, string>>);
480
+
364
481
  /** 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];
482
+ type OutcomeRule =
483
+ | {
484
+ [F in FactName]: readonly [fact: F, next: OutcomeNext, except?: Static<FactSchema<F>>];
485
+ }[FactName]
486
+ | readonly [fact: "publication", next: string, except?: PublicationStatus];
368
487
 
369
488
  /**
370
489
  * Recovery after a successful result, by the first fact present in this order.
@@ -373,13 +492,18 @@ type OutcomeRule = {
373
492
  export const OUTCOME_NEXT: readonly OutcomeRule[] = [
374
493
  // A file that no longer exists has no anchors to refresh.
375
494
  ["freshness", REREAD, "missing"],
495
+ [
496
+ "publication",
497
+ "The file already has this content; nothing was written, so do not repeat the call.",
498
+ "PUBLISHED",
499
+ ],
376
500
  [
377
501
  "lineTooLong",
378
502
  "Inspect the line in chunks with bash, or use replace for a known literal or regex change; a smaller limit cannot split a line.",
379
503
  ],
380
- ["pagination", "If you need more lines, set offset to pagination.nextOffset."],
504
+ ["nextOffset", "If you need more lines, set offset to nextOffset."],
381
505
  // 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."],
506
+ ["outputLimit", OUTPUT_LIMIT_NEXT],
383
507
  ["matchLimit", "If you need more matches, raise limit to include rows after the last one shown."],
384
508
  [
385
509
  "literalPipe",
@@ -389,32 +513,34 @@ export const OUTCOME_NEXT: readonly OutcomeRule[] = [
389
513
  "scanLimit",
390
514
  "Narrow path or glob, or add text every match must contain, to search the remaining files.",
391
515
  ],
392
- ["linePreviewLimit", "Read the full line before rewriting it from a partial preview."],
516
+ [
517
+ "linePreviewLimit",
518
+ "For paths listed in invalidUtf8, inspect the full line with bash; otherwise use read before rewriting a partial preview.",
519
+ ],
393
520
  ];
394
521
 
395
522
  /** The report envelope and facts, in output order; `next` is always last. */
396
523
  export const REPORT_SCHEMA = Type.Object({
397
- error: opt(Type.Union(ERROR_CODES.map((code) => Type.Literal(code)))),
524
+ error: opt(literalUnion(ERROR_CODES)),
398
525
  tool: Type.String(),
399
526
  path: opt(Type.Union([Type.String(), Type.Array(Type.String())])),
400
527
  publication: opt(PUBLICATION_SCHEMA),
401
528
  message: opt(Type.String()),
402
529
  cause: opt(CAUSE_SCHEMA),
403
530
  ...(Object.fromEntries(
404
- Object.entries(FACT_FIELDS).map(([name, schema]) => [name, opt(schema)]),
405
- ) as { [K in FactName]: ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>> }),
531
+ Object.entries(FACT_FIELDS).map(([name, definition]) => [name, opt(definition.schema)]),
532
+ ) as { [K in FactName]: ReturnType<typeof Type.Optional<FactSchema<K>>> }),
406
533
  next: opt(Type.String()),
407
534
  });
408
- type ReportFields = Omit<Static<typeof REPORT_SCHEMA>, "error"> & { error?: ErrorCode };
535
+ type ReportFields = Static<typeof REPORT_SCHEMA>;
409
536
 
410
537
  const SUCCESS_DEFINITIONS = {
411
- read: facts([], ["pagination", "outputLimit", "lineTooLong"]),
538
+ read: facts([], ["nextOffset", "outputLimit", "lineTooLong"]),
412
539
  grep: facts(
413
540
  [],
414
541
  [
415
542
  "matches",
416
543
  "files",
417
- "scanned",
418
544
  "matchLimit",
419
545
  "scanLimit",
420
546
  "outputLimit",
@@ -426,7 +552,7 @@ const SUCCESS_DEFINITIONS = {
426
552
  ),
427
553
  edit: facts([]),
428
554
  replace: facts([], ["matches"]),
429
- write: facts([], ["created"]),
555
+ write: facts([]),
430
556
  } as const;
431
557
  export type ReportTool = keyof typeof SUCCESS_DEFINITIONS;
432
558
  /** Tools whose reports carry publication, freshness, and the then_run outcome. */
@@ -435,7 +561,7 @@ export type MutationToolName = (typeof MUTATION_TOOLS)[number];
435
561
  /** Argument rejections may omit message; Pi supplies none for them. */
436
562
  const MESSAGE_OPTIONAL = "INVALID_ARGUMENTS" satisfies ErrorCode;
437
563
 
438
- const TOOL_SCHEMA = Type.Union(Object.keys(SUCCESS_DEFINITIONS).map((tool) => Type.Literal(tool)));
564
+ const TOOL_SCHEMA = literalUnion(Object.keys(SUCCESS_DEFINITIONS) as ReportTool[]);
439
565
  const COMMON_WIRE_FIELDS = {
440
566
  tool: TOOL_SCHEMA,
441
567
  path: REPORT_SCHEMA.properties.path,
@@ -475,6 +601,19 @@ const SUCCESS_SCHEMAS = Object.entries(SUCCESS_DEFINITIONS).map(([tool, schema])
475
601
  /** Closed records after the originating call supplies the tool; failure facts remain code-specific. */
476
602
  export const WIRE_REPORT_SCHEMA = Type.Union([...FAILURE_SCHEMAS, ...SUCCESS_SCHEMAS]);
477
603
 
604
+ type SuccessFactNames = {
605
+ [Tool in ReportTool]: keyof Static<(typeof SUCCESS_DEFINITIONS)[Tool]>;
606
+ }[ReportTool] &
607
+ string;
608
+ type ErrorFactNames = {
609
+ [Code in ErrorCode]: keyof Static<(typeof ERROR_DEFINITIONS)[Code]["facts"]>;
610
+ }[ErrorCode] &
611
+ string;
612
+ type MutationWireFactNames = keyof Fields<typeof MUTATION_WIRE_FIELDS> & string;
613
+ type UnusedFactNames = Exclude<FactName, SuccessFactNames | ErrorFactNames | MutationWireFactNames>;
614
+ // Compilation fails here, naming the fact, when no tool, code, or mutation field carries it.
615
+ ({}) satisfies Record<UnusedFactNames, never>;
616
+
478
617
  // Static counterparts of the per-tool and per-code wire schemas above, built from the same fields.
479
618
  type Fields<P extends TProperties> = Static<TObject<P>>;
480
619
  type Envelope = Omit<Fields<typeof COMMON_WIRE_FIELDS>, "tool">;