@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,512 @@
1
+ /**
2
+ * The single definition of the tool report: every fact a tool result can state,
3
+ * in the order the model reads it, each error code with its facts and recovery,
4
+ * and the recovery that follows from a successful result's facts.
5
+ *
6
+ * One report describes every result of every tool, success or failure. A
7
+ * failure report is the entire result; a success report follows the tool's
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
10
+ * omits tool and path from success text; render.ts uses the full report for the TUI.
11
+ *
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.
14
+ *
15
+ * @module pi-hashline-edit/pi
16
+ */
17
+
18
+ import { Type, type Static, type TObject, type TProperties } from "typebox";
19
+
20
+ const count = (description: string) => Type.Integer({ minimum: 1, description });
21
+ const opt = Type.Optional;
22
+
23
+ /** A failure reported beneath the step that failed: our code or Node's errno, its own message, and its causes. */
24
+ export const CAUSE_SCHEMA = Type.Cyclic(
25
+ {
26
+ Cause: Type.Object(
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." })),
30
+ message: Type.String(),
31
+ cause: Type.Optional(Type.Ref("Cause")),
32
+ errors: Type.Optional(Type.Array(Type.Ref("Cause"))),
33
+ },
34
+ { additionalProperties: false },
35
+ ),
36
+ },
37
+ "Cause",
38
+ );
39
+ export type Cause = Static<typeof CAUSE_SCHEMA>;
40
+
41
+ export const PUBLICATION_SCHEMA = Type.Union([
42
+ Type.Literal("NOT_PUBLISHED"),
43
+ Type.Literal("PUBLISHED"),
44
+ Type.Literal("UNKNOWN"),
45
+ ]);
46
+ export type PublicationStatus = Static<typeof PUBLICATION_SCHEMA>;
47
+
48
+ export 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
+ export const FRESHNESS_SCHEMA = Type.Union([
56
+ Type.Literal("unchanged"),
57
+ Type.Literal("changed"),
58
+ Type.Literal("missing"),
59
+ Type.Literal("unknown"),
60
+ ]);
61
+ export type Freshness = Static<typeof FRESHNESS_SCHEMA>;
62
+
63
+ /** A then_run command's final status; `skipped` never started, `cancelled` may have. */
64
+ export const COMMAND_STATUS_SCHEMA = Type.Union([
65
+ Type.Literal("succeeded"),
66
+ Type.Literal("failed"),
67
+ Type.Literal("timeout"),
68
+ Type.Literal("cancelled"),
69
+ Type.Literal("skipped"),
70
+ ]);
71
+ export type CommandStatus = Static<typeof COMMAND_STATUS_SCHEMA>;
72
+
73
+ /** Fusion updates cross RPC and transcript boundaries before a final tool report exists. */
74
+ export const ACTION_FUSION_PROGRESS_SCHEMA = Type.Object(
75
+ {
76
+ toolCallId: Type.String(),
77
+ path: Type.String(),
78
+ commandText: Type.String(),
79
+ command: Type.Union([COMMAND_STATUS_SCHEMA, Type.Literal("waiting"), Type.Literal("running")]),
80
+ publication: PUBLICATION_SCHEMA,
81
+ freshness: FRESHNESS_SCHEMA,
82
+ output: Type.String(),
83
+ mutationCompleted: Type.Boolean(),
84
+ timing: opt(
85
+ Type.Object(
86
+ {
87
+ timeoutSeconds: Type.Number({ exclusiveMinimum: 0 }),
88
+ remainingSeconds: Type.Integer({ minimum: 0 }),
89
+ },
90
+ { additionalProperties: false },
91
+ ),
92
+ ),
93
+ },
94
+ { additionalProperties: false },
95
+ );
96
+ export type ActionFusionProgress = Static<typeof ACTION_FUSION_PROGRESS_SCHEMA>;
97
+
98
+ const ANCHOR_FAILURE_SCHEMA = Type.Object(
99
+ {
100
+ field: Type.String(),
101
+ op: Type.String(),
102
+ cited: Type.String(),
103
+ result: Type.Union([
104
+ Type.Literal("shifted"),
105
+ Type.Literal("ambiguous"),
106
+ Type.Literal("unresolved"),
107
+ ]),
108
+ search: opt(Type.Union([Type.Literal("local window"), Type.Literal("full file")])),
109
+ candidate: opt(Type.String()),
110
+ content: opt(Type.String()),
111
+ contentOmitted: opt(Type.String()),
112
+ candidates: opt(Type.Array(Type.String())),
113
+ omittedCandidates: opt(Type.Integer({ minimum: 1 })),
114
+ observed: opt(Type.String()),
115
+ observedOmitted: opt(Type.String()),
116
+ },
117
+ { additionalProperties: false },
118
+ );
119
+ export type AnchorFailureFact = Static<typeof ANCHOR_FAILURE_SCHEMA>;
120
+
121
+ export const ARGUMENT_ISSUE_SCHEMA = Type.Object(
122
+ {
123
+ field: Type.String({
124
+ description: "Path of the field in Pi's prepared arguments; `$` for none.",
125
+ }),
126
+ reason: Type.String({ description: "What is wrong with the value; facts only." }),
127
+ fix: opt(
128
+ Type.String({ description: "How to correct it, when the reason alone does not say." }),
129
+ ),
130
+ },
131
+ { additionalProperties: false },
132
+ );
133
+ export type ArgumentIssue = Static<typeof ARGUMENT_ISSUE_SCHEMA>;
134
+
135
+ /**
136
+ * Every fact a report can carry beside the envelope, in output order: failure
137
+ * facts first, then each tool's outcome, freshness, the command, and forget.
138
+ */
139
+ export const FACT_FIELDS = {
140
+ // Argument rejection (argument-error.ts).
141
+ issues: Type.Array(ARGUMENT_ISSUE_SCHEMA),
142
+ omittedIssues: count("Issues omitted from the byte budget."),
143
+ schemaLimited: Type.Literal(true, {
144
+ description: "A native diagnostic allowance was reached; more issues may exist.",
145
+ }),
146
+ // A missing path among several (grep).
147
+ missing: Type.String(),
148
+ // Anchor verification (failure-context.ts).
149
+ failures: Type.Array(ANCHOR_FAILURE_SCHEMA),
150
+ omittedFailures: count("Failures omitted from the byte budget."),
151
+ matched: Type.Array(Type.String()),
152
+ omittedMatched: count("Matched anchors omitted from the byte budget."),
153
+ candidateNeighborhoods: Type.Array(
154
+ Type.Object(
155
+ { lines: Type.String(), rows: Type.Array(Type.String()) },
156
+ { additionalProperties: false },
157
+ ),
158
+ ),
159
+ omittedNeighborhoodRows: count("Neighborhood rows omitted from the byte budget."),
160
+ // Replacement rules (core/replace.ts, replace-regex.ts).
161
+ rule: Type.Integer({ minimum: 0 }),
162
+ rules: Type.Array(Type.Integer({ minimum: 0 })),
163
+ offset: Type.Integer({ minimum: 0 }),
164
+ timeoutMs: Type.Integer({ minimum: 1 }),
165
+ exitCode: Type.Union([Type.Integer(), Type.Null()]),
166
+ // read outcome.
167
+ pagination: Type.Object(
168
+ {
169
+ start: Type.Integer(),
170
+ end: Type.Integer(),
171
+ totalLines: Type.Integer(),
172
+ nextOffset: Type.Integer(),
173
+ },
174
+ { additionalProperties: false },
175
+ ),
176
+ truncatedAt: Type.String({ description: "The byte budget that stopped the output." }),
177
+ lineTooLong: Type.Object(
178
+ { line: Type.Integer(), limit: Type.String() },
179
+ { additionalProperties: false },
180
+ ),
181
+ // grep outcome; `matches` is also replace's match count.
182
+ matches: Type.Integer({ minimum: 0 }),
183
+ files: Type.Integer({ minimum: 0 }),
184
+ candidates: Type.Union([Type.Literal("files"), Type.Literal("all")], {
185
+ description:
186
+ "Without line candidates, the files searched whole: those containing text every match needs, or every file in scope.",
187
+ }),
188
+ matchLimit: Type.Integer({ minimum: 1, description: "The match limit that stopped the search." }),
189
+ scanLimit: Type.String({
190
+ description:
191
+ "Bytes of files read when every file was a candidate; later files were not searched.",
192
+ }),
193
+ outputLimit: Type.String({ description: "Pi's output byte limit that cut the result." }),
194
+ linePreviewLimit: Type.Integer({ description: "UTF-16 units kept in a cut line preview." }),
195
+ invalidUtf8: Type.Array(Type.String(), {
196
+ description: "Files shown as plain previews; their rows are not edit anchors.",
197
+ }),
198
+ diagnostics: Type.String({ description: "Search diagnostics; results cover confirmed matches." }),
199
+ // Mutation outcome.
200
+ created: Type.Literal(true),
201
+ // Commit-layer observation after publication.
202
+ freshness: FRESHNESS_SCHEMA,
203
+ freshnessError: CAUSE_SCHEMA,
204
+ // Action Fusion.
205
+ then_run: Type.Object(
206
+ { status: COMMAND_STATUS_SCHEMA, output: opt(Type.String()) },
207
+ { additionalProperties: false },
208
+ ),
209
+ progressError: CAUSE_SCHEMA,
210
+ // forget.
211
+ forgotten: Type.Array(Type.String()),
212
+ notForgettable: Type.Array(Type.String(), {
213
+ description: "Named ids that are not tagged results of the previous response.",
214
+ }),
215
+ resultId: Type.String({ description: "Id to pass to forget." }),
216
+ forgetScope: Type.String(),
217
+ contentForgotten: Type.Literal(true),
218
+ } satisfies TProperties;
219
+
220
+ type FactName = keyof typeof FACT_FIELDS;
221
+
222
+ /** Facts of one code: the named fields, each optional unless listed as required. */
223
+ function facts<const R extends readonly FactName[], const O extends readonly FactName[] = []>(
224
+ required: R,
225
+ optional?: O,
226
+ ) {
227
+ const properties: TProperties = {};
228
+ for (const name of required) properties[name] = FACT_FIELDS[name];
229
+ for (const name of optional ?? []) properties[name] = Type.Optional(FACT_FIELDS[name]);
230
+ // A single mapped property set preserves required keys in TypeBox's static inference.
231
+ return Type.Object(
232
+ properties as {
233
+ [K in R[number] | O[number]]: K extends R[number]
234
+ ? (typeof FACT_FIELDS)[K]
235
+ : ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>>;
236
+ },
237
+ { additionalProperties: false },
238
+ );
239
+ }
240
+ const NONE = facts([]);
241
+ const MATCHED = ["matched", "omittedMatched"] as const;
242
+
243
+ /** Text shared by forget's failure and partial success: a later response cannot forget them either. */
244
+ const NOT_FORGETTABLE_NEXT =
245
+ "Do not call forget again for the notForgettable ids; those results stay in context.";
246
+
247
+ /**
248
+ * Each error code: its facts and its recovery. `next.default` is the code's
249
+ * recovery; other keys are the only alternatives a throw site may select.
250
+ * Once a mutation reached or may have reached the file, PUBLICATION_NEXT replaces them.
251
+ */
252
+ export const ERROR_DEFINITIONS = {
253
+ INVALID_ARGUMENTS: {
254
+ facts: facts(["issues"], ["omittedIssues", "schemaLimited"]),
255
+ },
256
+ OPERATION_ABORTED: { facts: NONE },
257
+ PATH_NOT_FOUND: {
258
+ facts: facts([], ["missing"]),
259
+ next: {
260
+ default: "Check the path.",
261
+ useCreate: 'Use mode "create" to create a new file.',
262
+ useGlob: "Use an existing directory as path and a filename wildcard as glob.",
263
+ },
264
+ },
265
+ FILESYSTEM_ERROR: { facts: NONE },
266
+ FILE_CHANGED: {
267
+ facts: NONE,
268
+ next: { default: "Retry the call." },
269
+ },
270
+ UNSUPPORTED_ENCODING: { facts: NONE },
271
+ UNSUPPORTED_TEXT: { facts: NONE },
272
+ INVALID_UNICODE: {
273
+ facts: NONE,
274
+ },
275
+ ANCHOR_MISMATCH: {
276
+ facts: facts(
277
+ ["failures"],
278
+ ["omittedFailures", ...MATCHED, "candidateNeighborhoods", "omittedNeighborhoodRows"],
279
+ ),
280
+ next: {
281
+ default:
282
+ "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.",
283
+ },
284
+ },
285
+ INVALID_RANGE: {
286
+ facts: facts([], MATCHED),
287
+ },
288
+ OVERLAPPING_EDITS: {
289
+ facts: facts([], MATCHED),
290
+ next: { default: "Merge overlapping edits into one edit per range." },
291
+ },
292
+ NO_MATCH: {
293
+ facts: facts(["rule"]),
294
+ next: {
295
+ default:
296
+ "Verify the target text with read or grep; check case sensitivity or regex flags if applicable.",
297
+ },
298
+ },
299
+ OVERLAPPING_MATCHES: {
300
+ facts: facts(["rules", "offset"]),
301
+ },
302
+ REGEX_TIMEOUT: {
303
+ facts: facts(["timeoutMs"]),
304
+ },
305
+ REGEX_WORKER_FAILED: {
306
+ facts: facts([], ["exitCode"]),
307
+ },
308
+ TARGET_EXISTS: {
309
+ facts: NONE,
310
+ next: { default: 'Use mode "overwrite" to replace the existing file.' },
311
+ },
312
+ NOT_REGULAR_FILE: { facts: NONE },
313
+ MULTIPLE_HARD_LINKS: { facts: NONE },
314
+ SYMLINK_UNRESOLVED: { facts: NONE },
315
+ PUBLISH_FAILED: {
316
+ facts: NONE,
317
+ },
318
+ POST_PROCESS_FAILED: {
319
+ facts: NONE,
320
+ },
321
+ SEARCH_INCOMPLETE: {
322
+ facts: facts(["diagnostics"], ["candidates", "scanLimit"]),
323
+ },
324
+ RIPGREP_FAILED: {
325
+ facts: facts([], ["exitCode"]),
326
+ },
327
+ UNSUPPORTED_PATH: {
328
+ facts: NONE,
329
+ },
330
+ NOT_FORGETTABLE: {
331
+ facts: facts(["notForgettable"]),
332
+ next: { default: NOT_FORGETTABLE_NEXT },
333
+ },
334
+ UNCLASSIFIED: { facts: NONE },
335
+ } as const satisfies Record<
336
+ string,
337
+ { facts: TObject; next?: { default: string } & Record<string, string> }
338
+ >;
339
+
340
+ type Definitions = typeof ERROR_DEFINITIONS;
341
+ export type ErrorCode = keyof Definitions;
342
+ export const ERROR_CODES = Object.keys(ERROR_DEFINITIONS) as ErrorCode[];
343
+ /** The facts a failure of `code` carries. */
344
+ export type ErrorFacts<C extends ErrorCode> = C extends ErrorCode
345
+ ? keyof Static<Definitions[C]["facts"]> extends never
346
+ ? Readonly<Record<string, never>>
347
+ : Static<Definitions[C]["facts"]>
348
+ : never;
349
+ /** Recovery alternatives a throw site may select for `code`. */
350
+ export type NextVariant<C extends ErrorCode> = Definitions[C] extends {
351
+ next: infer N;
352
+ }
353
+ ? Exclude<keyof N, "default">
354
+ : never;
355
+
356
+ /** The guideline that ranks a report's own `next` above the general guidelines, which never restate it. */
357
+ export const NEXT_GUIDELINE =
358
+ "When a tool report includes next, follow it for that result; it takes precedence over these guidelines.";
359
+
360
+ /** Text shared by success and failure: a file whose current anchors are unknown must be read first. */
361
+ export const REREAD = "Read the file before further edits.";
362
+
363
+ /** Once a mutation reached or may have reached the file, a retry could apply it twice. */
364
+ export const PUBLICATION_NEXT = {
365
+ PUBLISHED: `The change is saved; do not repeat it. ${REREAD}`,
366
+ UNKNOWN: `The change may already be applied; do not repeat it. ${REREAD}`,
367
+ } as const satisfies Record<Exclude<PublicationStatus, "NOT_PUBLISHED">, string>;
368
+
369
+ /**
370
+ * Recovery after a successful result, by the first fact present in this order.
371
+ * A fact absent from this list needs no recovery beyond itself.
372
+ */
373
+ export const OUTCOME_NEXT = [
374
+ ["freshness", REREAD],
375
+ [
376
+ "lineTooLong",
377
+ "Inspect the line in chunks with bash, or use replace for a known literal or regex change; a smaller limit cannot split a line.",
378
+ ],
379
+ ["pagination", "Continue with offset set to pagination.nextOffset."],
380
+ ["matchLimit", "Raise limit or refine the pattern for more matches."],
381
+ [
382
+ "scanLimit",
383
+ "Narrow path or glob, or add text every match must contain, to search the remaining files.",
384
+ ],
385
+ ["outputLimit", "Narrow path, glob, or pattern to see the omitted output."],
386
+ ["linePreviewLimit", "Read the full line before rewriting it from a partial preview."],
387
+ ["notForgettable", NOT_FORGETTABLE_NEXT],
388
+ ["contentForgotten", "Rerun the call to see it again."],
389
+ ] as const satisfies readonly (readonly [FactName, string])[];
390
+
391
+ /** The report envelope and facts, in output order; `next` is always last. */
392
+ export const REPORT_SCHEMA = Type.Object({
393
+ error: opt(Type.Union(ERROR_CODES.map((code) => Type.Literal(code)))),
394
+ tool: Type.String(),
395
+ path: opt(Type.Union([Type.String(), Type.Array(Type.String())])),
396
+ publication: opt(PUBLICATION_SCHEMA),
397
+ stage: opt(STAGE_SCHEMA),
398
+ message: opt(Type.String()),
399
+ cause: opt(CAUSE_SCHEMA),
400
+ ...(Object.fromEntries(
401
+ Object.entries(FACT_FIELDS).map(([name, schema]) => [name, Type.Optional(schema)]),
402
+ ) as { [K in FactName]: ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>> }),
403
+ next: opt(Type.String()),
404
+ });
405
+ type ReportFields = Omit<Static<typeof REPORT_SCHEMA>, "error"> & { error?: ErrorCode };
406
+
407
+ const SUCCESS_DEFINITIONS = {
408
+ read: facts([], ["pagination", "truncatedAt", "lineTooLong", "resultId", "contentForgotten"]),
409
+ grep: facts(
410
+ [],
411
+ [
412
+ "matches",
413
+ "files",
414
+ "candidates",
415
+ "matchLimit",
416
+ "scanLimit",
417
+ "outputLimit",
418
+ "linePreviewLimit",
419
+ "invalidUtf8",
420
+ "diagnostics",
421
+ "resultId",
422
+ "contentForgotten",
423
+ ],
424
+ ),
425
+ edit: facts([]),
426
+ replace: facts([], ["matches"]),
427
+ write: facts([], ["created"]),
428
+ forget: facts(["forgotten"], ["notForgettable"]),
429
+ codemode: facts([], ["resultId", "forgetScope", "contentForgotten"]),
430
+ } as const;
431
+ export type ReportTool = keyof typeof SUCCESS_DEFINITIONS;
432
+ /** Tools whose reports carry publication, freshness, and the then_run outcome. */
433
+ export const MUTATION_TOOLS = ["edit", "replace", "write"] as const satisfies readonly ReportTool[];
434
+ export type MutationToolName = (typeof MUTATION_TOOLS)[number];
435
+ /** Argument rejections may omit message; Pi supplies none for them. */
436
+ const MESSAGE_OPTIONAL = "INVALID_ARGUMENTS" satisfies ErrorCode;
437
+
438
+ const TOOL_SCHEMA = Type.Union(Object.keys(SUCCESS_DEFINITIONS).map((tool) => Type.Literal(tool)));
439
+ const COMMON_WIRE_FIELDS = {
440
+ tool: TOOL_SCHEMA,
441
+ path: REPORT_SCHEMA.properties.path,
442
+ next: REPORT_SCHEMA.properties.next,
443
+ };
444
+ const MUTATION_WIRE_FIELDS = {
445
+ publication: REPORT_SCHEMA.properties.publication,
446
+ freshness: REPORT_SCHEMA.properties.freshness,
447
+ freshnessError: REPORT_SCHEMA.properties.freshnessError,
448
+ then_run: REPORT_SCHEMA.properties.then_run,
449
+ progressError: REPORT_SCHEMA.properties.progressError,
450
+ };
451
+ const FAILURE_WIRE_FIELDS = {
452
+ stage: REPORT_SCHEMA.properties.stage,
453
+ cause: REPORT_SCHEMA.properties.cause,
454
+ };
455
+ const FAILURE_SCHEMAS = ERROR_CODES.map((code) =>
456
+ Type.Object(
457
+ {
458
+ ...COMMON_WIRE_FIELDS,
459
+ ...MUTATION_WIRE_FIELDS,
460
+ ...FAILURE_WIRE_FIELDS,
461
+ error: Type.Literal(code),
462
+ message: code === MESSAGE_OPTIONAL ? opt(Type.String()) : Type.String(),
463
+ ...ERROR_DEFINITIONS[code].facts.properties,
464
+ },
465
+ { additionalProperties: false },
466
+ ),
467
+ );
468
+ const SUCCESS_SCHEMAS = Object.entries(SUCCESS_DEFINITIONS).map(([tool, schema]) =>
469
+ Type.Object(
470
+ {
471
+ ...COMMON_WIRE_FIELDS,
472
+ tool: Type.Literal(tool),
473
+ ...((MUTATION_TOOLS as readonly string[]).includes(tool) ? MUTATION_WIRE_FIELDS : {}),
474
+ ...schema.properties,
475
+ },
476
+ { additionalProperties: false },
477
+ ),
478
+ );
479
+ /** Closed records after call context supplies a missing success tool; failure facts remain code-specific. */
480
+ export const WIRE_REPORT_SCHEMA = Type.Union([...FAILURE_SCHEMAS, ...SUCCESS_SCHEMAS]);
481
+
482
+ // Static counterparts of the per-tool and per-code wire schemas above, built from the same fields.
483
+ type Fields<P extends TProperties> = Static<TObject<P>>;
484
+ type Envelope = Omit<Fields<typeof COMMON_WIRE_FIELDS>, "tool">;
485
+ type MutationFields = Fields<typeof MUTATION_WIRE_FIELDS>;
486
+
487
+ /** Facts owned by one successful tool, derived from its wire schema. */
488
+ export type SuccessFacts<T extends ReportTool> = Static<(typeof SUCCESS_DEFINITIONS)[T]>;
489
+
490
+ // Absent fields stay readable as undefined without admitting another variant's facts.
491
+ type ReportVariant<T> = T & { [K in Exclude<keyof ReportFields, keyof T>]?: never };
492
+
493
+ /** A success report a tool may produce: its own facts, and mutation facts only for mutation tools. */
494
+ export type SuccessReport = {
495
+ [T in ReportTool]: ReportVariant<
496
+ Envelope & { tool: T } & (T extends MutationToolName ? MutationFields : unknown) &
497
+ SuccessFacts<T>
498
+ >;
499
+ }[ReportTool];
500
+
501
+ /** A failure report: its code's facts, with message required except where MESSAGE_OPTIONAL allows. */
502
+ export type FailureReport = {
503
+ [C in ErrorCode]: ReportVariant<
504
+ Envelope & { tool: ReportTool; error: C } & MutationFields &
505
+ Fields<typeof FAILURE_WIRE_FIELDS> &
506
+ (C extends typeof MESSAGE_OPTIONAL ? { message?: string } : { message: string }) &
507
+ Static<Definitions[C]["facts"]>
508
+ >;
509
+ }[ErrorCode];
510
+
511
+ /** A checked report retains the tool or error code that determines its facts. */
512
+ export type Report = SuccessReport | FailureReport;