@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
@@ -0,0 +1,90 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { applyReplacements, type Replacement } from "./replace.ts";
4
+
5
+ test("replacement joins beside LF → preserve standalone CR content", async (t) => {
6
+ const literal = (find: string, replace: string): Replacement => ({
7
+ find,
8
+ replace,
9
+ literal: true,
10
+ });
11
+ const cases = [
12
+ {
13
+ name: "replacement before original LF",
14
+ source: "a\nb",
15
+ rules: [literal("a", "x\r")],
16
+ expected: "x\r\r\nb",
17
+ },
18
+ {
19
+ name: "original CR before replacement LF",
20
+ source: "a\rb",
21
+ rules: [literal("b", "\nB")],
22
+ expected: "a\r\r\nB",
23
+ },
24
+ {
25
+ name: "deletion joins original CR and LF",
26
+ source: "a\rx\nb",
27
+ rules: [literal("x", "")],
28
+ expected: "a\r\r\nb",
29
+ },
30
+ {
31
+ name: "replacement contains CR before a new LF",
32
+ source: "a\nb",
33
+ rules: [literal("a", "x\r\r\ny")],
34
+ expected: "x\r\r\ny\nb",
35
+ },
36
+ {
37
+ name: "replacement contains CR before a reused LF",
38
+ source: "a\nb",
39
+ rules: [literal("a\nb", "x\r\r\ny")],
40
+ expected: "x\r\r\ny",
41
+ },
42
+ {
43
+ name: "captured CR before replacement LF",
44
+ source: "a\rb\nc",
45
+ rules: [{ find: "(a\r)b", replace: "$1\nB", literal: false }],
46
+ expected: "a\r\r\nB\nc",
47
+ },
48
+ {
49
+ name: "adjacent replacements",
50
+ source: "ab",
51
+ rules: [literal("a", "x\r"), literal("b", "\ny")],
52
+ expected: "x\r\r\ny",
53
+ },
54
+ {
55
+ name: "adjacent replacements separated by a deletion",
56
+ source: "axb",
57
+ rules: [literal("a", "x\r"), literal("x", ""), literal("b", "\ny")],
58
+ expected: "x\r\r\ny",
59
+ },
60
+ {
61
+ name: "zero-width insertion before LF",
62
+ source: "a\nb",
63
+ rules: [{ find: "(?=\\n)", replace: "\r", literal: false }],
64
+ expected: "a\r\r\nb",
65
+ },
66
+ {
67
+ name: "replacement before original CRLF",
68
+ source: "a\r\nb",
69
+ rules: [literal("a", "x\r")],
70
+ expected: "x\r\r\nb",
71
+ },
72
+ {
73
+ name: "unchanged CR content and CRLF separator",
74
+ source: "a\r\r\nb",
75
+ rules: [literal("a\r\r\nb", "a\r\r\nb")],
76
+ expected: "a\r\r\nb",
77
+ },
78
+ {
79
+ name: "CR at EOF needs no separator",
80
+ source: "ab",
81
+ rules: [literal("b", "x\r")],
82
+ expected: "ax\r",
83
+ },
84
+ ];
85
+ for (const { name, source, rules, expected } of cases) {
86
+ await t.test(name, () => {
87
+ assert.equal(applyReplacements(source, rules).text, expected);
88
+ });
89
+ }
90
+ });
@@ -11,13 +11,14 @@ import { buildRegex } from "./regex.ts";
11
11
  import {
12
12
  createLfTextView,
13
13
  detectLineEnding,
14
+ joinTextFragments,
14
15
  normalizeLineEndings,
15
16
  restoreLineEndings,
16
17
  } from "./lines.ts";
17
18
  import { findSortedRangeConflict } from "./ranges.ts";
18
19
  import { HashlineError } from "./errors.ts";
19
20
 
20
- import type { Replacement } from "./replace-schema.ts";
21
+ import type { Replacement, ReplacementResult } from "./replace-schema.ts";
21
22
  export type { Replacement } from "./replace-schema.ts";
22
23
 
23
24
  /** Expand JS replacement tokens against the original match, including prefix/suffix context. */
