@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -54,19 +54,34 @@ export const PATH_ERROR_MESSAGES = {
54
54
  NOT_REGULAR_FILE: "Path is not a regular file.",
55
55
  } as const satisfies Partial<Record<ErrorCode, string>>;
56
56
 
57
- /** Message text for a caught value; non-Error throws are stringified. */
57
+ /** The description of a thrown value that has no string form. */
58
+ export const NO_STRING_FORM = "The thrown value has no string form.";
59
+
60
+ /**
61
+ * Message text for a caught value; non-Error throws are stringified. A thrown value may be
62
+ * foreign, and inspecting it can throw (a null-prototype object, a revoked proxy, a throwing
63
+ * getter); describing it must not throw in its place.
64
+ */
58
65
  export function errorMessage(error: unknown): string {
59
- return error instanceof Error ? error.message : String(error);
66
+ try {
67
+ return String(error instanceof Error ? error.message : error);
68
+ } catch {
69
+ return NO_STRING_FORM;
70
+ }
60
71
  }
61
72
 
62
- /** Node's errno code of a filesystem error, if any. */
73
+ /** Node's errno code of a filesystem error, if any; a value whose inspection throws has none. */
63
74
  export function errnoCode(error: unknown): string | undefined {
64
- return typeof error === "object" &&
65
- error !== null &&
66
- "code" in error &&
67
- typeof error.code === "string"
68
- ? error.code
69
- : undefined;
75
+ try {
76
+ return typeof error === "object" &&
77
+ error !== null &&
78
+ "code" in error &&
79
+ typeof error.code === "string"
80
+ ? error.code
81
+ : undefined;
82
+ } catch {
83
+ return undefined;
84
+ }
70
85
  }
71
86
 
72
87
  /**
package/src/core/lines.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  /**
2
- * Line text helpers: split/join with CRLF normalization, line-ending detection
2
+ * Line text helpers: split/join with CRLF normalization, the separator for new lines,
3
3
  * and final-newline fidelity.
4
4
  *
5
5
  * CRLF: splitLines normalizes `\r\n` boundaries while preserving standalone
6
- * `\r` content. detectLineEnding records whether the file uses CRLF at all
7
- * (any `\r\n` counts) so new boundaries added by an edit can use the file's
8
- * customary ending.
6
+ * `\r` content. newLineSeparator gives the separator for line boundaries an
7
+ * edit adds: CRLF when the file uses it at all (any `\r\n` counts), LF otherwise.
9
8
  *
10
9
  * Final newline: splitLines discards whether the input ended with a terminator
11
10
  * (a trailing newline terminates the last line, it does not create one).
@@ -16,18 +15,21 @@
16
15
  * @module pi-hashline-edit/core
17
16
  */
18
17
 
18
+ import type { CopiedSpan } from "./copy-span.ts";
19
+ import type { HalfOpenRange } from "./ranges.ts";
20
+
19
21
  /** Normalize CRLF boundaries to LF; standalone CR remains content. */
20
22
  export function normalizeLineEndings(text: string): string {
21
23
  return text.replace(/\r\n/g, "\n");
22
24
  }
23
25
 
