@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
@@ -1,4 +1,4 @@
1
- /** Serialize regex requests in one worker; timeout, cancellation, and cleanup have one owner. */
1
+ /** Own one regex worker's timeout, cancellation, and cleanup; callers await each request. */
2
2
  import { Worker, type ResourceLimits } from "node:worker_threads";
3
3
  import { HashlineError } from "../core/errors.ts";
4
4
  import { cancellationError, throwIfCancelled } from "./error-text.ts";
@@ -57,9 +57,9 @@ export async function withRegexWorker<Input, Result, Output>(
57
57
  ),
58
58
  );
59
59
  signal?.addEventListener("abort", abort, { once: true });
60
- let queue = Promise.resolve();
61
- const run = (input: Input): Promise<Result> => {
62
- const result = queue.then(() => {
60
+ // Keep dispatch asynchronous so cancellation can be observed before posting a request.
61
+ const run = (input: Input): Promise<Result> =>
62
+ Promise.resolve().then(() => {
63
63
  throwIfCancelled(signal);
64
64
  if (failure) throw failure;
65
65
  return new Promise<Result>((resolve, reject) => {
@@ -84,12 +84,6 @@ export async function withRegexWorker<Input, Result, Output>(
84
84
  }
85
85
  });
86
86
  });
87
- queue = result.then(
88
- () => undefined,
89
- () => undefined,
90
- );
91
- return result;
92
- };
93
87
  try {
94
88
  if (signal?.aborted) abort();
95
89
  return await execute(run);
@@ -1,6 +1,10 @@
1
1
  import { rejectsArgument } from "./argument-error.testing.ts";
2
2
  import { createEditTool } from "@earendil-works/pi-coding-agent";
3
3
  import { validateToolArguments } from "@earendil-works/pi-ai";
4
+ import {
5
+ makeStrictJsonSchema,
6
+ resolveJsonSchemaStrictSampling,
7
+ } from "@earendil-works/pi-ai/api/constrained-sampling";
4
8
  import { makeEditOverride } from "./edit-tool.ts";
5
9
  import { makeReadOverride } from "./read-tool.ts";
6
10
  import { loadConfig } from "./config.ts";
@@ -12,15 +16,50 @@ import assert from "node:assert/strict";
12
16
  import { test } from "node:test";
13
17
  import registerHashline from "../index.ts";
14
18
  import { initTheme } from "@earendil-works/pi-coding-agent";
19
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
20
+ import { ProcessTerminal, TuiMainScreen } from "@earendil-works/pi-tui";
15
21
  import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
16
22
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
17
23
  import { computeLineHash } from "../core/hash.ts";
18
24
  import { callTool } from "./tool-call.testing.ts";
19
25
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
- import type { ActionFusionProgress } from "./action-fusion.ts";
26
+ import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
21
27
  import { reportOf } from "./report.ts";
28
+ import { formatByteSize } from "./budgets.ts";
22
29
  import { expectToolFailure } from "./report-failure.testing.ts";
23
30
 
31
+ test("edit with or without Fusion → expose parameters usable by Pi strict sampling", () => {
32
+ for (const fusion of [undefined, createActionFusionExecutor()]) {
33
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG, fusion);
34
+ assert.deepEqual(tool.constrainedSampling, { type: "json_schema", strict: "prefer" });
35
+ assert.equal(resolveJsonSchemaStrictSampling(tool, true), true);
36
+ const strict = makeStrictJsonSchema(tool.parameters);
37
+ assert.partialDeepStrictEqual(strict, {
38
+ type: "object",
39
+ additionalProperties: false,
40
+ required: fusion ? ["path", "edits", "then_run"] : ["path", "edits"],
41
+ properties: {
42
+ edits: {
43
+ type: "array",
44
+ items: {
45
+ type: "object",
46
+ additionalProperties: false,
47
+ required: ["action", "anchor", "end", "body", "before", "after"],
48
+ properties: {
49
+ anchor: { anyOf: [{ type: "string" }, { type: "null" }] },
50
+ end: { anyOf: [{ type: "string" }, { type: "null" }] },
51
+ body: { anyOf: [{ type: "array" }, { type: "null" }] },
52
+ before: { anyOf: [{ type: "string" }, { type: "null" }] },
53
+ after: { anyOf: [{ type: "string" }, { type: "null" }] },
54
+ },
55
+ },
56
+ },
57
+ ...(fusion ? { then_run: { anyOf: [{ type: "object" }, { type: "null" }] } } : {}),
58
+ },
59
+ });
60
+ }
61
+ });
62
+
24
63
  test("mutation cards use Fusion by default and explicit false removes command support", async () => {
25
64
  const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
26
65
  const previousCwd = process.cwd();
@@ -34,8 +73,14 @@ test("mutation cards use Fusion by default and explicit false removes command su
34
73
  const tools: any[] = [];
35
74
  const entries: any[] = [];
36
75
  const renderers = new Map<string, any>();
76
+ let start: ((event: unknown, ctx: unknown) => void) | undefined;
37
77
  registerHashline({
38
- on() {},
78
+ on(event: string, handler: (event: unknown, ctx: unknown) => void) {
79
+ if (event === "session_start") start = handler;
80
+ },
81
+ getSettings() {
82
+ return {};
83
+ },
39
84
  registerEntryRenderer(type: string, renderer: any) {
40
85
  renderers.set(type, renderer);
41
86
  },
@@ -65,8 +110,8 @@ test("mutation cards use Fusion by default and explicit false removes command su
65
110
  ]);
66
111
  assert.equal(grep.parameters.additionalProperties, false);
67
112
  await assert.rejects(
68
- callTool(grep, { pattern: "needle", literal: true, noIgnore: false }),
69
- rejectsArgument("noIgnore", /not allowed/),
113
+ callTool(grep, { pattern: "needle", literal: true, unexpected: true }),
114
+ rejectsArgument("unexpected", /not allowed/),
70
115
  );
71
116
  for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
72
117
  assert.ok(
@@ -80,28 +125,38 @@ test("mutation cards use Fusion by default and explicit false removes command su
80
125
  );
81
126
  }
82
127
  initTheme("dark");
128
+ const tui = new TuiMainScreen(new ProcessTerminal());
129
+ tui.requestRender = () => {};
130
+ assert.ok(start);
131
+ start(
132
+ {},
133
+ {
134
+ cwd: dir,
135
+ mode: "tui",
136
+ sessionManager: { getBranch: () => entries },
137
+ ui: {
138
+ setWidget(_key: string, content: Parameters<ExtensionContext["ui"]["setWidget"]>[1]) {
139
+ if (typeof content === "function") content(tui, theme);
140
+ },
141
+ },
142
+ },
143
+ );
83
144
  const cases = [
84
145
  { name: "write", args: { content: "published\n", mode: "create" } },
85
- { name: "edit", args: { edits: [{ op: "append", body: ["appended"] }] } },
86
- { name: "replace", args: { replacements: [{ find: "published", replace: "published" }] } },
87
- ];
146
+ { name: "edit", args: { edits: [{ action: "append", body: ["appended"] }] } },
147
+ {
148
+ name: "replace",
149
+ args: { replacements: [{ literal: true, find: "published", replace: "published" }] },
150
+ },
151
+ ] as const;
88
152
  for (const { name, args } of cases) {
89
153
  const tool = tools.find((tool) => tool.name === name);
90
154
  const params = { path: "published.txt", ...args, then_run: { command: "exit 7" } };
91
- const card = new ToolExecutionComponent(
92
- name,
93
- name,
94
- params,
95
- {},
96
- tool,
97
- { requestRender() {} } as any,
98
- dir,
99
- );
155
+ const card = new ToolExecutionComponent(name, name, params, {}, tool, tui, dir);
100
156
  card.setArgsComplete();
101
157
  card.markExecutionStarted();
102
158
  const frames: {
103
159
  command: string;
104
- publication: string;
105
160
  mutationCompleted: boolean;
106
161
  output: string;
107
162
  commandOutput: string;
@@ -127,12 +182,11 @@ test("mutation cards use Fusion by default and explicit false removes command su
127
182
  },
128
183
  ctx: { cwd: dir },
129
184
  });
130
- assert.equal(result.details.actionFusion.command, "failed");
131
185
  assert.equal(
132
- reportOf(result)?.publication,
186
+ reportOf(result, name)?.publication,
133
187
  name === "replace" ? "NOT_PUBLISHED" : "PUBLISHED",
134
188
  );
135
- assert.equal(reportOf(result)?.then_run?.status, "failed");
189
+ assert.equal(reportOf(result, name)?.then_run?.status, "failed");
136
190
  assert.ok(frames[0].output.includes(theme.getBgAnsi("toolPendingBg")));
137
191
  const running = frames.find((frame) => frame.command === "running")!;
138
192
  assert.ok(running, `${name} should emit running progress`);
@@ -158,18 +212,13 @@ test("mutation cards use Fusion by default and explicit false removes command su
158
212
  assert.ok(frame.expandedOutput.includes(expectedBackground));
159
213
  }
160
214
  if (name === "replace") {
161
- assert.equal(running.publication, "NOT_PUBLISHED");
162
- assert.match(running.output, /No net change/);
215
+ assert.match(running.output, /No diff available/);
163
216
  }
164
217
  card.updateResult({ ...result, isError: false });
165
218
  assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
219
+ if (name === "replace") assert.match(card.render(100).join("\n"), /No net change/);
166
220
  card.setExpanded(true);
167
- assert.doesNotMatch(card.render(100).join("\n"), /publication=|freshness=/);
168
- assert.doesNotMatch(card.render(100).join("\n"), /Command exited|then_run:failed/);
169
- assert.doesNotMatch(
170
- frames.at(-1)!.commandOutput,
171
- /publication=|freshness=|File changes are saved|No file changes were published|mutation completed/,
172
- );
221
+ assert.doesNotMatch(card.render(100).join("\n"), /Command exited/);
173
222
  assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
174
223
 
175
224
  const invalid = {
@@ -183,19 +232,17 @@ test("mutation cards use Fusion by default and explicit false removes command su
183
232
  invalid,
184
233
  {},
185
234
  tool,
186
- { requestRender() {} } as any,
235
+ tui,
187
236
  dir,
188
237
  );
189
- const failed = await tool.execute(
190
- `${name}-bad`,
191
- invalid,
192
- undefined,
193
- (update: AgentToolResult<unknown>) =>
238
+ const failed = await callTool(tool, invalid, {
239
+ toolCallId: `${name}-bad`,
240
+ onUpdate: (update: AgentToolResult<unknown>) =>
194
241
  failedCard.updateResult({ ...update, isError: false }, true),
195
- { cwd: dir },
196
- );
242
+ ctx: { cwd: dir },
243
+ });
197
244
  assert.equal(failed.isError, true);
198
- const report = reportOf(failed);
245
+ const report = reportOf(failed, name);
199
246
  assert.equal(report?.error, "PATH_NOT_FOUND");
200
247
  failedCard.updateResult(failed);
201
248
  const output = failedCard.render(100).join("\n");
@@ -218,7 +265,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
218
265
  .render(160)
219
266
  .join("\n");
220
267
  assert.match(commandOutput, /skipped[\s\S]*Not run.*mutation did not complete/);
221
- assert.doesNotMatch(commandOutput, /Error reading|does not exist|publication=|freshness=/);
268
+ assert.doesNotMatch(commandOutput, /Error reading|does not exist/);
222
269
  assert.ok(!commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
223
270
  }
224
271
  assert.deepEqual(
@@ -237,28 +284,20 @@ test("mutation cards use Fusion by default and explicit false removes command su
237
284
  const edit = tools.find((tool) => tool.name === "edit");
238
285
  const stale = {
239
286
  path: "stale.txt",
240
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, body: ["changed"] }],
287
+ edits: [
288
+ { action: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, body: ["changed"] },
289
+ ],
241
290
  then_run: { command: "exit 99" },
242
291
  };
243
- const staleCard = new ToolExecutionComponent(
244
- "edit",
245
- "stale",
246
- stale,
247
- {},
248
- edit,
249
- { requestRender() {} } as any,
250
- dir,
251
- );
252
- const failed = await edit.execute(
253
- "stale",
254
- stale,
255
- undefined,
256
- (update: AgentToolResult<unknown>) =>
292
+ const staleCard = new ToolExecutionComponent("edit", "stale", stale, {}, edit, tui, dir);
293
+ const failed = await callTool(edit, stale, {
294
+ toolCallId: "stale",
295
+ onUpdate: (update: AgentToolResult<unknown>) =>
257
296
  staleCard.updateResult({ ...update, isError: false }, true),
258
- { cwd: dir },
259
- );
297
+ ctx: { cwd: dir },
298
+ });
260
299
  assert.equal(failed.isError, true);
261
- assert.equal(reportOf(failed)?.failures?.[0].result, "shifted");
300
+ assert.equal(reportOf(failed, "edit")?.failures?.[0].result, "shifted");
262
301
  staleCard.updateResult(failed);
263
302
  assert.match(staleCard.render(160).join("\n"), /ANCHOR_MISMATCH/);
264
303
  const entry = entries.find(
@@ -269,10 +308,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
269
308
  .render(160)
270
309
  .join("\n");
271
310
  assert.match(commandOutput, /skipped/);
272
- assert.doesNotMatch(
273
- commandOutput,
274
- /ANCHOR_MISMATCH|candidate|Input-anchor|publication=|freshness=/,
275
- );
311
+ assert.doesNotMatch(commandOutput, /ANCHOR_MISMATCH|candidate/);
276
312
  assert.equal(await readFile(join(dir, "stale.txt"), "utf8"), "header\ntarget\n");
277
313
  await writeFile(
278
314
  join(dir, ".pi", "settings.json"),
@@ -383,7 +419,7 @@ test("loaded configuration controls hash length and recovery radius", async () =
383
419
  await expectToolFailure(
384
420
  call(makeEditOverride(dir, config), {
385
421
  path: "configured.txt",
386
- edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
422
+ edits: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
387
423
  }),
388
424
  "ANCHOR_MISMATCH",
389
425
  (report) => {
@@ -406,16 +442,19 @@ test("configured read defaults bound omitted limits and returned bytes", async (
406
442
  assert.match(description, /default 2\)/);
407
443
  await writeFile(join(dir, "short.txt"), "a\nb\nc\n");
408
444
  const paged = await call(read, { path: "short.txt" });
409
- assert.deepEqual(paged.details.pagination, { start: 1, end: 2, totalLines: 3, nextOffset: 3 });
410
- assert.match(reportOf(paged)?.next ?? "", /offset.*pagination\.nextOffset/);
445
+ assert.deepEqual(reportOf(paged, "read")?.pagination, {
446
+ start: 1,
447
+ end: 2,
448
+ totalLines: 3,
449
+ nextOffset: 3,
450
+ });
451
+ assert.match(reportOf(paged, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
411
452
  assert.match(paged.content[0].text, /^2#[0-9A-Z]+│b$/m);
412
453
  assert.doesNotMatch(paged.content[0].text, /^3#/m);
413
454
  const explicit = await call(read, { path: "short.txt", limit: 3 });
414
455
  assert.match(explicit.content[0].text, /^3#[0-9A-Z]+│c$/m);
415
456
  await writeFile(join(dir, "wide.txt"), `${"x".repeat(2048)}\n`);
416
457
  const wide = await call(read, { path: "wide.txt" });
417
- assert.equal(wide.details.truncation.firstLineExceedsLimit, true);
418
- assert.equal(wide.details.truncation.outputLines, 0);
419
- assert.equal(wide.details.truncation.maxBytes, 1024);
420
- assert.equal(wide.details.truncation.outputBytes, 0);
458
+ assert.deepEqual(reportOf(wide, "read")?.lineTooLong, { line: 1, limit: formatByteSize(1024) });
459
+ assert.doesNotMatch(wide.content[0].text, /^\d+#/m);
421
460
  }));