@criogaid/pi-hashline-edit 0.7.0 → 0.9.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 (118) hide show
  1. package/README.md +76 -220
  2. package/README.zh-CN.md +166 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +171 -133
  6. package/src/core/apply.ts +34 -31
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +49 -9
  14. package/src/core/ranges.ts +15 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +6 -8
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +18 -10
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +132 -92
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +4 -5
  34. package/src/integration/model-budget-lifecycle.test.ts +26 -8
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +2 -2
  37. package/src/integration/npm-package.testing.ts +7 -33
  38. package/src/integration/publication-read-changes.test.ts +60 -28
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +3 -3
  42. package/src/integration/utf8-errors.test.ts +3 -3
  43. package/src/pi/AGENTS.md +13 -14
  44. package/src/pi/action-fusion.test.ts +75 -220
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +35 -186
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +25 -38
  52. package/src/pi/argument-validation.test.ts +446 -420
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +175 -121
  60. package/src/pi/execute.test.ts +170 -227
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +13 -10
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +271 -170
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +27 -18
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +7 -6
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +106 -67
  92. package/src/pi/render.test.ts +239 -109
  93. package/src/pi/render.ts +42 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +29 -27
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +60 -45
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +186 -131
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
package/src/pi/render.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
19
19
  import { Text, type Component } from "@earendil-works/pi-tui";
20
20
  import type { ActionFusionProgress } from "./action-fusion.ts";
21
+ import type { MutationToolName, ReportTool } from "./report-schema.ts";
21
22
  import { renderReport, reportEntries, reportOf, type Report, detailsReport } from "./report.ts";
22
23
 
23
24
  /** Max diff lines shown when a result is rendered collapsed. */
@@ -56,7 +57,7 @@ export interface MutationRenderState {
56
57
  }
57
58
 
58
59
  /** Count added/removed lines in a pi-format diff (`+N content` / `-N content` / ` N content`). */
