@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,103 @@
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
4
+ * mapping, so it must not import typebox at runtime.
5
+ * External boundaries validate cause data before restoreCause.
6
+ */
7
+ import {
8
+ errnoCode,
9
+ errorMessage,
10
+ HashlineError,
11
+ type HashlineErrorOptions,
12
+ } from "../core/errors.ts";
13
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
14
+ import type { Cause, ErrorCode } from "./report-schema.ts";
15
+
16
+ class RestoredCause extends Error {
17
+ readonly data: Cause;
18
+ constructor(data: Cause) {
19
+ super(data.message);
20
+ this.data = data;
21
+ }
22
+ }
23
+
24
+ /** Preserve validated cause data across a worker boundary without flattening it into prose. */
25
+ export function restoreCause(data: Cause | undefined): Error | undefined {
26
+ return data === undefined ? undefined : new RestoredCause(data);
27
+ }
28
+
29
+ /** One free-text value within its budget, keeping the opening and the final cause. */
30
+ export function boundedText(text: string, maxBytes: number): string {
31
+ if (Buffer.byteLength(text) <= maxBytes) return text;
32
+ const buffer = new DiagnosticBuffer(maxBytes);
33
+ buffer.append(text);
34
+ return buffer.toString();
35
+ }
36
+
37
+ function boundedCause(data: Cause, maxBytes: number): Cause {
38
+ return {
39
+ ...data,
40
+ message: boundedText(data.message, maxBytes),
41
+ ...(data.cause ? { cause: boundedCause(data.cause, maxBytes) } : {}),
42
+ ...(data.errors ? { errors: data.errors.map((inner) => boundedCause(inner, maxBytes)) } : {}),
43
+ };
44
+ }
45
+ /**
46
+ * A failure a regex worker transports: its code ties the facts that code requires.
47
+ * The host still validates every reply (regex-worker-contract.ts) before trusting it.
48
+ */
49
+ export type WorkerError = {
50
+ [C in ErrorCode]: {
51
+ readonly code: C;
52
+ readonly message: string;
53
+ readonly cause?: Cause;
54
+ } & Pick<HashlineErrorOptions<C>, "facts">;
55
+ }[ErrorCode];
56
+ type WorkerFailure = { readonly error: WorkerError };
57
+
58
+ /** Transport full failures; the receiving tool applies its model-budget snapshot. */
59
+ export function workerFailure(caught: unknown): WorkerFailure {
60
+ if (caught instanceof HashlineError) {
61
+ // Its constructor enforced the code/facts relationship; TypeScript cannot carry that link
62
+ // through the generic errorCode.
63
+ return {
64
+ error: {
65
+ code: caught.errorCode,
66
+ message: caught.message,
67
+ ...(caught.facts === undefined ? {} : { facts: caught.facts }),
68
+ ...(caught.cause === undefined ? {} : { cause: causeOf(caught.cause, Infinity) }),
69
+ } as WorkerError,
70
+ };
71
+ }
72
+ return {
73
+ error: {
74
+ code: "REGEX_WORKER_FAILED",
75
+ message: "Regex evaluation failed.",
76
+ cause: causeOf(caught, Infinity),
77
+ },
78
+ };
79
+ }
80
+
81
+ /** Preserve underlying failures; visit each native error once to avoid cycles and repeats. */
82
+ export function causeOf(
83
+ error: unknown,
84
+ maxBytes: number,
85
+ seen = new Set<unknown>(),
86
+ ): Cause | undefined {
87
+ if (error === undefined || seen.has(error)) return undefined;
88
+ seen.add(error);
89
+ if (error instanceof RestoredCause) return boundedCause(error.data, maxBytes);
90
+ const errno = errnoCode(error);
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
+ return {
97
+ ...(error instanceof HashlineError ? { error: error.errorCode } : {}),
98
+ ...(errno === undefined ? {} : { code: errno }),
99
+ message: boundedText(errorMessage(error), maxBytes),
100
+ ...(nested ? { cause: nested } : {}),
101
+ ...(errors.length ? { errors } : {}),
102
+ };
103
+ }
@@ -0,0 +1,20 @@
1
+ import assert from "node:assert/strict";
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";
5
+ import { detailsReport } from "./report.ts";
6
+
7
+ /** Assert execution failures through the returned model/TUI report, without changing tool semantics. */
8
+ export async function expectToolFailure(
9
+ pending: Promise<AgentToolResult<unknown> & { isError?: boolean }>,
10
+ code: ErrorCode,
11
+ inspect?: (report: Report) => void,
12
+ ): Promise<Report> {
13
+ const result = await pending;
14
+ assert.equal(result.isError, true);
15
+ const report = detailsReport(result.details);
16
+ assert.ok(report);
17
+ assert.equal(report.error, code);
18
+ inspect?.(report);
19
+ return report;
20
+ }
@@ -0,0 +1,524 @@
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 the call's tool and path from result 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
+ 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
+ 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
+ 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
+ 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
+ /** A then_run command's session tool result, as the TUI renders it. */
74
+ const COMMAND_RESULT_SCHEMA = Type.Object(
75
+ {
76
+ content: Type.Array(
77
+ Type.Union([
78
+ Type.Object(
79
+ {
80
+ type: Type.Literal("text"),
81
+ text: Type.String(),
82
+ textSignature: opt(Type.String()),
83
+ },
84
+ { additionalProperties: false },
85
+ ),
86
+ Type.Object(
87
+ { type: Type.Literal("image"), data: Type.String(), mimeType: Type.String() },
88
+ { additionalProperties: false },
89
+ ),
90
+ ]),
91
+ ),
92
+ details: opt(Type.Unknown()),
93
+ },
94
+ { additionalProperties: false },
95
+ );
96
+ export type CommandResult = Static<typeof COMMAND_RESULT_SCHEMA>;
97
+
98
+ /** Fusion updates cross RPC and transcript boundaries before a final tool report exists. */
99
+ export const ACTION_FUSION_PROGRESS_SCHEMA = Type.Object(
100
+ {
101
+ toolCallId: Type.String(),
102
+ commandText: Type.String(),
103
+ command: Type.Union([COMMAND_STATUS_SCHEMA, Type.Literal("waiting"), Type.Literal("running")]),
104
+ freshness: FRESHNESS_SCHEMA,
105
+ result: opt(COMMAND_RESULT_SCHEMA),
106
+ mutationCompleted: Type.Boolean(),
107
+ timing: opt(
108
+ Type.Object(
109
+ {
110
+ timeoutSeconds: Type.Number({ exclusiveMinimum: 0 }),
111
+ remainingSeconds: Type.Integer({ minimum: 0 }),
112
+ },
113
+ { additionalProperties: false },
114
+ ),
115
+ ),
116
+ },
117
+ { additionalProperties: false },
118
+ );
119
+ export type ActionFusionProgress = Static<typeof ACTION_FUSION_PROGRESS_SCHEMA>;
120
+
121
+ const ANCHOR_FAILURE_SCHEMA = Type.Object(
122
+ {
123
+ field: Type.String(),
124
+ op: Type.String(),
125
+ cited: Type.String(),
126
+ result: Type.Union([
127
+ Type.Literal("shifted"),
128
+ Type.Literal("ambiguous"),
129
+ Type.Literal("unresolved"),
130
+ ]),
131
+ search: opt(Type.Union([Type.Literal("local window"), Type.Literal("full file")])),
132
+ candidate: opt(Type.String()),
133
+ content: opt(Type.String()),
134
+ candidates: opt(Type.Array(Type.String())),
135
+ omittedCandidates: opt(Type.Integer({ minimum: 1 })),
136
+ observed: opt(Type.String()),
137
+ omitted: opt(
138
+ Type.String({ description: "Why content (shifted) or observed (unresolved) is absent." }),
139
+ ),
140
+ },
141
+ { additionalProperties: false },
142
+ );
143
+ export type AnchorFailureFact = Static<typeof ANCHOR_FAILURE_SCHEMA>;
144
+
145
+ const ARGUMENT_ISSUE_SCHEMA = Type.Object(
146
+ {
147
+ field: Type.String({
148
+ description: "Path of the field in Pi's prepared arguments; `$` for none.",
149
+ }),
150
+ reason: Type.String({ description: "What is wrong with the value; facts only." }),
151
+ fix: opt(
152
+ Type.String({ description: "How to correct it, when the reason alone does not say." }),
153
+ ),
154
+ },
155
+ { additionalProperties: false },
156
+ );
157
+ export type ArgumentIssue = Static<typeof ARGUMENT_ISSUE_SCHEMA>;
158
+
159
+ /**
160
+ * Every fact a report can carry beside the envelope, in output order: failure
161
+ * facts first, then each tool's outcome, freshness, and the command.
162
+ */
163
+ const FACT_FIELDS = {
164
+ // 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(),
172
+ // 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 },
181
+ ),
182
+ ),
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 },
199
+ ),
200
+ lineTooLong: Type.Object(
201
+ { line: Type.Integer(), limit: Type.String() },
202
+ { additionalProperties: false },
203
+ ),
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),
227
+ // Commit-layer observation after publication.
228
+ freshness: FRESHNESS_SCHEMA,
229
+ freshnessError: CAUSE_SCHEMA,
230
+ // Action Fusion.
231
+ then_run: Type.Object(
232
+ { status: COMMAND_STATUS_SCHEMA, output: opt(Type.String()) },
233
+ { additionalProperties: false },
234
+ ),
235
+ progressError: CAUSE_SCHEMA,
236
+ } satisfies TProperties;
237
+
238
+ type FactName = keyof typeof FACT_FIELDS;
239
+
240
+ /** Facts of one code: the named fields, each optional unless listed as required. */
241
+ function facts<const R extends readonly FactName[], const O extends readonly FactName[] = []>(
242
+ required: R,
243
+ optional?: O,
244
+ ) {
245
+ 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]);
248
+ // A single mapped property set preserves required keys in TypeBox's static inference.
249
+ return Type.Object(
250
+ properties as {
251
+ [K in R[number] | O[number]]: K extends R[number]
252
+ ? (typeof FACT_FIELDS)[K]
253
+ : ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>>;
254
+ },
255
+ { additionalProperties: false },
256
+ );
257
+ }
258
+ const NONE = facts([]);
259
+ const MATCHED = ["matched", "omittedMatched"] as const;
260
+
261
+ /**
262
+ * Each error code: its facts and its recovery. `next.default` is the code's
263
+ * recovery; other keys are the only alternatives a throw site may select.
264
+ * Once a mutation reached or may have reached the file, PUBLICATION_NEXT replaces them.
265
+ */
266
+ export const ERROR_DEFINITIONS = {
267
+ INVALID_ARGUMENTS: {
268
+ facts: facts(["issues"], ["omittedIssues", "schemaLimited"]),
269
+ },
270
+ OPERATION_ABORTED: { facts: NONE },
271
+ PATH_NOT_FOUND: {
272
+ facts: facts([], ["missing"]),
273
+ next: {
274
+ default: "Check the path.",
275
+ useCreate: 'Use mode "create" to create a new file.',
276
+ useGlob: "Use an existing directory as path and a filename wildcard as glob.",
277
+ },
278
+ },
279
+ FILESYSTEM_ERROR: { facts: NONE },
280
+ FILE_CHANGED: {
281
+ facts: NONE,
282
+ next: { default: "Retry the call." },
283
+ },
284
+ UNSUPPORTED_ENCODING: { facts: NONE },
285
+ UNSUPPORTED_TEXT: { facts: NONE },
286
+ INVALID_UNICODE: {
287
+ facts: NONE,
288
+ },
289
+ ANCHOR_MISMATCH: {
290
+ facts: facts(
291
+ ["failures"],
292
+ ["omittedFailures", ...MATCHED, "candidateNeighborhoods", "omittedNeighborhoodRows"],
293
+ ),
294
+ next: {
295
+ 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.",
297
+ },
298
+ },
299
+ INVALID_RANGE: {
300
+ facts: facts([], MATCHED),
301
+ },
302
+ OVERLAPPING_EDITS: {
303
+ facts: facts([], MATCHED),
304
+ next: { default: "Merge overlapping edits into one edit per range." },
305
+ },
306
+ NO_MATCH: {
307
+ facts: facts(["rule"]),
308
+ next: {
309
+ default:
310
+ "Verify the target text with read or grep; check case sensitivity or regex flags if applicable.",
311
+ },
312
+ },
313
+ OVERLAPPING_MATCHES: {
314
+ facts: facts(["rules", "offset"]),
315
+ },
316
+ REGEX_TIMEOUT: {
317
+ facts: facts(["timeoutMs"]),
318
+ },
319
+ REGEX_WORKER_FAILED: {
320
+ facts: facts([], ["exitCode"]),
321
+ },
322
+ TARGET_EXISTS: {
323
+ facts: NONE,
324
+ next: {
325
+ default:
326
+ 'Check the path and read the existing file. Use mode "overwrite" only if replacing that file is intended.',
327
+ },
328
+ },
329
+ NOT_REGULAR_FILE: { facts: NONE },
330
+ MULTIPLE_HARD_LINKS: { facts: NONE },
331
+ SYMLINK_UNRESOLVED: { facts: NONE },
332
+ PUBLISH_FAILED: {
333
+ facts: NONE,
334
+ },
335
+ POST_PROCESS_FAILED: {
336
+ facts: NONE,
337
+ },
338
+ SEARCH_INCOMPLETE: {
339
+ facts: facts(["diagnostics"], ["candidates", "scanLimit"]),
340
+ },
341
+ RIPGREP_FAILED: {
342
+ facts: facts([], ["exitCode"]),
343
+ },
344
+ UNSUPPORTED_PATH: {
345
+ facts: NONE,
346
+ },
347
+ UNCLASSIFIED: { facts: NONE },
348
+ } as const satisfies Record<
349
+ string,
350
+ { facts: TObject; next?: { default: string } & Record<string, string> }
351
+ >;
352
+
353
+ type Definitions = typeof ERROR_DEFINITIONS;
354
+ export type ErrorCode = keyof Definitions;
355
+ export const ERROR_CODES = Object.keys(ERROR_DEFINITIONS) as ErrorCode[];
356
+ /** The facts a failure of `code` carries. */
357
+ export type ErrorFacts<C extends ErrorCode> = C extends ErrorCode
358
+ ? keyof Static<Definitions[C]["facts"]> extends never
359
+ ? Readonly<Record<string, never>>
360
+ : Static<Definitions[C]["facts"]>
361
+ : never;
362
+ /** Recovery alternatives a throw site may select for `code`. */
363
+ export type NextVariant<C extends ErrorCode> = Definitions[C] extends {
364
+ next: infer N;
365
+ }
366
+ ? Exclude<keyof N, "default">
367
+ : never;
368
+
369
+ /** The guideline that ranks a report's own `next` above the general guidelines, which never restate it. */
370
+ export const NEXT_GUIDELINE =
371
+ "When a tool report includes next, follow it for that result; it takes precedence over these guidelines.";
372
+
373
+ /** Text shared by success and failure: a file whose current anchors are unknown must be read first. */
374
+ export const REREAD = "Read the file before further edits.";
375
+
376
+ /** Once a mutation reached or may have reached the file, a retry could apply it twice. */
377
+ export const PUBLICATION_NEXT = {
378
+ PUBLISHED: `The change is saved; do not repeat it. ${REREAD}`,
379
+ UNKNOWN: `The change may already be applied; do not repeat it. ${REREAD}`,
380
+ } as const satisfies Record<Exclude<PublicationStatus, "NOT_PUBLISHED">, string>;
381
+
382
+ /**
383
+ * Recovery after a successful result, by the first fact present in this order.
384
+ * A fact absent from this list needs no recovery beyond itself.
385
+ */
386
+ export const OUTCOME_NEXT = [
387
+ ["freshness", REREAD],
388
+ [
389
+ "lineTooLong",
390
+ "Inspect the line in chunks with bash, or use replace for a known literal or regex change; a smaller limit cannot split a line.",
391
+ ],
392
+ ["pagination", "If you need more lines, set offset to pagination.nextOffset."],
393
+ ["matchLimit", "If you need more matches, raise limit to include rows after the last one shown."],
394
+ [
395
+ "literalPipe",
396
+ "If you meant alternatives, pass them as a pattern array. Otherwise, keep literal matching.",
397
+ ],
398
+ [
399
+ "scanLimit",
400
+ "Narrow path or glob, or add text every match must contain, to search the remaining files.",
401
+ ],
402
+ ["outputLimit", "Narrow path, glob, or pattern to see the omitted output."],
403
+ ["linePreviewLimit", "Read the full line before rewriting it from a partial preview."],
404
+ ] as const satisfies readonly (readonly [FactName, string])[];
405
+
406
+ /** The report envelope and facts, in output order; `next` is always last. */
407
+ export const REPORT_SCHEMA = Type.Object({
408
+ error: opt(Type.Union(ERROR_CODES.map((code) => Type.Literal(code)))),
409
+ tool: Type.String(),
410
+ path: opt(Type.Union([Type.String(), Type.Array(Type.String())])),
411
+ publication: opt(PUBLICATION_SCHEMA),
412
+ stage: opt(STAGE_SCHEMA),
413
+ message: opt(Type.String()),
414
+ cause: opt(CAUSE_SCHEMA),
415
+ ...(Object.fromEntries(
416
+ Object.entries(FACT_FIELDS).map(([name, schema]) => [name, Type.Optional(schema)]),
417
+ ) as { [K in FactName]: ReturnType<typeof Type.Optional<(typeof FACT_FIELDS)[K]>> }),
418
+ next: opt(Type.String()),
419
+ });
420
+ type ReportFields = Omit<Static<typeof REPORT_SCHEMA>, "error"> & { error?: ErrorCode };
421
+
422
+ const SUCCESS_DEFINITIONS = {
423
+ read: facts([], ["pagination", "outputLimit", "lineTooLong"]),
424
+ grep: facts(
425
+ [],
426
+ [
427
+ "matches",
428
+ "files",
429
+ "candidates",
430
+ "matchLimit",
431
+ "scanLimit",
432
+ "outputLimit",
433
+ "linePreviewLimit",
434
+ "invalidUtf8",
435
+ "diagnostics",
436
+ "literalPipe",
437
+ ],
438
+ ),
439
+ edit: facts([]),
440
+ replace: facts([], ["matches"]),
441
+ write: facts([], ["created"]),
442
+ } as const;
443
+ export type ReportTool = keyof typeof SUCCESS_DEFINITIONS;
444
+ /** Tools whose reports carry publication, freshness, and the then_run outcome. */
445
+ export const MUTATION_TOOLS = ["edit", "replace", "write"] as const satisfies readonly ReportTool[];
446
+ export type MutationToolName = (typeof MUTATION_TOOLS)[number];
447
+ /** Argument rejections may omit message; Pi supplies none for them. */
448
+ const MESSAGE_OPTIONAL = "INVALID_ARGUMENTS" satisfies ErrorCode;
449
+
450
+ const TOOL_SCHEMA = Type.Union(Object.keys(SUCCESS_DEFINITIONS).map((tool) => Type.Literal(tool)));
451
+ const COMMON_WIRE_FIELDS = {
452
+ tool: TOOL_SCHEMA,
453
+ path: REPORT_SCHEMA.properties.path,
454
+ next: REPORT_SCHEMA.properties.next,
455
+ };
456
+ const MUTATION_WIRE_FIELDS = {
457
+ publication: REPORT_SCHEMA.properties.publication,
458
+ freshness: REPORT_SCHEMA.properties.freshness,
459
+ freshnessError: REPORT_SCHEMA.properties.freshnessError,
460
+ then_run: REPORT_SCHEMA.properties.then_run,
461
+ progressError: REPORT_SCHEMA.properties.progressError,
462
+ };
463
+ const FAILURE_WIRE_FIELDS = {
464
+ stage: REPORT_SCHEMA.properties.stage,
465
+ cause: REPORT_SCHEMA.properties.cause,
466
+ };
467
+ const FAILURE_SCHEMAS = ERROR_CODES.map((code) =>
468
+ Type.Object(
469
+ {
470
+ ...COMMON_WIRE_FIELDS,
471
+ ...MUTATION_WIRE_FIELDS,
472
+ ...FAILURE_WIRE_FIELDS,
473
+ error: Type.Literal(code),
474
+ message: code === MESSAGE_OPTIONAL ? opt(Type.String()) : Type.String(),
475
+ ...ERROR_DEFINITIONS[code].facts.properties,
476
+ },
477
+ { additionalProperties: false },
478
+ ),
479
+ );
480
+ const SUCCESS_SCHEMAS = Object.entries(SUCCESS_DEFINITIONS).map(([tool, schema]) =>
481
+ Type.Object(
482
+ {
483
+ ...COMMON_WIRE_FIELDS,
484
+ tool: Type.Literal(tool),
485
+ ...((MUTATION_TOOLS as readonly string[]).includes(tool) ? MUTATION_WIRE_FIELDS : {}),
486
+ ...schema.properties,
487
+ },
488
+ { additionalProperties: false },
489
+ ),
490
+ );
491
+ /** Closed records after the originating call supplies the tool; failure facts remain code-specific. */
492
+ export const WIRE_REPORT_SCHEMA = Type.Union([...FAILURE_SCHEMAS, ...SUCCESS_SCHEMAS]);
493
+
494
+ // Static counterparts of the per-tool and per-code wire schemas above, built from the same fields.
495
+ type Fields<P extends TProperties> = Static<TObject<P>>;
496
+ type Envelope = Omit<Fields<typeof COMMON_WIRE_FIELDS>, "tool">;
497
+ type MutationFields = Fields<typeof MUTATION_WIRE_FIELDS>;
498
+
499
+ /** Facts owned by one successful tool, derived from its wire schema. */
500
+ export type SuccessFacts<T extends ReportTool> = Static<(typeof SUCCESS_DEFINITIONS)[T]>;
501
+
502
+ // Absent fields stay readable as undefined without admitting another variant's facts.
503
+ type ReportVariant<T> = T & { [K in Exclude<keyof ReportFields, keyof T>]?: never };
504
+
505
+ /** A success report a tool may produce: its own facts, and mutation facts only for mutation tools. */
506
+ export type SuccessReport = {
507
+ [T in ReportTool]: ReportVariant<
508
+ Envelope & { tool: T } & (T extends MutationToolName ? MutationFields : unknown) &
509
+ SuccessFacts<T>
510
+ >;
511
+ }[ReportTool];
512
+
513
+ /** A failure report: its code's facts, with message required except where MESSAGE_OPTIONAL allows. */
514
+ export type FailureReport = {
515
+ [C in ErrorCode]: ReportVariant<
516
+ Envelope & { tool: ReportTool; error: C } & MutationFields &
517
+ Fields<typeof FAILURE_WIRE_FIELDS> &
518
+ (C extends typeof MESSAGE_OPTIONAL ? { message?: string } : { message: string }) &
519
+ Static<Definitions[C]["facts"]>
520
+ >;
521
+ }[ErrorCode];
522
+
523
+ /** A checked report retains the tool or error code that determines its facts. */
524
+ export type Report = SuccessReport | FailureReport;