24
- /** Raw separators in logical-line order, shared by both mutation applicators. */
25
- export function lineSeparators(text: string): string[] {
26
+ /** Raw separators in logical-line order. */
27
+ function lineSeparators(text: string): string[] {
26
28
  return text.match(/\r?\n/g) ?? [];
27
29
  }
28
30
 
29
31
  /** New internal gaps reuse the corresponding old gap, then the last gap or file style. */
30
- export function replacementSeparator(
32
+ function replacementSeparator(
31
33
  separators: readonly string[],
32
34
  index: number,
33
35
  fallback: string,
@@ -40,16 +42,44 @@ function preserveBoundaryCarriageReturn(previous: string, next: string): string
40
42
  return previous.endsWith("\r") && next.startsWith("\n") ? `\r${next}` : next;
41
43
  }
42
44
 
43
- /** Join independent raw fragments without absorbing trailing CR content into the next LF. */
44
- export function joinTextFragments(parts: readonly string[]): string {
45
+ /** Generated text or a half-open interval in the original raw UTF-16 text. */
46
+ export type TextFragment = string | HalfOpenRange;
47
+
48
+ /** Join raw fragments and report contiguous copied slices past any inserted CR. */
49
+ export function joinTextFragments(
50
+ source: string,
51
+ parts: readonly TextFragment[],
52
+ ): {
53
+ text: string;
54
+ copied: CopiedSpan[];
55
+ } {
45
56
  const joined: string[] = [];
57
+ const copied: CopiedSpan[] = [];
46
58
  let previous = "";
47
- for (const part of parts) {
48
- if (!part) continue;
49
- joined.push(preserveBoundaryCarriageReturn(previous, part));
50
- previous = part;
59
+ let targetEnd = 0;
60
+ for (const fragment of parts) {
61
+ const text = typeof fragment === "string" ? fragment : source.slice(...fragment);
62
+ if (!text) continue;
63
+ const part = preserveBoundaryCarriageReturn(previous, text);
64
+ joined.push(part);
65
+ if (typeof fragment !== "string") {
66
+ const [sourceStart] = fragment;
67
+ const targetStart = targetEnd + (part.length - text.length);
68
+ const last = copied[copied.length - 1];
69
+ if (
70
+ last &&
71
+ last.sourceStart + last.length === sourceStart &&
72
+ last.targetStart + last.length === targetStart
73
+ ) {
74
+ copied[copied.length - 1] = { ...last, length: last.length + text.length };
75
+ } else {
76
+ copied.push({ sourceStart, targetStart, length: text.length });
77
+ }
78
+ }
79
+ targetEnd += part.length;
80
+ previous = text;
51
81
  }
52
- return joined.join("");
82
+ return { text: joined.join(""), copied };
53
83
  }
54
84
 
55
85
  /** Restore a logical replacement without normalizing it a second time. */
@@ -100,9 +130,33 @@ export function splitLines(text: string): string[] {
100
130
  return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
101
131
  }
102
132
 
103
- /** Whether the text uses CRLF at all (any `\r\n` counts; mixed files report "crlf"). */
104
- export function detectLineEnding(text: string): "lf" | "crlf" {
105
- return text.includes("\r\n") ? "crlf" : "lf";
133
+ /**
134
+ * Index zero-based lines in raw UTF-16 offsets. end(line) excludes its terminator.
135
+ * start(length) is the EOF boundary.
136
+ */
137
+ export function indexSourceLines(text: string) {
138
+ const starts = [0];
139
+ for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) {
140
+ starts.push(at + 1);
141
+ }
142
+ if (starts[starts.length - 1] !== text.length) starts.push(text.length);
143
+
144
+ const end = (line: number) => {
145
+ const next = starts[line + 1];
146
+ if (text[next - 1] !== "\n") return next;
147
+ return next - (text[next - 2] === "\r" ? 2 : 1);
148
+ };
149
+ return {
150
+ length: starts.length - 1,
151
+ start: (line: number) => starts[line],
152
+ end,
153
+ content: (line: number) => text.slice(starts[line], end(line)),
154
+ };
155
+ }
156
+
157
+ /** The separator for a new line boundary: CRLF when the text uses it at all, mixed files included. */
158
+ export function newLineSeparator(text: string): "\r\n" | "\n" {
159
+ return text.includes("\r\n") ? "\r\n" : "\n";
106
160
  }
107
161
 
108
162
  /**
@@ -1,22 +1,23 @@
1
1
  /** Half-open bounds in a caller-selected unit (line indices or string offsets). */
2
- type HalfOpenRange = readonly [start: number, end: number];
2
+ export type HalfOpenRange = readonly [start: number, end: number];
3
3
 
4
4
  /**
5
5
  * Find the first conflicting pair's second index. Input must be sorted by start, then end.
6
6
  * A range starting inside an earlier non-empty range conflicts, and so do two insertions
7
7
  * (empty ranges) at one position. An insertion at the start of a non-empty range also
8
- * conflicts unless `insertBeforeRange` is set; then it applies before that range.
8
+ * conflicts under "reject-shared-start"; under "allow-insertion-before-range" it applies first.
9
9
  */
10
10
  export function findSortedRangeConflict(
11
11
  ranges: readonly HalfOpenRange[],
12
- insertBeforeRange = false,
12
+ policy: "reject-shared-start" | "allow-insertion-before-range",
13
13
  ): number | undefined {
14
14
  for (let i = 1; i < ranges.length; i++) {
15
15
  const previous = ranges[i - 1];
16
16
  const current = ranges[i];
17
17
  if (
18
18
  current[0] < previous[1] ||
19
- (current[0] === previous[0] && (!insertBeforeRange || current[1] === previous[1]))
19
+ (current[0] === previous[0] &&
20
+ (policy === "reject-shared-start" || current[1] === previous[1]))
20
21
  )
21
22
  return i;
22
23
  }
@@ -1,5 +1,6 @@
1
1
  /** Tool-validated replacement rules, the engine's result, and their types; no Pi runtime imports. */
2
2
  import { Type, type Static } from "typebox";
3
+ import { COPIED_SPAN_SCHEMA } from "./copy-span.ts";
3
4
 
4
5
  const REPLACEMENT_SCHEMA = Type.Object(
5
6
  {
@@ -30,11 +31,12 @@ export const REPLACEMENTS_SCHEMA = Type.Array(REPLACEMENT_SCHEMA, {
30
31
  });
31
32
  export type Replacement = Readonly<Static<typeof REPLACEMENT_SCHEMA>>;
32
33
 
33
- /** A replacement batch's new text and match count; the host checks it again across the worker boundary. */
34
+ /** A replacement batch’s result, checked by the host across the worker boundary. */
34
35
  export const REPLACEMENT_RESULT_SCHEMA = Type.Object(
35
36
  {
36
37
  text: Type.String(),
37
38
  count: Type.Integer({ minimum: 1 }),
39
+ copied: Type.Array(COPIED_SPAN_SCHEMA),
38
40
  },
39
41
  { additionalProperties: false },
40
42
  );
@@ -10,33 +10,55 @@
10
10
  import { buildRegex } from "./regex.ts";
11
11
  import {
12
12
  createLfTextView,
13
- detectLineEnding,
13
+ newLineSeparator,
14
14
  joinTextFragments,
15
15
  normalizeLineEndings,
16
16
  restoreLineEndings,
17
+ type TextFragment,
17
18
  } from "./lines.ts";
18
19
  import { findSortedRangeConflict } from "./ranges.ts";
19
20
  import { HashlineError } from "./errors.ts";
20
21
 
21
22
  import type { Replacement, ReplacementResult } from "./replace-schema.ts";
22
23
 
23
- /** Expand JS replacement tokens against the original match, including prefix/suffix context. */
24
- function expandReplacement(template: string, match: RegExpExecArray, source: string): string {
24
+ /** Expand JS replacement tokens, reusing a leading copy of the header when the match consumes it. */
25
+ function expandReplacement(template: string, match: RegExpExecArray, regex: RegExp): string {
26
+ const { index, input, groups } = match;
27
+ const consumesHeader = index === 0 && match[0].startsWith("\uFEFF");
25
28
  // Without named captures, $<...> is ordinary text and may contain other $ tokens.
26
- const tokens =
27
- match.groups === undefined ? /\$(\$|&|`|'|\d{1,2})/g : /\$(\$|&|`|'|<[^>]*>|\d{1,2})/g;
28
- return template.replace(tokens, (token, key: string) => {
29
+ const tokens = groups === undefined ? /\$(\$|&|`|'|\d{1,2})/g : /\$(\$|&|`|'|<[^>]*>|\d{1,2})/g;
30
+ // Track where a copy of the header can still be the first output character.
31
+ let leadingOffset = consumesHeader ? 0 : -1;
32
+ return template.replace(tokens, (token, key: string, offset: number) => {
29
33
  if (key === "$") return "$";
30
- if (key === "&") return match[0];
31
- if (key === "`") return source.slice(0, match.index);
32
- if (key === "'") return source.slice(match.index + match[0].length);
33
- if (key.startsWith("<")) return match.groups![key.slice(1, -1)] ?? "";
34
- const index = Number(key);
35
- if (index > 0 && index < match.length) return match[index] ?? "";
36
- // $12 falls back to capture 1 plus literal 2 when capture 12 does not exist.
37
- const first = Number(key[0]);
38
- if (key.length === 2 && first > 0 && first < match.length) return (match[first] ?? "") + key[1];
39
- return token;
34
+ if (key === "&") return offset === leadingOffset ? match[0].slice(1) : match[0];
35
+
36
+ let text: string;
37
+ let capture: string | number | undefined;
38
+ if (key === "`") text = input.slice(0, index);
39
+ else if (key === "'") text = input.slice(index + match[0].length);
40
+ else if (key.startsWith("<")) {
41
+ capture = key.slice(1, -1);
42
+ text = groups?.[capture] ?? "";
43
+ } else {
44
+ // Prefer the whole reference ($01 is capture 1), then try just its first digit.
45
+ const digits = Number(key) < match.length ? key : key[0];
46
+ capture = Number(digits);
47
+ if (capture === 0 || capture >= match.length) return token;
48
+ text = (match[capture] ?? "") + key.slice(digits.length);
49
+ }
50
+
51
+ if (offset !== leadingOffset) return text;
52
+ if (text === "") {
53
+ leadingOffset += token.length;
54
+ return text;
55
+ }
56
+ if (capture === undefined || text[0] !== input[0]) return text;
57
+
58
+ // Adding d to the same regex at offset zero yields this match with capture offsets.
59
+ const indices = match.indices ?? new RegExp(regex, `${regex.flags}d`).exec(input)!.indices!;
60
+ const span = typeof capture === "number" ? indices[capture] : indices.groups?.[capture];
61
+ return span?.[0] === 0 ? text.slice(1) : text;
40
62
  });
41
63
  }
42
64
 
@@ -49,7 +71,8 @@ export function applyReplacements(
49
71
  ): ReplacementResult {
50
72
  const changes: { start: number; end: number; text: string; rule: number }[] = [];
51
73
  const view = createLfTextView(source);
52
- const fallbackEnding = detectLineEnding(source) === "crlf" ? "\r\n" : "\n";
74
+ const bom = source.startsWith("\uFEFF") ? source[0] : "";
75
+ const fallbackEnding = newLineSeparator(source);
53
76
  const unmatched: string[] = [];
54
77
  for (const [index, rule] of rules.entries()) {
55
78
  const regex = buildRegex(rule.find, rule.literal, rule.flags);
@@ -64,7 +87,7 @@ export function applyReplacements(
64
87
  end,
65
88
  rule: index,
66
89
  text: restoreLineEndings(
67
- rule.literal ? replacement : expandReplacement(replacement, match, view.text),
90
+ rule.literal ? replacement : expandReplacement(replacement, match, regex),
68
91
  source.slice(start, end),
69
92
  fallbackEnding,
70
93
  ),
@@ -77,7 +100,10 @@ export function applyReplacements(
77
100
  facts: { unmatched },
78
101
  });
79
102
  changes.sort((a, b) => a.start - b.start || a.end - b.end);
80
- const conflict = findSortedRangeConflict(changes.map((change) => [change.start, change.end]));
103
+ const conflict = findSortedRangeConflict(
104
+ changes.map((change) => [change.start, change.end]),
105
+ "reject-shared-start",
106
+ );
81
107
  if (conflict !== undefined) {
82
108
  const previous = changes[conflict - 1];
83
109
  const current = changes[conflict];
@@ -88,18 +114,13 @@ export function applyReplacements(
88
114
  },
89
115
  });
90
116
  }
91
- const bom = source.startsWith("\uFEFF") ? "\uFEFF" : "";
92
- const parts: string[] = [bom];
117
+ const parts: TextFragment[] = [[0, bom.length]];
118
+ // The header is copied separately, even when a match consumes it.
93
119
  let cursor = bom.length;
94
120
  for (const change of changes) {
95
- // Keep the original header at byte zero; a copied leading BOM denotes that same header.
96
- const text =
97
- bom && change.start === 0 && change.end > 0 && change.text.startsWith(bom)
98
- ? change.text.slice(1)
99
- : change.text;
100
- parts.push(source.slice(cursor, Math.max(bom.length, change.start)), text);
121
+ parts.push([cursor, Math.max(bom.length, change.start)], change.text);
101
122
  cursor = Math.max(bom.length, change.end);
102
123
  }
103
- parts.push(source.slice(cursor));
104
- return { text: joinTextFragments(parts), count: changes.length };
124
+ parts.push([cursor, source.length]);
125
+ return { ...joinTextFragments(source, parts), count: changes.length };
105
126
  }
@@ -45,8 +45,12 @@ interface Info {
45
45
  readonly filter: Prefilter;
46
46
  }
47
47
 
48
- const EMPTY: Info = { exact: [[]], filter: ALL };
49
- const UNKNOWN: Info = { exact: [[GAP]], filter: ALL };
48
+ const EMPTY = { exact: [[]], filter: ALL } satisfies Info;
49
+ const UNKNOWN = { exact: [[GAP]], filter: ALL } satisfies Info;
50
+
51
+ /** A node whose exact texts are known. */
52
+ const hasExact = (info: Info): info is Info & { readonly exact: readonly Sequence[] } =>
53
+ info.exact !== undefined;
50
54
 
51
55
  interface Context {
52
56
  readonly ignoreCase: boolean;
@@ -84,7 +88,7 @@ function distinct<T>(values: readonly T[]): T[] {
84
88
 
85
89
  function literalFilter(values: readonly Literal[]): Prefilter {
86
90
  let literals = distinct(values);
87
- if (!literals.length || literals.some((literal) => !literal.length)) return ALL;
91
+ if (!literals.length) return ALL;
88
92
  if (literals.length <= MAX_LITERALS) return { kind: "literals", literals };
89
93
  // Keep every branch while shortening its necessary prefix or suffix.
90
94
  for (let length = MAX_SEQUENCE_LENGTH; length >= 1; length = Math.floor(length / 2)) {
@@ -179,8 +183,8 @@ function concatenate(infos: readonly Info[]): Info {
179
183
  }
180
184
 
181
185
  function alternate(infos: readonly Info[]): Info {
182
- if (infos.every((info) => info.exact)) {
183
- const exact = distinct(infos.flatMap((info) => info.exact!));
186
+ if (infos.every(hasExact)) {
187
+ const exact = distinct(infos.flatMap((info) => info.exact));
184
188
  if (exact.length <= MAX_SEQUENCES)
185
189
  return { exact, filter: orFilters(infos.map((info) => info.filter)) };
186
190
  }
@@ -206,7 +210,7 @@ function quantified(node: AST.Quantifier, ctx: Context): Info {
206
210
  if (exact.length <= MAX_SEQUENCES) return { exact, filter: ALL };
207
211
  }
208
212
  // The repetitions beyond the minimum are text of unknown length.
209
- const exact = head && cross(head, UNKNOWN.exact!);
213
+ const exact = head && cross(head, UNKNOWN.exact);
210
214
  if (exact) return { exact, filter: node.min ? inner.filter : ALL };
211
215
  }
212
216
  return node.min === 0 ? UNKNOWN : { filter: filterOf(inner) };
@@ -221,7 +225,7 @@ function classInfo(node: CharacterNode, ctx: Context): Info {
221
225
  for (let point = low; point <= high; point++)
222
226
  units.push(charUnit(point, { ignoreCase: false }));
223
227
  // A class that matches nothing has no exact text.
224
- return alternate(units.length ? [{ exact: [[unionUnits(units)]], filter: ALL }] : []);
228
+ return { exact: units.length ? [[unionUnits(units)]] : [], filter: ALL };
225
229
  }
226
230
 
227
231
  function analyzeElement(node: AST.Element, ctx: Context): Info {
@@ -294,26 +298,21 @@ export function analyzeQueryPattern<T>(
294
298
  }
295
299
 
296
300
  /**
297
- * Smart case over decoded characters, a surrogate pair counting as its supplementary
298
- * character; case-sensitive when a pattern cannot be analyzed.
301
+ * Smart case over the characters the pattern spells, a surrogate pair counting as its
302
+ * supplementary character; case-sensitive when a pattern cannot be analyzed. The pair is
303
+ * decided by source adjacency, because a quantifier can hold the low half alone.
299
304
  */
300
305
  export function smartIgnoreCase(patterns: readonly string[], literal: boolean): boolean {
301
306
  return !patterns.some((pattern) => {
302
307
  const uppercase = analyzeQueryPattern(pattern, literal, (parsed) => {
303
- let found = false;
304
- visitRegExpAST(parsed, {
305
- onCharacterEnter(node) {
306
- const { parent } = node;
307
- const siblings: readonly AST.Node[] =
308
- parent.type === "Alternative" || parent.type === "CharacterClass"
309
- ? parent.elements
310
- : [];
311
- const point = surrogatePair(node, siblings[siblings.indexOf(node) + 1]) ?? node.value;
312
- const text = String.fromCodePoint(point);
313
- found ||= text !== text.toLowerCase();
314
- },
308
+ const characters: AST.Character[] = [];
309
+ visitRegExpAST(parsed, { onCharacterEnter: (node) => characters.push(node) });
310
+ return characters.some((node, index) => {
311
+ const next = characters[index + 1];
312
+ const point = (next?.start === node.end && surrogatePair(node, next)) || node.value;
313
+ const text = String.fromCodePoint(point);
314
+ return text !== text.toLowerCase();
315
315
  });
316
- return found;
317
316
  });
318
317
  return uppercase ?? true;
319
318
  });
@@ -13,19 +13,12 @@ export interface GrepQuery {
13
13
  readonly multiline: boolean;
14
14
  }
15
15
  export interface SearchInput {
16
+ /** Decoded physical lines with original terminators. Multiline needs the whole file.
17
+ * Result line numbers start at 1 in this input, including when line mode receives a subset. */
16
18
  readonly source: string;
17
19
  readonly query: GrepQuery;
18
20
  readonly limit: number;
19
21
  }
20
- /**
21
- * Selected physical lines of an LF view, each followed by a line feed. Unlike a source, they
22
- * are not normalized: a line keeps a CR that ends it.
23
- */
24
- export interface LineSearchInput {
25
- readonly lines: string;
26
- readonly query: GrepQuery;
27
- readonly limit: number;
28
- }
29
22
  type Rows = SearchResult["lines"];
30
23
 
31
24
  function mergeRows(left: Rows, right: Rows, limit: number): Rows {
@@ -48,27 +41,22 @@ function mergeRows(left: Rows, right: Rows, limit: number): Rows {
48
41
 
49
42
  function multilineRows(source: string, regex: RegExp, limit: number): Rows {
50
43
  const rows: Rows = [];
51
- let lineNumber = 1;
52
- let lineStart = 0;
53
- let nextBreak = source.indexOf("\n");
44
+ let nextStart = 0;
45
+ let lineNumber = 0;
54
46
  for (const match of source.matchAll(regex)) {
55
- // A trailing separator terminates the last physical line; it does not create another.
56
- if (match.index === source.length && (source.length === 0 || source.endsWith("\n"))) break;
47
+ // An EOF-only match after LF needs no walk over the preceding physical lines.
48
+ if (match.index === source.length && source.endsWith("\n")) break;
57
49
  const last = match.index + Math.max(0, match[0].length - 1);
58
- while (nextBreak !== -1 && nextBreak < match.index) {
59
- lineStart = nextBreak + 1;
50
+ // Visit a physical line only once. Later matches on it cannot move its first column.
51
+ while (nextStart < source.length && nextStart <= last) {
52
+ const start = nextStart;
53
+ const lf = source.indexOf("\n", start);
54
+ const end = lf === -1 ? source.length : lf;
55
+ nextStart = end + 1;
60
56
  lineNumber++;
61
- nextBreak = source.indexOf("\n", lineStart);
62
- }
63
- for (;;) {
64
- if (rows.at(-1)?.lineNumber !== lineNumber) {
65
- rows.push({ lineNumber, column: Math.max(0, match.index - lineStart) });
66
- if (rows.length === limit) return rows;
67
- }
68
- if (nextBreak === -1 || nextBreak >= last) break;
69
- lineStart = nextBreak + 1;
70
- lineNumber++;
71
- nextBreak = source.indexOf("\n", lineStart);
57
+ if (end < match.index) continue;
58
+ rows.push({ lineNumber, column: Math.max(0, match.index - start) });
59
+ if (rows.length === limit) return rows;
72
60
  }
73
61
  }
74
62
  return rows;
@@ -114,8 +102,3 @@ export function searchText({ source: raw, query, limit }: SearchInput): SearchRe
114
102
  } else lines = lineRows(source, regexes, limit);
115
103
  return { lines };
116
104
  }
117
-
118
- /** Line-mode matching of selected lines; a row's lineNumber is the line's 1-based position. */
119
- export function searchLines({ lines, query, limit }: LineSearchInput): SearchResult {
120
- return { lines: lineRows(lines, queryRegexes(query), limit) };
121
- }
package/src/core/types.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  * @module pi-hashline-edit/core
5
5
  */
6
6
 
7
+ import type { CopiedSpan } from "./copy-span.ts";
8
+
7
9
  /** Line anchor: dual reference of line number (1-based) + content hash. */
8
10
  export interface Anchor {
9
11
  readonly line: number;
@@ -81,5 +83,6 @@ export type ApplyResult =
81
83
  | {
82
84
  readonly ok: true;
83
85
  readonly text: string;
86
+ readonly copied: readonly CopiedSpan[];
84
87
  }
85
88
  | { readonly ok: false; readonly failures: readonly AnchorFailure[] };
package/src/index.ts CHANGED
@@ -10,9 +10,13 @@
10
10
  * @module pi-hashline-edit
11
11
  */
12
12
 
13
- import { isAbsolute, join } from "node:path";
14
- import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
15
- import type { TSchema } from "typebox";
13
+ import {
14
+ type ExtensionAPI,
15
+ SettingsManager,
16
+ type ToolDefinition,
17
+ } from "@earendil-works/pi-coding-agent";
18
+ import type { Static, TSchema } from "typebox";
19
+ import { createRenderArguments } from "./pi/argument-validation.ts";
16
20
  import { loadConfig } from "./pi/config.ts";
17
21
  import { registerModelBudgets } from "./pi/model-budgets.ts";
18
22
  import { makeEditOverride } from "./pi/edit-tool.ts";
@@ -20,36 +24,16 @@ import { makeReadOverride } from "./pi/read-tool.ts";
20
24
  import { makeGrepOverride } from "./pi/grep-tool.ts";
21
25
  import { makeReplaceTool } from "./pi/replace-tool.ts";
22
26
  import { makeWriteOverride } from "./pi/write-tool.ts";
23
- import { createActionFusionExecutor } from "./pi/action-fusion.ts";
27
+ import { createActionFusionScheduler, observeFusionToolCall } from "./pi/action-fusion.ts";
28
+ import { runAlone } from "./pi/mutation-runner.ts";
24
29
  import { registerFusionCards, withMutationStatus } from "./pi/fusion-card.ts";
30
+ import type { ToolGuidelines } from "./pi/schema.ts";
25
31
  import { NEXT_GUIDELINE } from "./pi/report-schema.ts";
32
+ import { resolveWorkspace } from "./pi/workspace.ts";
26
33
 
27
34
  export default async function (pi: ExtensionAPI) {
28
- // Pi runs exec in the extension loader's workspace, even before session_start.
29
- // Replay on reload needs tools and entry renderers registered before that event.
30
- // Ask the OS directly so a second Node runtime cannot rerun the host's preloads.
31
- const windows = process.platform === "win32";
32
- const result = windows
33
- ? await pi.exec(
34
- join(
35
- process.env.SystemRoot ?? "C:\\Windows",
36
- "System32/WindowsPowerShell/v1.0/powershell.exe",
37
- ),
38
- [
39
- "-NoProfile",
40
- "-NonInteractive",
41
- "-Command",
42
- "[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); [Console]::Write([Environment]::CurrentDirectory)",
43
- ],
44
- )
45
- : await pi.exec("/bin/pwd", ["-P"]);
46
- const { stderr, code, killed, truncated } = result;
47
- const cwd = windows ? result.stdout : result.stdout.replace(/\n$/, "");
48
- if (code !== 0 || killed || truncated || !isAbsolute(cwd)) {
49
- throw new Error(`Unable to resolve the Pi workspace (exit ${code})`, {
50
- cause: stderr || undefined,
51
- });
52
- }
35
+ // Replay on reload needs tools and entry renderers registered before session_start.
36
+ const cwd = await resolveWorkspace(pi);
53
37
 
54
38
  // Tools capture this snapshot at registration; a reload registers them again.
55
39
  const config = loadConfig(cwd);
@@ -60,25 +44,49 @@ export default async function (pi: ExtensionAPI) {
60
44
  const budgets = registerModelBudgets(pi);
61
45
  // Saved then_run cards render even when Action Fusion is off.
62
46
  const reportProgress = registerFusionCards(pi);
63
- const fusion = config.actionFusion ? createActionFusionExecutor(reportProgress) : undefined;
47
+ const schedule = config.actionFusion ? createActionFusionScheduler(reportProgress) : runAlone;
48
+ if (config.actionFusion) pi.on("tool_call", observeFusionToolCall);
64
49
  // Every tool returns a report; Pi prints this shared guideline once.
65
50
  const register = <TParams extends TSchema, TDetails, TState>(
66
- tool: ToolDefinition<TParams, TDetails, TState>,
67
- ) =>
68
- pi.registerTool({
51
+ tool: ToolDefinition<TParams, TDetails, TState> & ToolGuidelines,
52
+ ) => {
53
+ const { renderCall, renderResult } = tool;
54
+ const coerce = createRenderArguments(tool.parameters);
55
+ const view = (args: unknown) => coerce(args) as Static<TParams>;
56
+ const registered: ToolDefinition<TParams, TDetails, TState> = {
69
57
  ...tool,
70
- promptGuidelines: [...(tool.promptGuidelines ?? []), NEXT_GUIDELINE],
71
- });
58
+ promptGuidelines: [...tool.promptGuidelines, NEXT_GUIDELINE],
59
+ renderCall:
60
+ renderCall &&
61
+ ((args, theme, context) => {
62
+ // Pi passes the same arguments as `args` and `context.args`.
63
+ const viewed = view(args);
64
+ return renderCall(viewed, theme, { ...context, args: viewed });
65
+ }),
66
+ renderResult:
67
+ renderResult &&
68
+ ((result, options, theme, context) =>
69
+ renderResult(result, options, theme, { ...context, args: view(context.args) })),
70
+ };
71
+ pi.registerTool(registered);
72
+ };
72
73
  const registerMutation = <TParams extends TSchema, TDetails>(
73
- tool: ToolDefinition<TParams, TDetails>,
74
- ) => register(fusion ? withMutationStatus(tool) : tool);
74
+ tool: ToolDefinition<TParams, TDetails> & ToolGuidelines,
75
+ ) => register(config.actionFusion ? withMutationStatus(tool) : tool);
75
76
  const env = { cwd, config, budgets };
76
- const mutationEnv = { ...env, fusion };
77
+ const mutationEnv = { ...env, schedule };
77
78
  registerMutation(makeWriteOverride(mutationEnv));
78
79
  registerMutation(makeEditOverride(mutationEnv));
79
80
  registerMutation(makeReplaceTool(mutationEnv));
80
81
 
81
- register(makeReadOverride(env));
82
+ let autoResizeImages: boolean | undefined;
83
+ const readAutoResize = () =>
84
+ (autoResizeImages ??= SettingsManager.inMemory(pi.getSettings()).getImageAutoResize());
85
+ // Pi snapshots the setting when it builds the native tool. Headless reload can skip session_start.
86
+ pi.on("session_start", () => {
87
+ readAutoResize();
88
+ });
89
+ register(makeReadOverride(env, readAutoResize));
82
90
  register(makeGrepOverride(env));
83
91
  }
84
92
  }