59
- export function countDiffLines(diff: string): DiffCounts {
60
+ function countDiffLines(diff: string): DiffCounts {
60
61
  let added = 0;
61
62
  let removed = 0;
62
63
  for (const line of diff.split("\n")) {
@@ -66,6 +67,16 @@ export function countDiffLines(diff: string): DiffCounts {
66
67
  return { added, removed };
67
68
  }
68
69
 
70
+ /**
71
+ * The call header's path. Arguments stream in the provider's key order, so the
72
+ * path may arrive after the operations; until then it shows Pi's `...` placeholder.
73
+ */
74
+ export function formatHeaderPath(path: unknown, theme: Theme): string {
75
+ return typeof path === "string" && path
76
+ ? theme.fg("accent", path)
77
+ : theme.fg("toolOutput", "...");
78
+ }
79
+
69
80
  /** Format `+N -N` with the theme's diff colors for the tool call header. */
70
81
  export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
71
82
  return ` ${theme.fg("toolDiffAdded", `+${counts.added}`)} ${theme.fg("toolDiffRemoved", `-${counts.removed}`)}`;
@@ -87,7 +98,7 @@ export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
87
98
  * synchronously (not re-entrant) and the outer pass then re-adds the result
88
99
  * component after the nested one — the diff renders twice.
89
100
  */
90
- export function publishDiffCounts(
101
+ function publishDiffCounts(
91
102
  diff: string | undefined,
92
103
  context: { state?: MutationRenderState },
93
104
  refreshHeader: (counts: DiffCounts) => void,
@@ -168,7 +179,7 @@ function argumentLines(report: Report, theme: Theme): string[] {
168
179
  for (const { field, reason, fix } of report.issues ?? []) {
169
180
  const [first, ...rest] = reason.split("\n");
170
181
  lines.push(`${theme.fg("accent", theme.bold(field))}: ${theme.fg("error", first)}`);
171
- lines.push(...rest.map((line) => ` ${theme.fg("error", line)}`));
182
+ for (const line of rest) lines.push(` ${theme.fg("error", line)}`);
172
183
  if (fix) lines.push(` ${theme.fg("dim", fix)}`);
173
184
  }
174
185
  return lines;
@@ -202,35 +213,40 @@ export function reportLines(
202
213
  ),
203
214
  );
204
215
  if (report.message !== undefined)
205
- lines.push(...report.message.split("\n").map((line) => theme.fg("error", line)));
216
+ for (const line of report.message.split("\n")) lines.push(theme.fg("error", line));
206
217
  }
207
218
  for (const [key, value] of reportEntries(report)) {
208
219
  if (ENVELOPE_FIELDS.includes(key) || shown.has(key)) continue;
209
- lines.push(...factLines(key, value, theme));
220
+ for (const line of factLines(key, value, theme)) lines.push(line);
210
221
  }
211
222
  if (report.next !== undefined) lines.push(`${theme.fg("dim", "next:")} ${report.next}`);
212
223
  return lines;
213
224
  }
214
225
 
215
- /** A result without its report block, for renderers that show every content block. */
216
- export function withoutReport<T extends Pick<AgentToolResult<unknown>, "content" | "details">>(
217
- result: T,
218
- ): T {
226
+ /**
227
+ * A successful result's checked report and the content before its report block. Renderers
228
+ * read reports only here or through renderToolError, so the facts a card shows and the
229
+ * block it strips come from one check; content that is not our report stays.
230
+ */
231
+ export function splitReport(result: Pick<AgentToolResult<unknown>, "content" | "details">): {
232
+ content: AgentToolResult<unknown>["content"];
233
+ report: Report | undefined;
234
+ } {
219
235
  const report = detailsReport(result.details);
220
236
  const last = result.content.at(-1);
221
- if (!report || last?.type !== "text") return result;
222
- if (last.text !== renderReport(report)) return result;
223
- return { ...result, content: result.content.slice(0, -1) };
237
+ const ours = report !== undefined && last?.type === "text" && last.text === renderReport(report);
238
+ return { content: ours ? result.content.slice(0, -1) : result.content, report };
224
239
  }
225
240
 
226
241
  /** Render a failure from its report; text that is not ours keeps its original lines. */
227
242
  export function renderToolError(
228
243
  result: Pick<AgentToolResult<unknown>, "content"> &
229
244
  Partial<Pick<AgentToolResult<unknown>, "details">>,
245
+ tool: ReportTool,
230
246
  theme: Theme,
231
247
  expanded: boolean,
232
248
  ): Text {
233
- const report = reportOf(result);
249
+ const report = reportOf(result, tool);
234
250
  const lines = report
235
251
  ? reportLines(report, theme)
236
252
  : result.content.flatMap((block) =>
@@ -248,9 +264,9 @@ const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
248
264
  export function renderMutationResult<TArgs>(
249
265
  result: AgentToolResult<
250
266
  | {
251
- displayDiff?: string;
267
+ diff?: string;
252
268
  report?: Report;
253
- actionFusion?: Partial<Pick<ActionFusionProgress, "publication" | "mutationCompleted">>;
269
+ actionFusion?: Partial<Pick<ActionFusionProgress, "mutationCompleted">>;
254
270
  }
255
271
  | undefined
256
272
  >,
@@ -259,20 +275,24 @@ export function renderMutationResult<TArgs>(
259
275
  context: { isError: boolean; args: TArgs; state?: MutationRenderState },
260
276
  pending: string,
261
277
  header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
278
+ tool: MutationToolName,
262
279
  ): Text {
263
280
  if (isPartial && result.details?.actionFusion?.mutationCompleted !== true)
264
281
  return new Text(theme.fg("warning", pending), 0, 0);
265
- if (context.isError) return renderToolError(result, theme, expanded);
266
- const diff = result.details?.displayDiff;
282
+ if (context.isError) return renderToolError(result, tool, theme, expanded);
283
+ const diff = result.details?.diff;
267
284
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
268
285
  publishDiffCounts(diff, context, (counts) => {
269
286
  context.state?.callText?.setText(header(context.args, theme, counts));
270
287
  });
271
- const report = result.details?.report;
288
+ const { report } = splitReport(result);
272
289
  const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
273
- // Only identical content produces no diff.
274
- const body = diff
275
- ? renderDiffPreview(diff, expanded, theme)
276
- : theme.fg("success", "No net change");
290
+ const emptyDiff =
291
+ report?.publication === "NOT_PUBLISHED"
292
+ ? "No net change"
293
+ : report?.publication === "PUBLISHED"
294
+ ? "Updated; no logical line diff"
295
+ : "No diff available";
296
+ const body = diff ? renderDiffPreview(diff, expanded, theme) : theme.fg("success", emptyDiff);
277
297
  return new Text([body, ...facts].join("\n"), 0, 0);
278
298
  }
@@ -1,17 +1,15 @@
1
1
  /** Run a validated replacement batch through the shared isolated regex lifecycle. */
2
- import type { applyReplacements, Replacement } from "../core/replace.ts";
2
+ import type { Replacement, ReplacementResult } from "../core/replace-schema.ts";
3
3
  import { decodeWorkerReply, type ReplacementRequest } from "./replace-worker-contract.ts";
4
4
  import { withRegexWorker } from "./regex-worker.ts";
5
5
 
6
- type ReplaceResult = ReturnType<typeof applyReplacements>;
7
-
8
6
  export function runRegexReplacements(
9
7
  source: string,
10
8
  rules: readonly Replacement[],
11
9
  timeoutMs: number,
12
10
  signal: AbortSignal | undefined,
13
- ): Promise<ReplaceResult> {
14
- return withRegexWorker<ReplacementRequest, ReplaceResult, ReplaceResult>(
11
+ ): Promise<ReplacementResult> {
12
+ return withRegexWorker<ReplacementRequest, ReplacementResult, ReplacementResult>(
15
13
  new URL("./replace-worker.mjs", import.meta.url),
16
14
  decodeWorkerReply,
17
15
  timeoutMs,
@@ -9,7 +9,8 @@
9
9
  * lines belongs to `edit`.
10
10
  *
11
11
  * - Both modes match the shared LF view and restore original line separators.
12
- * - Literal mode keeps `$` verbatim; regex mode expands JavaScript replacement tokens.
12
+ * - Each rule states `literal`: literal mode keeps `$` verbatim; regex mode expands
13
+ * JavaScript replacement tokens.
13
14
  * - `flags` adds regex flags in either mode; `g` is always forced so every
14
15
  * occurrence is replaced. `i` (case-insensitive), `m` (per-line ^/$),
15
16
  * `s` (dotall), `u` (unicode) all work.
@@ -32,8 +33,8 @@ import {
32
33
  import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
33
34
  import { Type, type Static } from "typebox";
34
35
  import { applyReplacements } from "../core/replace.ts";
35
- import { buildRegex } from "../core/regex.ts";
36
- import { REPLACEMENTS_SCHEMA, REGEX_FLAGS_PATTERN } from "../core/replace-schema.ts";
36
+ import { checkRegexArguments } from "../core/regex.ts";
37
+ import { REPLACEMENTS_SCHEMA } from "../core/replace-schema.ts";
37
38
  import { runRegexReplacements } from "./replace-regex.ts";
38
39
  import { unwritableTextError } from "../core/text.ts";
39
40
  import {
@@ -45,6 +46,7 @@ import {
45
46
  import type { HashlineEditConfig } from "./config.ts";
46
47
  import {
47
48
  formatDiffCounts,
49
+ formatHeaderPath,
48
50
  renderMutationCall,
49
51
  renderMutationResult,
50
52
  type DiffCounts,
@@ -57,7 +59,6 @@ import {
57
59
  type TextMutationDetails,
58
60
  } from "./mutation-runner.ts";
59
61
  import type { MutationResultDetails } from "./mutation-result.ts";
60
- import { errorMessage } from "../core/errors.ts";
61
62
  import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
62
63
  import {
63
64
  argumentItems,
@@ -80,41 +81,34 @@ const replaceSchema = Type.Object(
80
81
  { additionalProperties: false },
81
82
  );
82
83
 
83
- function createReplaceSchema(actionFusion: boolean) {
84
- return withThenRunSchema(replaceSchema, "replace", actionFusion);
85
- }
86
84
  type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
87
85
 
88
86
  /** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
89
87
  function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
90
88
  let t = theme.fg("toolTitle", theme.bold("replace "));
91
- t += theme.fg("accent", args.path);
89
+ t += formatHeaderPath(args.path, theme);
92
90
  const count = args.replacements?.length ?? 0;
93
91
  t += theme.fg("dim", ` — ${count} rule${count === 1 ? "" : "s"}`);
94
92
  if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
95
93
  return t;
96
94
  }
97
95
 
98
- /** Report unwritable replacement text and regex compile errors; Pi checks field shapes. */
96
+ /** Report unwritable replacement text, flags V8 rejects, and regex compile errors; Pi checks field shapes. */
99
97
  function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void {
100
98
  const rules = argumentItems((args as { replacements?: unknown } | null)?.replacements);
101
- const validFlags = new RegExp(REGEX_FLAGS_PATTERN);
102
99
  rules.forEach((rule, index) => {
103
- const { find, replace, regex, flags } = (rule ?? {}) as Record<string, unknown>;
100
+ const { find, replace, literal, flags } = (rule ?? {}) as Record<string, unknown>;
104
101
  const unwritable = typeof replace === "string" ? unwritableTextError(replace) : undefined;
105
102
  if (unwritable) report(`replacements[${index}].replace`, unwritable.message);
106
- if (
107
- regex === true &&
108
- typeof find === "string" &&
109
- find !== "" &&
110
- (flags === undefined || (typeof flags === "string" && validFlags.test(flags)))
111
- ) {
112
- try {
113
- buildRegex(find, true, flags);
114
- } catch (error) {
115
- report(`replacements[${index}].find`, errorMessage(error));
116
- }
117
- }
103
+ if (flags !== undefined && typeof flags !== "string") return;
104
+ const item = `replacements[${index}]`;
105
+ checkRegexArguments(
106
+ `${item}.flags`,
107
+ flags,
108
+ literal !== false,
109
+ [[`${item}.find`, find]],
110
+ report,
111
+ );
118
112
  });
119
113
  }
120
114
 
@@ -124,12 +118,12 @@ export function makeReplaceTool(
124
118
  fusion?: ActionFusionExecutor,
125
119
  budgets: OutputBudgetProvider = defaultOutputBudgets,
126
120
  ) {
127
- const parameters = createReplaceSchema(fusion !== undefined);
121
+ const parameters = withThenRunSchema(replaceSchema, "replace", fusion !== undefined);
128
122
  return {
129
123
  name: "replace" as const,
130
124
  label: "replace",
131
125
  description: withThenRunDescription(
132
- "Replace every match of one or more literal or JavaScript-regex rules in a file. Rules swap only their matched fragments in one call, without line anchors. Use edit instead for inserting, deleting, or rewriting whole lines. Overlapping matches or a rule with no match reject the whole call. Returns a mutation report.",
126
+ "Replace every match of one or more literal or JavaScript-regex rules in a file. Rules swap only their matched fragments in one call, without line anchors. Use edit instead for inserting, deleting, or rewriting whole lines. Overlapping matches or a rule with no match reject the whole call.",
133
127
  fusion !== undefined,
134
128
  ),
135
129
  promptSnippet: "Replace matching text across a file",
@@ -148,7 +142,15 @@ export function makeReplaceTool(
148
142
  theme: Theme,
149
143
  context: ReplaceRenderContext,
150
144
  ) {
151
- return renderMutationResult(result, options, theme, context, "Replacing…", replaceHeader);
145
+ return renderMutationResult(
146
+ result,
147
+ options,
148
+ theme,
149
+ context,
150
+ "Replacing…",
151
+ replaceHeader,
152
+ "replace",
153
+ );
152
154
  },
153
155
 
154
156
  async execute(
@@ -179,7 +181,7 @@ function runReplace(
179
181
  ) {
180
182
  return runTextMutation<"replace">(target, async (currentText) => {
181
183
  // The regex worker reports its own cancellation; a literal batch runs synchronously.
182
- const { text, count } = rules.some((rule) => rule.regex === true)
184
+ const { text, count } = rules.some((rule) => !rule.literal)
183
185
  ? await runRegexReplacements(currentText, rules, config.replace.regexTimeoutMs, target.signal)
184
186
  : applyReplacements(currentText, rules);
185
187
  return { text, facts: { matches: count } };
@@ -1,19 +1,10 @@
1
- /** Replacement-specific result shape; shared worker errors are checked by the host. */
2
- import { Type } from "typebox";
1
+ /** Replacement worker request and reply decoder; shared worker errors are checked by the host. */
3
2
  import { workerReplyDecoder } from "./regex-worker-contract.ts";
4
- import type { Replacement } from "../core/replace.ts";
3
+ import { REPLACEMENT_RESULT_SCHEMA, type Replacement } from "../core/replace-schema.ts";
5
4
 
6
5
  export interface ReplacementRequest {
7
6
  readonly source: string;
8
7
  readonly rules: readonly Replacement[];
9
8
  }
10
9
 
11
- export const decodeWorkerReply = workerReplyDecoder(
12
- Type.Object(
13
- {
14
- text: Type.String(),
15
- count: Type.Integer({ minimum: 1 }),
16
- },
17
- { additionalProperties: false },
18
- ),
19
- );
10
+ export const decodeWorkerReply = workerReplyDecoder(REPLACEMENT_RESULT_SCHEMA);