@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
package/src/pi/report.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Every result of every tool states its facts in one report (report-schema.ts).
5
5
  * Layers return structured facts and never append sentences: the commit layer
6
- * owns publication, stage, and freshness; each tool owns its outcome facts;
6
+ * owns publication and freshness; each tool owns its outcome facts;
7
7
  * Action Fusion owns `then_run`. This module builds the
8
8
  * report of a success or a failure, derives its single `next`, and owns the
9
9
  * one model-facing serialization: one JSON object in schema order, without the
@@ -18,30 +18,31 @@
18
18
 
19
19
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
20
  import { Value } from "typebox/value";
21
- import { errorMessage, errnoCode, filesystemErrorCode, HashlineError } from "../core/errors.ts";
21
+ import {
22
+ errorMessage,
23
+ errnoCode,
24
+ filesystemErrorCode,
25
+ HashlineError,
26
+ pathError,
27
+ } from "../core/errors.ts";
22
28
  import { boundedText, causeOf } from "./report-cause.ts";
23
29
  import type { OutputBudgets } from "./budgets.ts";
24
- export { boundedText, causeOf } from "./report-cause.ts";
25
30
  import { cancellationError } from "./error-text.ts";
26
- import { FileMutationError } from "./file-commit.ts";
27
31
  import {
28
32
  ERROR_DEFINITIONS,
29
- MUTATION_TOOLS,
33
+ MODEL_OMITTED_FIELDS,
30
34
  OUTCOME_NEXT,
31
35
  PUBLICATION_NEXT,
32
36
  REPORT_SCHEMA,
33
37
  WIRE_REPORT_SCHEMA,
34
- type Cause,
35
- type CommandStatus,
36
38
  type ErrorCode,
37
39
  type FailureReport,
40
+ type ModelOmittedField,
38
41
  type Report,
39
42
  type ReportTool,
40
43
  type SuccessReport,
41
44
  } from "./report-schema.ts";
42
45
 
43
- export type { Report } from "./report-schema.ts";
44
-
45
46
  /** Every result's details carry its report for the TUI; Pi does not send details to the model. */