@@ -44,12 +45,12 @@ function expandReplacement(template: string, match: RegExpMatchArray, source: st
44
45
  export function applyReplacements(
45
46
  source: string,
46
47
  rules: readonly Replacement[],
47
- ): { text: string; count: number } {
48
+ ): ReplacementResult {
48
49
  const changes: { start: number; end: number; text: string; rule: number }[] = [];
49
50
  const view = createLfTextView(source);
50
51
  const fallbackEnding = detectLineEnding(source) === "crlf" ? "\r\n" : "\n";
51
52
  for (const [index, rule] of rules.entries()) {
52
- const regex = buildRegex(rule.find, rule.regex === true, rule.flags);
53
+ const regex = buildRegex(rule.find, rule.literal, rule.flags);
53
54
  let count = 0;
54
55
  const replacement = normalizeLineEndings(rule.replace);
55
56
  for (const match of view.text.matchAll(regex)) {
@@ -61,7 +62,7 @@ export function applyReplacements(
61
62
  end,
62
63
  rule: index,
63
64
  text: restoreLineEndings(
64
- rule.regex ? expandReplacement(replacement, match, view.text) : replacement,
65
+ rule.literal ? replacement : expandReplacement(replacement, match, view.text),
65
66
  source.slice(start, end),
66
67
  fallbackEnding,
67
68
  ),
@@ -88,5 +89,5 @@ export function applyReplacements(
88
89
  cursor = change.end;
89
90
  }
90
91
  parts.push(source.slice(cursor));
91
- return { text: parts.join(""), count: changes.length };
92
+ return { text: joinTextFragments(parts), count: changes.length };
92
93
  }
@@ -197,3 +197,12 @@ test("word escape → keeps word-containing files and rejects punctuation-only f
197
197
  assert.ok(hasCandidateBytes(Buffer.from("---a---"), prefilter));
198
198
  assert.equal(hasCandidateBytes(Buffer.from("---"), prefilter), false);
199
199
  });
200
+
201
+ test("deeply nested uppercase pattern → smart case stays sensitive and prefilter retains native hits", () => {
202
+ for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
203
+ const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
204
+ assert.equal(new RegExp(pattern).test("A"), true);
205
+ assert.equal(smartIgnoreCase([pattern], false), false);
206
+ assert.equal(hasCandidateBytes(Buffer.from("A"), extractPrefilter(query(pattern))), true);
207
+ }
208
+ });
@@ -11,9 +11,8 @@
11
11
  import { RegExpParser, visitRegExpAST, type AST } from "@eslint-community/regexpp";
12
12
  import { caseVariants } from "./case-fold.ts";
13
13
  import {
14
+ acceptedClassStrings,
14
15
  nativeCharacterRanges,
15
- classStrings,
16
- membership,
17
16
  total,
18
17
  type CharacterNode,
19
18
  surrogatePair,
@@ -22,9 +21,9 @@ import { regexSource } from "./regex.ts";
22
21
  import type { GrepQuery } from "./search.ts";
23
22
 
24
23
  /** One literal position: the characters JavaScript may match there. */
25
- export type LiteralChar = readonly string[];
24
+ type LiteralChar = readonly string[];
26
25
  export type Literal = readonly LiteralChar[];
27
- export interface LiteralFilter {
26
+ interface LiteralFilter {
28
27
  readonly kind: "literals";
29
28
  readonly literals: readonly Literal[];
30
29
  }
@@ -147,10 +146,12 @@ function andFilters(filters: readonly Prefilter[]): Prefilter {
147
146
  }
148
147
 
149
148
  function orFilters(filters: readonly Prefilter[]): Prefilter {
150
- if (!filters.length || filters.some((filter) => filter.kind === "all")) return ALL;
151
- let result = filters[0];
152
- for (const filter of filters.slice(1)) {
153
- if (result.kind === "all" || filter.kind === "all") return ALL;
149
+ const known = filters.filter((filter) => filter.kind !== "all");
150
+ if (!known.length || known.length < filters.length) return ALL;
151
+ let result: Prefilter = known[0];
152
+ for (const filter of known.slice(1)) {
153
+ // Distribution can drop every bounded clause, leaving no condition.
154
+ if (result.kind === "all") return ALL;
154
155
  const left = result.kind === "and" ? result.filters : [result];
155
156
  const right = filter.kind === "and" ? filter.filters : [filter];
156
157
  // CNF distribution creates AND clauses; keeping only bounded clauses is a widening.
@@ -247,9 +248,9 @@ function quantified(node: AST.Quantifier, ctx: Context): Info {
247
248
 
248
249
  function classInfo(node: CharacterNode, ctx: Context): Info {
249
250
  if (node.type === "CharacterSet" && node.kind === "any") return UNKNOWN;
250
- const strings = classStrings(node);
251
- if (!strings) return UNKNOWN;
252
251
  const flags = `${ctx.ignoreCase ? "i" : ""}${ctx.unicodeSets ? "v" : ctx.unicode ? "u" : ""}`;
252
+ const strings = acceptedClassStrings(node, flags);
253
+ if (!strings) return UNKNOWN;
253
254
  const ranges = nativeCharacterRanges(node.raw, flags);
254
255
  if (total(ranges) > MAX_CLASS_CHARS) return UNKNOWN;
255
256
  const units: Unit[] = [];
@@ -257,9 +258,7 @@ function classInfo(node: CharacterNode, ctx: Context): Info {
257
258
  for (let point = low; point <= high; point++)
258
259
  units.push(charUnit(point, { ...ctx, ignoreCase: false }));
259
260
  const infos: Info[] = units.length ? [{ exact: [[unionUnits(units)]], filter: ALL }] : [];
260
- const accepts = membership(node.raw, flags);
261
261
  for (const value of strings) {
262
- if (!accepts.test(value)) continue;
263
262
  const sequence = [...value].map((char) => charUnit(char.codePointAt(0)!, ctx));
264
263
  infos.push(
265
264
  sequence.length <= MAX_SEQUENCE_LENGTH
@@ -318,20 +317,22 @@ function analyzeAlternatives(alternatives: readonly AST.Alternative[], ctx: Cont
318
317
  }
319
318
 
320
319
  /**
321
- * Parse a pattern V8 already accepted; undefined when regexpp lacks its syntax or
322
- * exceeds its own limits, which only makes an analysis less precise.
320
+ * Analyze a pattern V8 already accepted; undefined when regexpp lacks its syntax
321
+ * or parsing or analysis exceeds its limits, which only makes candidates less precise.
323
322
  */
324
- export function parseQueryPattern(
323
+ export function analyzeQueryPattern<T>(
325
324
  pattern: string,
326
325
  literal: boolean,
327
326
  flags: string,
328
- ): AST.Pattern | undefined {
329
- const source = regexSource(pattern, !literal);
327
+ analyze: (parsed: AST.Pattern) => T,
328
+ ): T | undefined {
329
+ const source = regexSource(pattern, literal);
330
330
  try {
331
- return new RegExpParser({ ecmaVersion: 2025 }).parsePattern(source, 0, source.length, {
331
+ const parsed = new RegExpParser({ ecmaVersion: 2025 }).parsePattern(source, 0, source.length, {
332
332
  unicode: flags.includes("u"),
333
333
  unicodeSets: flags.includes("v"),
334
334
  });
335
+ return analyze(parsed);
335
336
  } catch (error) {
336
337
  if (error instanceof SyntaxError || error instanceof RangeError) return undefined;
337
338
  throw error;
@@ -345,16 +346,17 @@ export function smartIgnoreCase(
345
346
  flags = "",
346
347
  ): boolean {
347
348
  return !patterns.some((pattern) => {
348
- const parsed = parseQueryPattern(pattern, literal, flags);
349
- if (!parsed) return true;
350
- let uppercase = false;
351
- visitRegExpAST(parsed, {
352
- onCharacterEnter({ value }) {
353
- const text = String.fromCodePoint(value);
354
- uppercase ||= text !== text.toLowerCase();
355
- },
349
+ const uppercase = analyzeQueryPattern(pattern, literal, flags, (parsed) => {
350
+ let found = false;
351
+ visitRegExpAST(parsed, {
352
+ onCharacterEnter({ value }) {
353
+ const text = String.fromCodePoint(value);
354
+ found ||= text !== text.toLowerCase();
355
+ },
356
+ });
357
+ return found;
356
358
  });
357
- return uppercase;
359
+ return uppercase ?? true;
358
360
  });
359
361
  }
360
362
 
@@ -367,9 +369,11 @@ export function extractPrefilter(query: GrepQuery): Prefilter {
367
369
  unicodeSets: query.flags.includes("v"),
368
370
  };
369
371
  return orFilters(
370
- query.patterns.map((pattern) => {
371
- const parsed = parseQueryPattern(pattern, query.literal, query.flags);
372
- return parsed ? filterOf(analyzeAlternatives(parsed.alternatives, ctx)) : ALL;
373
- }),
372
+ query.patterns.map(
373
+ (pattern) =>
374
+ analyzeQueryPattern(pattern, query.literal, query.flags, (parsed) =>
375
+ filterOf(analyzeAlternatives(parsed.alternatives, ctx)),
376
+ ) ?? ALL,
377
+ ),
374
378
  );
375
379
  }
@@ -75,7 +75,7 @@ function multilineRows(source: string, regex: RegExp, limit: number): Rows {
75
75
  }
76
76
 
77
77
  const queryRegexes = (query: GrepQuery) =>
78
- query.patterns.map((pattern) => buildRegex(pattern, !query.literal, query.flags));
78
+ query.patterns.map((pattern) => buildRegex(pattern, query.literal, query.flags));
79
79
 
80
80
  /** The first match column of one physical line, or undefined when no pattern matches it. */
81
81
  function lineColumn(regexes: readonly RegExp[], text: string): number | undefined {
package/src/core/types.ts CHANGED
@@ -22,12 +22,12 @@ type AnchorField = (typeof EDIT_ANCHOR_FIELDS)[number];
22
22
  export type Edit =
23
23
  | {
24
24
  readonly op: "replace";
25
- readonly start: Anchor;
25
+ readonly anchor: Anchor;
26
26
  readonly end?: Anchor;
27
27
  readonly body: string[];
28
28
  }
29
- | { readonly op: "delete"; readonly start: Anchor; readonly end?: Anchor }
30
- | ({ readonly op: "copy" | "move"; readonly start: Anchor; readonly end?: Anchor } & (
29
+ | { readonly op: "delete"; readonly anchor: Anchor; readonly end?: Anchor }
30
+ | ({ readonly op: "copy" | "move"; readonly anchor: Anchor; readonly end?: Anchor } & (
31
31
  | { readonly before: Anchor; readonly after?: never }
32
32
  | { readonly after: Anchor; readonly before?: never }
33
33
  ))
@@ -73,7 +73,7 @@ export type AnchorRecovery =
73
73
  *
74
74
  * `opIndex` is the 0-based position in the input `edits[]`; `which` names the
75
75
  * op's source/insertion anchor, range end, or before/after destination; `op` is the op kind.
76
- * `current` is the cited line's live content + hash (null if the line number is
76
+ * `current` is the cited line's live content (null if the line number is
77
77
  * out of range) — surfaced when recovery is `none` so the model can self-diagnose.
78
78
  */
79
79
  export interface AnchorFailure {
@@ -82,15 +82,13 @@ export interface AnchorFailure {
82
82
  readonly op: Edit["op"];
83
83
  readonly cited: Anchor;
84
84
  readonly recovery: AnchorRecovery;
85
- readonly current: { readonly hash: string; readonly content: string } | null;
85
+ readonly current: { readonly content: string } | null;
86
86
  }
87
87
 
88
88
  /** Record for one supplied anchor in the immutable apply snapshot. */
89
89
  export interface AnchorCheck {
90
90
  readonly opIndex: number;
91
91
  readonly which: AnchorField;
92
- readonly op: Edit["op"];
93
- readonly cited: Anchor;
94
92
  readonly status: "matched" | "mismatched";
95
93
  }
96
94
 
@@ -103,7 +101,7 @@ export type ApplyFailure =
103
101
  }
104
102
  | {
105
103
  readonly kind: "range";
106
- /** INVALID_RANGE for a reversed range or a move into itself; OVERLAPPING_EDITS for overlap. */
104
+ /** INVALID_RANGE for a reversed range or a move into itself; OVERLAPPING_EDITS for overlap or a repeated insertion position. */
107
105
  readonly code: "INVALID_RANGE" | "OVERLAPPING_EDITS";
108
106
  readonly message: string;
109
107
  readonly checks: readonly AnchorCheck[];
package/src/index.ts CHANGED
@@ -4,8 +4,8 @@
4
4
  * Overrides Pi's built-in read, grep, edit, and write: read and grep output
5
5
  * `LINE#HASH│content` anchors, edit applies structured ops on those anchors, and
6
6
  * write publishes whole files through the same commit layer. Adds `replace`
7
- * (literal or JavaScript-regex replacement across a file) and, when enabled,
8
- * `forget`. Each tool carries its own renderer; src/pi/AGENTS.md maps the modules.
7
+ * (literal or JavaScript-regex replacement across a file). Each tool carries its
8
+ * own renderer; src/pi/AGENTS.md maps the modules.
9
9
  *
10
10
  * @module pi-hashline-edit
11
11
  */
@@ -17,7 +17,6 @@ import { registerModelBudgets } from "./pi/model-budgets.ts";
17
17
  import { makeEditOverride } from "./pi/edit-tool.ts";
18
18
  import { makeReadOverride } from "./pi/read-tool.ts";
19
19
  import { makeGrepOverride } from "./pi/grep-tool.ts";
20
- import { registerForgetTool } from "./pi/forget-tool.ts";
21
20
  import { makeReplaceTool } from "./pi/replace-tool.ts";
22
21
  import { makeWriteOverride } from "./pi/write-tool.ts";
23
22
  import { createActionFusionExecutor } from "./pi/action-fusion.ts";
@@ -56,6 +55,5 @@ export default function (pi: ExtensionAPI) {
56
55
 
57
56
  register(makeReadOverride(cwd, config, budgets));
58
57
  register(makeGrepOverride(cwd, config, budgets));
59
- if (config.forget) registerForgetTool(pi, budgets);
60
58
  }
61
59
  }
@@ -9,6 +9,7 @@ import { computeLineHash } from "../core/hash.ts";
9
9
  import { callTool } from "../pi/tool-call.testing.ts";
10
10
  import { DEFAULT_CONFIG, type HashlineEditConfig } from "../pi/config.ts";
11
11
  import { reportOf } from "../pi/report.ts";
12
+ import { formatByteSize } from "../pi/budgets.ts";
12
13
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
13
14
 
14
15
  test("registered tools retain their configuration when another tool set is registered", async (t) => {
@@ -74,7 +75,7 @@ test("registered tools retain their configuration when another tool set is regis
74
75
  path,
75
76
  edits: [
76
77
  {
77
- op: "replace",
78
+ action: "replace",
78
79
  anchor: `1#${computeLineHash(1, "before", hashLen)}`,
79
80
  body: ["after"],
80
81
  },
@@ -82,6 +83,7 @@ test("registered tools retain their configuration when another tool set is regis
82
83
  },
83
84
  }[name];
84
85
  const result = await callTool(tool, params);
86
+ assert.equal(result.content[0].type, "text");
85
87
  const expected = name === "edit" ? "after" : "before";
86
88
  if (name === "edit") {
87
89
  assert.equal(result.isError, undefined);
@@ -102,7 +104,7 @@ test("registered tools retain their configuration when another tool set is regis
102
104
  await expectToolFailure(
103
105
  callTool(tool, {
104
106
  path,
105
- edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
107
+ edits: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
106
108
  }),
107
109
  "ANCHOR_MISMATCH",
108
110
  (report) => {
@@ -122,6 +124,7 @@ test("registered tools retain their configuration when another tool set is regis
122
124
  const lines = ["first", "second", "third"];
123
125
  await writeFile(join(directory, path), `${lines.join("\n")}\n`);
124
126
  const result = await callTool(tool, { path });
127
+ assert.equal(result.content[0].type, "text");
125
128
  assert.deepEqual(
126
129
  result.content[0].text.split("\n").filter((line: string) => /^\d+#/.test(line)),
127
130
  lines
@@ -131,21 +134,25 @@ test("registered tools retain their configuration when another tool set is regis
131
134
  `${index + 1}#${computeLineHash(index + 1, content, hashLen)}│${content}`,
132
135
  ),
133
136
  );
134
- assert.equal(result.details.pagination.nextOffset, read.defaultLimit + 1);
137
+ assert.equal(reportOf(result, "read")?.pagination?.nextOffset, read.defaultLimit + 1);
135
138
 
136
139
  const wide = "界".repeat(500);
137
140
  await writeFile(join(directory, path), `${wide}\n`);
138
141
  const bounded = await callTool(tool, { path });
142
+ assert.equal(bounded.content[0].type, "text");
139
143
  if (read.maxKiB === 1) {
140
- assert.deepEqual(reportOf(bounded)?.lineTooLong, { line: 1, limit: "1 KiB" });
141
- assert.equal(bounded.details.truncation.maxBytes, 1024);
142
- assert.equal(bounded.details.truncation.outputBytes, 0);
144
+ const maxBytes = read.maxKiB * 1024;
145
+ assert.deepEqual(reportOf(bounded, "read")?.lineTooLong, {
146
+ line: 1,
147
+ limit: formatByteSize(maxBytes),
148
+ });
149
+ assert.doesNotMatch(bounded.content[0].text, /^\d+#/m);
143
150
  } else {
144
151
  assert.ok(
145
152
  bounded.content[0].text.includes(`1#${computeLineHash(1, wide, hashLen)}│${wide}`),
146
153
  );
147
- assert.equal(reportOf(bounded)?.truncatedAt, undefined);
148
- assert.equal(reportOf(bounded)?.pagination, undefined);
154
+ assert.equal(reportOf(bounded, "read")?.outputLimit, undefined);
155
+ assert.equal(reportOf(bounded, "read")?.pagination, undefined);
149
156
  }
150
157
  },
151
158
  );
@@ -171,6 +178,7 @@ test("registered tools retain their configuration when another tool set is regis
171
178
  ];
172
179
  await writeFile(join(directory, path), `${lines.join("\n")}\n`);
173
180
  const result = await callTool(tool, { path, pattern: "needle", literal: true });
181
+ assert.equal(result.content[0].type, "text");
174
182
  assert.deepEqual(
175
183
  result.content[0].text.split("\n").filter((line: string) => /^\d+#/.test(line)),
176
184
  expectedGrepLines.map(
@@ -178,7 +186,7 @@ test("registered tools retain their configuration when another tool set is regis
178
186
  `${line}#${computeLineHash(line, lines[line - 1], hashLen)}│${lines[line - 1]}`,
179
187
  ),
180
188
  );
181
- assert.equal(reportOf(result)?.matchLimit, grep.defaultLimit);
189
+ assert.equal(reportOf(result, "grep")?.matchLimit, grep.defaultLimit);
182
190
  },
183
191
  );
184
192
 
@@ -193,7 +201,7 @@ test("registered tools retain their configuration when another tool set is regis
193
201
  await expectToolFailure(
194
202
  callTool(tool, {
195
203
  path,
196
- replacements: [{ find: "^(a+)+$", replace: "changed", regex: true }],
204
+ replacements: [{ find: "^(a+)+$", replace: "changed", literal: false }],
197
205
  }),
198
206
  "REGEX_TIMEOUT",
199
207
  (report) => {
@@ -3,15 +3,18 @@ import { readFile, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { test, type TestContext } from "node:test";
5
5
  import { Type } from "typebox";
6
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
6
7
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
8
  import { openTestSession, responseStream } from "../testing/session.testing.ts";
8
9
  import {
9
10
  createActionFusionExecutor,
10
- type ActionFusionDetails,
11
11
  type ActionFusionProgress,
12
12
  type ThenRunInput,
13
13
  } from "../pi/action-fusion.ts";
14
14
  import { makeWriteOverride } from "../pi/write-tool.ts";
15
+ import { commandText } from "../pi/mutation-result.ts";
16
+ import { reportOf } from "../pi/report.ts";
17
+ import type { CommandStatus } from "../pi/report-schema.ts";
15
18
 
16
19
  /** Exercise the default runner through a real parent tool call, with no provider traffic. */
17
20
  async function openSession(
@@ -78,7 +81,7 @@ async function openSession(
78
81
  assert.equal(await readFile(join(cwd, "saved.txt"), "utf8"), "saved\n");
79
82
  return {
80
83
  modelRequests: responses,
81
- state: (result.details as unknown as { actionFusion: ActionFusionDetails }).actionFusion,
84
+ report: reportOf(result, "write"),
82
85
  text: result.content
83
86
  .filter((block) => block.type === "text")
84
87
  .map((block) => block.text)
@@ -92,7 +95,7 @@ const commandCases: {
92
95
  name: string;
93
96
  source: string;
94
97
  timeout?: number;
95
- command: ActionFusionDetails["command"];
98
+ command: CommandStatus;
96
99
  diagnostic: RegExp;
97
100
  }[] = [
98
101
  {
@@ -132,7 +135,9 @@ for (const { name, source, timeout, command, diagnostic } of commandCases) {
132
135
  command: "node command.mjs",
133
136
  ...(timeout === undefined ? {} : { timeout }),
134
137
  });
135
- assert.deepEqual(result.state, { publication: "PUBLISHED", command, freshness: "unchanged" });
138
+ assert.equal(result.report?.publication, "PUBLISHED");
139
+ assert.equal(result.report?.then_run?.status, command);
140
+ assert.equal(result.report?.freshness, undefined);
136
141
  assert.match(result.text, diagnostic);
137
142
  assert.equal(f.progress.at(-1)?.command, command);
138
143
  });
@@ -143,7 +148,12 @@ test("cancelling a real session Bash command → reports cancellation and keeps
143
148
  }, async (t) => {
144
149
  const started = Promise.withResolvers<void>();
145
150
  const f = await openSession(t, undefined, (event) => {
146
- if (event.command === "running" && event.output.includes("READY")) started.resolve();
151
+ if (
152
+ event.command === "running" &&
153
+ event.result &&
154
+ commandText(event.result.content).includes("READY")
155
+ )
156
+ started.resolve();
147
157
  });
148
158
  await writeFile(
149
159
  join(f.cwd, "command.mjs"),
@@ -153,11 +163,8 @@ test("cancelling a real session Bash command → reports cancellation and keeps
153
163
  await started.promise;
154
164
  await f.abort();
155
165
  const result = await pending;
156
- assert.deepEqual(result.state, {
157
- publication: "PUBLISHED",
158
- command: "cancelled",
159
- freshness: "unchanged",
160
- });
166
+ assert.equal(result.report?.publication, "PUBLISHED");
167
+ assert.equal(result.report?.then_run?.status, "cancelled");
161
168
  assert.match(result.text, /Command aborted/);
162
169
  assert.equal(f.progress.at(-1)?.command, "cancelled");
163
170
  });
@@ -206,11 +213,8 @@ test("session Bash tool_call blocks then_run → no command side effect, mutatio
206
213
  "import { writeFileSync } from 'node:fs'; writeFileSync('command-ran', 'yes');\n",
207
214
  );
208
215
  const result = await f.run({ command: "node command.mjs" });
209
- assert.deepEqual(result.state, {
210
- publication: "PUBLISHED",
211
- command: "failed",
212
- freshness: "unchanged",
213
- });
216
+ assert.equal(result.report?.publication, "PUBLISHED");
217
+ assert.equal(result.report?.then_run?.status, "failed");
214
218
  assert.match(result.text, /BLOCKED_BY_POLICY/);
215
219
  assert.equal(result.modelRequests, 1, "Preserve the policy hook's request to stop the batch");
216
220
  await assert.rejects(readFile(join(f.cwd, "command-ran")), { code: "ENOENT" });
@@ -221,21 +225,33 @@ test("session Bash override and tool_result hook → then_run uses their final r
221
225
  timeout: 15_000,
222
226
  }, async (t) => {
223
227
  let executions = 0;
228
+ const partial: AgentToolResult<unknown> = {
229
+ content: [{ type: "text", text: "OVERRIDE_PROGRESS" }],
230
+ details: { fullOutputPath: "/tmp/partial-command.log" },
231
+ };
232
+ const final: AgentToolResult<unknown> = {
233
+ content: [
234
+ { type: "text", text: "HOOK_REJECTED_OVERRIDE" },
235
+ { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" },
236
+ ],
237
+ details: { fullOutputPath: "/tmp/final-command.log" },
238
+ };
224
239
  const f = await openSession(t, (pi) => {
225
240
  pi.registerTool({
226
241
  name: "bash",
227
242
  label: "bash",
228
243
  description: "Session Bash override",
229
244
  parameters: Type.Object({ command: Type.String() }),
230
- async execute() {
245
+ async execute(_id, _args, _signal, onUpdate) {
231
246
  executions++;
247
+ onUpdate?.(partial);
232
248
  return { content: [{ type: "text", text: "OVERRIDE_RESULT" }], details: {} };
233
249
  },
234
250
  });
235
251
  pi.on("tool_result", (event) =>
236
252
  event.toolName === "bash"
237
253
  ? {
238
- content: [{ type: "text", text: "HOOK_REJECTED_OVERRIDE" }],
254
+ ...final,
239
255
  isError: true,
240
256
  }
241
257
  : undefined,
@@ -247,13 +263,16 @@ test("session Bash override and tool_result hook → then_run uses their final r
247
263
  );
248
264
  const result = await f.run({ command: "node command.mjs" });
249
265
  assert.equal(executions, 1);
250
- assert.deepEqual(result.state, {
251
- publication: "PUBLISHED",
252
- command: "failed",
253
- freshness: "unchanged",
254
- });
266
+ assert.equal(result.report?.then_run?.status, "failed");
255
267
  assert.match(result.text, /HOOK_REJECTED_OVERRIDE/);
256
268
  assert.doesNotMatch(result.text, /OVERRIDE_RESULT/);
269
+ assert.deepEqual(
270
+ f.progress.find(
271
+ (event) => event.result && commandText(event.result.content) === "OVERRIDE_PROGRESS",
272
+ )?.result,
273
+ partial,
274
+ );
275
+ assert.deepEqual(f.progress.at(-1)?.result, final);
257
276
  await assert.rejects(readFile(join(f.cwd, "command-ran")), { code: "ENOENT" });
258
277
  assert.ok(f.calls.some((call) => call.name === "bash" && call.parent === "fused"));
259
278
  });
@@ -6,6 +6,7 @@ import { test } from "node:test";
6
6
  import { DEFAULT_CONFIG } from "../pi/config.ts";
7
7
  import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
8
8
  import { reportOf } from "../pi/report.ts";
9
+ import { grepCounts } from "../pi/grep-output.testing.ts";
9
10
  import { callTool } from "../pi/tool-call.testing.ts";
10
11
  import { rejectsArgument } from "../pi/argument-error.testing.ts";
11
12
 
@@ -228,8 +229,8 @@ test("grep flags: JavaScript modes preserve native matching through the real sea
228
229
  multiline: scenario.multiline ?? false,
229
230
  ...(scenario.ignoreCase === undefined ? {} : { ignoreCase: scenario.ignoreCase }),
230
231
  });
231
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result)));
232
- assert.equal(reportOf(result)?.matches, scenario.lines.length);
232
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
233
+ assert.equal(grepCounts(result).matches, scenario.lines.length);
233
234
  const body = result.content[0];
234
235
  assert.ok(body.type === "text");
235
236
  const lines = [...body.text.matchAll(/^(\d+)#[0-9A-Z]+│/gm)].map((match) => Number(match[1]));
@@ -238,16 +239,8 @@ test("grep flags: JavaScript modes preserve native matching through the real sea
238
239
  }
239
240
  });
240
241
 
241
- test("grep flags: native flag and Unicode syntax errors reject the corresponding argument", async () => {
242
+ test("grep flags: invalid Unicode syntax rejects the pattern argument", async () => {
242
243
  const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {});
243
- for (const literal of [false, true]) {
244
- for (const flags of ["x", "uv"]) {
245
- await assert.rejects(
246
- callTool(tool, { path: "missing.txt", pattern: "a", literal, flags }),
247
- rejectsArgument("flags"),
248
- );
249
- }
250
- }
251
244
  await assert.rejects(
252
245
  callTool(tool, {
253
246
  path: "missing.txt",
@@ -274,7 +267,7 @@ test("grep flags: valid V8 patterns exceeding translator parser depth still exec
274
267
  literal: false,
275
268
  ...(flags === undefined ? {} : { flags }),
276
269
  });
277
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result)));
278
- assert.equal(reportOf(result)?.matches, 1);
270
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
271
+ assert.equal(grepCounts(result).matches, 1);
279
272
  }
280
273
  });