46
47
  export interface ReportDetails<TReport extends Report = Report> {
47
48
  readonly report: TReport;
@@ -51,7 +52,7 @@ type Content = AgentToolResult<unknown>["content"];
51
52
 
52
53
  /** What a report's text states: the originating call supplies its tool and path. */
53
54
  export type ReportText<R extends Report = Report> = R extends unknown
54
- ? Omit<R, "tool" | "path">
55
+ ? Omit<R, ModelOmittedField>
55
56
  : never;
56
57
 
57
58
  /** The fields a report states, in schema order; both renderers list them in this order. */
@@ -64,17 +65,24 @@ export function reportEntries(report: ReportText): [string, unknown][] {
64
65
 
65
66
  /** Serialize facts in schema order; a result never repeats its call's tool and path. */
66
67
  export function renderReport(report: ReportText): string {
67
- const entries = reportEntries(report).filter(([key]) => !ENVELOPE.has(key));
68
+ const entries = reportEntries(report).filter(
69
+ ([key]) => !MODEL_OMITTED_FIELDS.has(key as ModelOmittedField),
70
+ );
68
71
  return JSON.stringify(Object.fromEntries(entries), null, 2);
69
72
  }
70
73
 
71
74
  /** Decode a text report; the text omits its tool, which the originating call supplies. */
72
- export function decodeReport(text: string, contextTool: ReportTool): Report | undefined {
75
+ function decodeReport(text: string, contextTool: ReportTool): Report | undefined {
73
76
  if (!text.startsWith("{")) return undefined;
74
77
  try {
75
78
  let value: unknown = JSON.parse(text);
76
- if (typeof value === "object" && value !== null && !Array.isArray(value) && !("tool" in value))
77
- value = { tool: contextTool, ...value };
79
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
80
+ if ("tool" in value) {
81
+ if (value.tool !== contextTool) return undefined;
82
+ } else {
83
+ value = { tool: contextTool, ...value };
84
+ }
85
+ }
78
86
  return Value.Check(WIRE_REPORT_SCHEMA, value) ? (value as Report) : undefined;
79
87
  } catch (error) {
80
88
  if (error instanceof SyntaxError || error instanceof RangeError || error instanceof TypeError)
@@ -87,15 +95,15 @@ export function decodeReport(text: string, contextTool: ReportTool): Report | un
87
95
  * The report a result's details carry, checked once against the wire schema: details also
88
96
  * come from saved sessions and other extensions' result hooks, so their shape is unknown.
89
97
  */
90
- export function detailsReport(details: unknown): Report | undefined {
98
+ export function detailsReport(details: unknown, contextTool: ReportTool): Report | undefined {
91
99
  const report: unknown =
92
100
  typeof details === "object" && details !== null ? Reflect.get(details, "report") : undefined;
93
101
  try {
94
102
  // Hooks can introduce cycles; reject non-JSON reports before recursive schema validation.
95
103
  JSON.stringify(report);
96
- return report !== undefined && Value.Check(WIRE_REPORT_SCHEMA, report)
97
- ? (report as Report)
98
- : undefined;
104
+ if (report === undefined || !Value.Check(WIRE_REPORT_SCHEMA, report)) return undefined;
105
+ const checked = report as Report;
106
+ return checked.tool === contextTool ? checked : undefined;
99
107
  } catch (error) {
100
108
  if (error instanceof TypeError || error instanceof RangeError) return undefined;
101
109
  throw error;
@@ -104,20 +112,20 @@ export function detailsReport(details: unknown): Report | undefined {
104
112
 
105
113
  /** Tool results carry their report in details; Pi argument failures carry it as their final text block. */
106
114
  export function reportOf(
107
- result: { readonly content?: Content; readonly details?: unknown },
115
+ result: { readonly content: Content; readonly details?: unknown },
108
116
  tool: ReportTool,
109
117
  ): Report | undefined {
110
- const report = detailsReport(result.details);
118
+ const report = detailsReport(result.details, tool);
111
119
  if (report) return report;
112
- const last = result.content?.at(-1);
120
+ const last = result.content.at(-1);
113
121
  return last?.type === "text" ? decodeReport(last.text, tool) : undefined;
114
122
  }
115
123
 
116
- const ENVELOPE = new Set(["tool", "path"]);
117
-
118
124
  /** The recovery a successful result's facts call for: the first in OUTCOME_NEXT order. */
119
125
  function outcomeNext(report: Report): string | undefined {
120
- return OUTCOME_NEXT.find(([fact]) => report[fact] !== undefined)?.[1];
126
+ return OUTCOME_NEXT.find(
127
+ ([fact, , except]) => report[fact] !== undefined && report[fact] !== except,
128
+ )?.[1];
121
129
  }
122
130
 
123
131
  /**
@@ -132,8 +140,8 @@ export function reportResult<TDetails extends object | undefined>(
132
140
  const complete = Object.fromEntries(
133
141
  reportEntries({ ...report, next: outcomeNext(report) }),
134
142
  ) as SuccessReport;
135
- const stated = Object.entries(complete).some(
136
- ([key, value]) => value !== undefined && !ENVELOPE.has(key),
143
+ const stated = Object.keys(complete).some(
144
+ (key) => !MODEL_OMITTED_FIELDS.has(key as ModelOmittedField),
137
145
  );
138
146
  return {
139
147
  content:
@@ -145,9 +153,7 @@ export function reportResult<TDetails extends object | undefined>(
145
153
  }
146
154
 
147
155
  /** A failed result: the report is its entire content, flagged so Pi reports it as an error. */
148
- export function failureResult(
149
- report: FailureReport,
150
- ): AgentToolResult<ReportDetails<FailureReport>> {
156
+ function failureResult(report: FailureReport): AgentToolResult<ReportDetails<FailureReport>> {
151
157
  const complete = Object.fromEntries(reportEntries(report)) as FailureReport;
152
158
  return {
153
159
  content: [{ type: "text", text: renderReport(complete) }],
@@ -157,46 +163,28 @@ export function failureResult(
157
163
  }
158
164
 
159
165
  /** Where a failure happened, as the caller knows it. */
160
- interface FailureContext {
166
+ export interface FailureContext {
161
167
  /** The path or paths the call names, as supplied. */
162
168
  readonly path?: string | readonly string[];
163
169
  readonly signal?: AbortSignal;
164
170
  readonly budget: OutputBudgets;
165
171
  }
166
172
 
167
- /**
168
- * A mutation that did not complete, so its then_run command never ran. Action
169
- * Fusion owns the command status; the mutation's own failure stays unchanged.
170
- * It lives here because describeFailure unwraps it, and action-fusion.ts already
171
- * imports this module.
172
- */
173
- export class CommandNotRun extends Error {
174
- readonly status: Extract<CommandStatus, "skipped" | "cancelled">;
175
- readonly progressError: Cause | undefined;
176
-
177
- constructor(
178
- error: unknown,
179
- status: Extract<CommandStatus, "skipped" | "cancelled">,
180
- progressError?: Cause,
181
- ) {
182
- super(errorMessage(error), { cause: error });
183
- this.name = "CommandNotRun";
184
- this.status = status;
185
- this.progressError = progressError;
186
- }
187
- }
173
+ /** What a mutation tool states about its failure beside the classified error. */
174
+ type MutationFailureFacts = Pick<FailureReport, "publication" | "then_run" | "progressError">;
188
175
 
189
176
  function classify(error: unknown, signal: AbortSignal | undefined): HashlineError {
190
177
  if (error instanceof HashlineError) return error;
191
178
  // Pi's native tools and Node report cancellation with their own errors.
192
179
  if (signal?.aborted) return cancellationError();
180
+ const path = pathError(error);
181
+ if (path) return path;
193
182
  const code: ErrorCode = filesystemErrorCode(error) ?? "UNCLASSIFIED";
183
+ const cause = error instanceof Error ? error.cause : undefined;
194
184
  const diagnostic = errorMessage(error);
195
185
  const errno = errnoCode(error);
196
186
  const message = errno && !diagnostic.includes(errno) ? `${errno}: ${diagnostic}` : diagnostic;
197
- return new HashlineError(code, message, {
198
- cause: error instanceof Error ? error.cause : undefined,
199
- });
187
+ return new HashlineError(code, message, { cause });
200
188
  }
201
189
 
202
190
  /** The recovery of a failure: publication first, then the throw site's alternative or the code's default. */
@@ -215,40 +203,22 @@ export function describeFailure(
215
203
  tool: ReportTool,
216
204
  caught: unknown,
217
205
  context: FailureContext,
206
+ mutation?: MutationFailureFacts,
218
207
  ): FailureReport {
219
- let error = caught;
220
- let command: CommandNotRun | undefined;
221
- if (error instanceof CommandNotRun) {
222
- command = error;
223
- // The mutation's own failure, unchanged.
224
- error = error.cause;
225
- }
226
- const failure = classify(error, context.signal);
208
+ const failure = classify(caught, context.signal);
227
209
  const budget = context.budget;
228
- const mutation = MUTATION_TOOLS.some((name) => name === tool);
229
- const publication = mutation
230
- ? failure instanceof FileMutationError
231
- ? failure.publication
232
- : ("NOT_PUBLISHED" as const)
233
- : undefined;
234
- const stage = mutation
235
- ? failure instanceof FileMutationError
236
- ? failure.stage
237
- : ("prepare" as const)
238
- : undefined;
239
210
  // HashlineError's constructor ties its facts to its code; the union cannot carry that link.
240
211
  return {
241
212
  error: failure.errorCode,
242
213
  tool,
243
214
  path: context.path as Report["path"],
244
- publication,
245
- stage,
215
+ publication: mutation?.publication,
246
216
  message: boundedText(failure.message, budget.fieldBytes),
247
217
  cause: causeOf(failure.cause, budget.fieldBytes),
248
218
  ...failure.facts,
249
- then_run: command ? { status: command.status } : undefined,
250
- progressError: command?.progressError,
251
- next: failureNext(failure, publication),
219
+ then_run: mutation?.then_run,
220
+ progressError: mutation?.progressError,
221
+ next: failureNext(failure, mutation?.publication),
252
222
  } as FailureReport;
253
223
  }
254
224
 
@@ -257,29 +227,11 @@ export async function runTool<T>(
257
227
  tool: ReportTool,
258
228
  context: FailureContext,
259
229
  run: () => Promise<T>,
230
+ describe: typeof describeFailure = describeFailure,
260
231
  ): Promise<T | AgentToolResult<ReportDetails<FailureReport>>> {
261
232
  try {
262
233
  return await run();
263
234
  } catch (error) {
264
- return failureResult(describeFailure(tool, error, context));
265
- }
266
- }
267
-
268
- /**
269
- * Keep the leading entries of a fact list whose compact JSON fits `maxBytes`;
270
- * report how many were omitted. Whole entries are omitted, never cut.
271
- */
272
- export function boundedFacts<T>(
273
- entries: readonly T[],
274
- maxBytes: number,
275
- ): { kept: T[]; omitted: number } {
276
- const kept: T[] = [];
277
- let bytes = 0;
278
- for (const entry of entries) {
279
- const entryBytes = Buffer.byteLength(JSON.stringify(entry)) + 1;
280
- if (bytes + entryBytes > maxBytes) break;
281
- kept.push(entry);
282
- bytes += entryBytes;
235
+ return failureResult(describe(tool, error, context));
283
236
  }
284
- return { kept, omitted: entries.length - kept.length };
285
237
  }