@criogaid/pi-hashline-edit 0.4.0 → 0.5.1

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 (66) hide show
  1. package/README.md +134 -30
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.test.ts +30 -1
  10. package/src/core/text.ts +9 -6
  11. package/src/core/types.ts +4 -7
  12. package/src/index.ts +9 -11
  13. package/src/integration/config-registration.test.ts +206 -0
  14. package/src/integration/grep-rg.test.ts +285 -153
  15. package/src/integration/large-text.test.ts +11 -12
  16. package/src/integration/replace-package.test.ts +11 -7
  17. package/src/pi/action-fusion.test.ts +251 -39
  18. package/src/pi/action-fusion.ts +113 -117
  19. package/src/pi/anchor-format.test.ts +91 -24
  20. package/src/pi/anchor-format.ts +43 -9
  21. package/src/pi/budgets.ts +7 -2
  22. package/src/pi/config.test.ts +153 -40
  23. package/src/pi/config.ts +87 -41
  24. package/src/pi/diagnostic-buffer.test.ts +58 -0
  25. package/src/pi/diagnostic-buffer.ts +59 -0
  26. package/src/pi/e2e-scenarios.test.ts +13 -11
  27. package/src/pi/edit-tool.ts +21 -157
  28. package/src/pi/error-text.ts +10 -5
  29. package/src/pi/execute.test.ts +299 -175
  30. package/src/pi/failure-context.test.ts +7 -2
  31. package/src/pi/failure-context.ts +155 -8
  32. package/src/pi/failure-path.test.ts +33 -26
  33. package/src/pi/file-commit.ts +2 -1
  34. package/src/pi/fusion-card.test.ts +26 -0
  35. package/src/pi/fusion-card.ts +102 -6
  36. package/src/pi/grep-output.ts +50 -35
  37. package/src/pi/grep-render.ts +13 -15
  38. package/src/pi/grep-scope.ts +8 -46
  39. package/src/pi/grep-search.ts +90 -63
  40. package/src/pi/grep-tool.ts +109 -121
  41. package/src/pi/grep.test.ts +597 -377
  42. package/src/pi/mutation-outcome.testing.ts +22 -0
  43. package/src/pi/mutation-result.test.ts +51 -2
  44. package/src/pi/mutation-result.ts +62 -55
  45. package/src/pi/mutation-runner.ts +16 -33
  46. package/src/pi/pi.test.ts +11 -6
  47. package/src/pi/read-tool.ts +62 -34
  48. package/src/pi/registration.test.ts +7 -7
  49. package/src/pi/render.test.ts +143 -9
  50. package/src/pi/render.ts +32 -96
  51. package/src/pi/replace-regex.ts +54 -0
  52. package/src/pi/replace-tool.ts +25 -59
  53. package/src/pi/replace-worker.ts +2 -2
  54. package/src/pi/replace.test.ts +62 -58
  55. package/src/pi/result-safety.test.ts +124 -84
  56. package/src/pi/rg-line-ranges.ts +3 -2
  57. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  58. package/src/pi/{rg-line-filter.ts → rg-process.ts} +43 -9
  59. package/src/pi/rg-text-view.ts +25 -38
  60. package/src/pi/schema.ts +2 -10
  61. package/src/pi/text-stream.test.ts +153 -0
  62. package/src/pi/text-stream.ts +33 -13
  63. package/src/pi/write-tool.ts +3 -2
  64. package/src/pi/write.test.ts +10 -9
  65. package/src/core/index.ts +0 -14
  66. package/src/pi/state.ts +0 -26
@@ -1,11 +1,35 @@
1
+ /**
2
+ * Action Fusion: run an optional `then_run` command after a successful mutation.
3
+ *
4
+ * Two per-file queues nest here, with different jobs:
5
+ * - Pi's `withFileMutationQueue` (entered by the mutation runner) serializes
6
+ * the read-modify-write itself and is shared with every tool that uses it.
7
+ * It is released as soon as the file is published.
8
+ * - The executor's own queue wraps mutation, freshness check, and command, so
9
+ * a later fused call on the same file waits until this command finishes and
10
+ * cannot change the revision the command started from. Its key resolves the nearest
11
+ * existing ancestor and folds case on Windows, so it is never looser than
12
+ * Pi's key. It is always taken first and Pi's queue never waits on it, so
13
+ * the nesting cannot deadlock.
14
+ *
15
+ * Writers outside these queues are not blocked; the freshness check against
16
+ * `publishedRevision` detects them and the command is skipped or reported stale.
17
+ * A failed command never rolls back the published file.
18
+ *
19
+ * @module pi-hashline-edit/pi
20
+ */
21
+
1
22
  import { realpath } from "node:fs/promises";
2
23
  import { basename, dirname, resolve } from "node:path";
3
24
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
4
25
  import { createBashToolDefinition, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
26
  import { Type, type Static, type TObject, type TProperties } from "typebox";
6
27
  import { fileRevision, FileMutationError, type PublicationStatus } from "./file-commit.ts";
7
- import { finalizeMutationResult, observedFreshness } from "./mutation-result.ts";
8
- import { errorMessage, OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
28
+ import { commitFreshness, finalizeMutation, type MutationOutcome } from "./mutation-result.ts";
29
+ import { errorMessage } from "../core/errors.ts";
30
+ import { OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
31
+
32
+ const MILLISECONDS_PER_SECOND = 1_000;
9
33
 
10
34
  export const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
11
35
  export const THEN_RUN_FAILED = "[then_run:failed]";
@@ -48,6 +72,8 @@ export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command
48
72
  reason?: string;
49
73
  /** True only after mutation execution and result generation both succeed. */
50
74
  mutationCompleted: boolean;
75
+ /** Present once a command with an explicit timeout starts; refreshed during silent execution. */
76
+ timing?: { readonly timeoutSeconds: number; readonly remainingSeconds: number };
51
77
  }
52
78
 
53
79
  type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionContext) => void;
@@ -93,13 +119,20 @@ type CommandRunner = (
93
119
  ) => Promise<string>;
94
120
 
95
121
  type MutationResult<TDetails> = AgentToolResult<TDetails>;
96
- type MutationFinalizer<TDetails> = (
122
+ /** Attach the fused outcome to a finalized mutation result, plus optional command text. */
123
+ function withFusionDetails<TDetails>(
97
124
  result: MutationResult<TDetails>,
98
- publishAnchors: boolean,
99
- ) => MutationResult<TDetails>;
100
-
101
- function staleAnchorNotice(): string {
102
- return `${THEN_RUN_STALE} Pre-command anchors are omitted: target freshness is unconfirmed. Re-read before further edits.`;
125
+ actionFusion: ActionFusionDetails,
126
+ commandText?: string,
127
+ ): MutationResult<TDetails> {
128
+ return {
129
+ ...result,
130
+ details: { ...((result.details as object) ?? {}), actionFusion },
131
+ content:
132
+ commandText === undefined
133
+ ? result.content
134
+ : [...result.content, { type: "text", text: commandText }],
135
+ } as MutationResult<TDetails>;
103
136
  }
104
137
 
105
138
  async function readFreshness(path: string, baseline: string): Promise<Freshness> {
@@ -171,17 +204,6 @@ export class ActionFusionError extends Error {
171
204
  }
172
205
  }
173
206
 
174
- function mutationPublication<TDetails>(result: MutationResult<TDetails>): PublicationStatus {
175
- const details = result.details as { publication?: PublicationStatus } | undefined;
176
- return details?.publication ?? "PUBLISHED";
177
- }
178
-
179
- function mutationPublishedRevision<TDetails>(result: MutationResult<TDetails>): string | undefined {
180
- const revision = (result.details as { publishedRevision?: unknown } | undefined)
181
- ?.publishedRevision;
182
- return typeof revision === "string" && revision.length > 0 ? revision : undefined;
183
- }
184
-
185
207
  function commandStatus(error: unknown, signal: AbortSignal | undefined): CommandStatus {
186
208
  if (signal?.aborted) return "cancelled";
187
209
  return /timeout|timed out/i.test(errorMessage(error)) ? "timeout" : "failed";
@@ -261,20 +283,18 @@ export function createActionFusionExecutor(
261
283
  signal,
262
284
  ctx,
263
285
  onUpdate,
264
- finalizeMutation,
265
286
  }: {
266
287
  toolCallId: string;
267
288
  absolutePath: string;
268
289
  thenRun: ThenRunInput | undefined;
269
- mutate: () => Promise<MutationResult<TDetails>>;
290
+ mutate: () => Promise<MutationOutcome<TDetails>>;
270
291
  signal: AbortSignal | undefined;
271
292
  ctx: ExtensionContext;
272
293
  onUpdate?: AgentToolUpdateCallback<TDetails>;
273
- finalizeMutation?: MutationFinalizer<TDetails>;
274
294
  }): Promise<MutationResult<TDetails>> {
275
- let completedMutation: MutationResult<TDetails> | undefined;
295
+ let completedMutation: MutationOutcome<TDetails> | undefined;
276
296
  let progressFailure: string | undefined;
277
- let commandSucceeded = false;
297
+ let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
278
298
  const report = (
279
299
  command: ActionFusionProgress["command"],
280
300
  publication: PublicationStatus,
@@ -282,7 +302,6 @@ export function createActionFusionExecutor(
282
302
  output = "",
283
303
  reason?: string,
284
304
  ) => {
285
- if (command === "succeeded") commandSucceeded = true;
286
305
  if (!thenRun) return;
287
306
  const progress: ActionFusionProgress = {
288
307
  toolCallId,
@@ -294,6 +313,17 @@ export function createActionFusionExecutor(
294
313
  output,
295
314
  ...(reason ? { reason } : {}),
296
315
  mutationCompleted: completedMutation !== undefined,
316
+ ...(commandTiming
317
+ ? {
318
+ timing: {
319
+ timeoutSeconds: commandTiming.timeoutSeconds,
320
+ remainingSeconds: Math.max(
321
+ 0,
322
+ Math.ceil((commandTiming.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
323
+ ),
324
+ },
325
+ }
326
+ : {}),
297
327
  };
298
328
  // Display callbacks are observers: their failures must not change publication or command execution.
299
329
  for (const notify of [
@@ -301,13 +331,16 @@ export function createActionFusionExecutor(
301
331
  () =>
302
332
  onUpdate?.({
303
333
  content: [
304
- ...(completedMutation?.content ?? []),
334
+ ...(completedMutation?.result.content ?? []),
305
335
  {
306
336
  type: "text",
307
337
  text: `then_run ${command}: ${thenRun.command}\n${reason ?? output}`,
308
338
  },
309
339
  ],
310
- details: { ...((completedMutation?.details as object) ?? {}), actionFusion: progress },
340
+ details: {
341
+ ...((completedMutation?.result.details as object) ?? {}),
342
+ actionFusion: progress,
343
+ },
311
344
  } as MutationResult<TDetails>),
312
345
  ]) {
313
346
  try {
@@ -334,10 +367,10 @@ export function createActionFusionExecutor(
334
367
  );
335
368
  throw error;
336
369
  }
337
- let mutationResult: MutationResult<TDetails>;
370
+ let outcome: MutationOutcome<TDetails>;
338
371
  try {
339
- mutationResult = await mutate();
340
- completedMutation = mutationResult;
372
+ outcome = await mutate();
373
+ completedMutation = outcome;
341
374
  } catch (error) {
342
375
  const publication =
343
376
  error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
@@ -355,32 +388,15 @@ export function createActionFusionExecutor(
355
388
  throw error;
356
389
  }
357
390
 
358
- const publication = mutationPublication(mutationResult);
391
+ const { publication, publishedRevision: baseline } = outcome.commit;
359
392
  report("waiting", publication, "unknown");
360
393
  if (thenRun === undefined) {
361
- const finalized = finalizeMutation
362
- ? finalizeMutationResult(mutationResult, finalizeMutation)
363
- : mutationResult;
364
- return {
365
- ...finalized,
366
- details: {
367
- ...((finalized.details as object) ?? {}),
368
- actionFusion: {
369
- publication,
370
- command: "not_requested",
371
- freshness: observedFreshness(mutationResult),
372
- } satisfies ActionFusionDetails,
373
- },
374
- } as MutationResult<TDetails>;
375
- }
376
-
377
- const baseline = mutationPublishedRevision(mutationResult);
378
- if (baseline === undefined) {
379
- throw new ActionFusionError(
380
- "Missing published revision; cannot validate fused command freshness.",
381
- { publication, command: "skipped", freshness: "unknown" },
382
- { commandReason: "Not run because the mutation revision is unavailable." },
383
- );
394
+ const freshness = commitFreshness(outcome.commit);
395
+ return withFusionDetails(finalizeMutation(outcome, freshness === "unchanged"), {
396
+ publication,
397
+ command: "not_requested",
398
+ freshness,
399
+ });
384
400
  }
385
401
  try {
386
402
  throwIfCancelled(signal);
@@ -400,20 +416,37 @@ export function createActionFusionExecutor(
400
416
  );
401
417
  }
402
418
 
419
+ if (thenRun.timeout !== undefined) {
420
+ commandTiming = {
421
+ timeoutSeconds: thenRun.timeout,
422
+ deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
423
+ };
424
+ }
403
425
  report("running", publication, "unchanged");
404
- let output: string;
426
+ let output = "";
405
427
  let commandError: unknown;
428
+ // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
429
+ const heartbeat =
430
+ commandTiming && (onProgress || onUpdate)
431
+ ? setInterval(
432
+ () => report("running", publication, "unknown", output),
433
+ MILLISECONDS_PER_SECOND,
434
+ )
435
+ : undefined;
436
+ heartbeat?.unref();
406
437
  try {
407
438
  output = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
408
- const text = partial.content
439
+ output = partial.content
409
440
  .filter((block) => block.type === "text")
410
441
  .map((block) => block.text)
411
442
  .join("\n");
412
- report("running", publication, "unknown", text);
443
+ report("running", publication, "unknown", output);
413
444
  });
414
445
  } catch (error) {
415
446
  commandError = error;
416
447
  output = "";
448
+ } finally {
449
+ if (heartbeat) clearInterval(heartbeat);
417
450
  }
418
451
  const freshness = await readFreshness(absolutePath, baseline);
419
452
  if (commandError !== undefined) {
@@ -424,71 +457,34 @@ export function createActionFusionExecutor(
424
457
  );
425
458
  }
426
459
 
427
- const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
428
460
  report("succeeded", publication, freshness, output);
429
- const finalized = finalizeMutation
430
- ? finalizeMutationResult(
431
- mutationResult,
432
- finalizeMutation,
433
- freshness === "unchanged",
434
- staleAnchorNotice(),
435
- )
436
- : mutationResult;
437
- const commandText = `${THEN_RUN_SUCCEEDED}${!finalizeMutation && freshness !== "unchanged" ? `\n${THEN_RUN_STALE} Re-read the file before further edits; previous anchors may no longer match.` : ""}${output ? `\n${output}` : ""}`;
438
- return {
439
- ...finalized,
440
- details: { ...((finalized.details as object) ?? {}), actionFusion },
441
- content: [...finalized.content, { type: "text", text: commandText }],
442
- } as MutationResult<TDetails>;
461
+ return withFusionDetails(
462
+ finalizeMutation(outcome, freshness === "unchanged", THEN_RUN_STALE),
463
+ { publication, command: "succeeded", freshness },
464
+ `${THEN_RUN_SUCCEEDED}${output ? `\n${output}` : ""}`,
465
+ );
443
466
  })
444
467
  .catch((error: unknown) => {
445
- // Result-generation errors after a successful command must not relabel it skipped.
446
- if (!commandSucceeded) {
447
- report(
448
- error instanceof ActionFusionError
449
- ? (error.command as ActionFusionProgress["command"])
450
- : "skipped",
451
- error instanceof ActionFusionError || error instanceof FileMutationError
452
- ? error.publication
453
- : completedMutation
454
- ? mutationPublication(completedMutation)
455
- : "NOT_PUBLISHED",
456
- error instanceof ActionFusionError ? error.freshness : "unknown",
457
- error instanceof ActionFusionError ? error.commandOutput : "",
458
- error instanceof ActionFusionError
459
- ? error.commandReason
460
- : "Not run because the mutation did not complete.",
461
- );
462
- }
468
+ report(
469
+ error instanceof ActionFusionError
470
+ ? (error.command as ActionFusionProgress["command"])
471
+ : "skipped",
472
+ error instanceof ActionFusionError || error instanceof FileMutationError
473
+ ? error.publication
474
+ : (completedMutation?.commit.publication ?? "NOT_PUBLISHED"),
475
+ error instanceof ActionFusionError ? error.freshness : "unknown",
476
+ error instanceof ActionFusionError ? error.commandOutput : "",
477
+ error instanceof ActionFusionError
478
+ ? error.commandReason
479
+ : "Not run because the mutation did not complete.",
480
+ );
463
481
  // A completed mutation remains successful; command failure belongs to its own card.
464
482
  if (completedMutation && error instanceof ActionFusionError) {
465
- const finalized = finalizeMutation
466
- ? finalizeMutationResult(
467
- completedMutation,
468
- finalizeMutation,
469
- error.freshness === "unchanged",
470
- staleAnchorNotice(),
471
- )
472
- : completedMutation;
473
- const anchorNotice =
474
- !finalizeMutation && error.freshness !== "unchanged"
475
- ? `\n${THEN_RUN_STALE} Re-read before further edits; previous anchors may no longer match.`
476
- : "";
477
- return {
478
- ...finalized,
479
- details: {
480
- ...((finalized.details as object) ?? {}),
481
- actionFusion: {
482
- publication: error.publication,
483
- command: error.command,
484
- freshness: error.freshness,
485
- } satisfies ActionFusionDetails,
486
- },
487
- content: [
488
- ...finalized.content,
489
- { type: "text", text: `${error.message}${anchorNotice}` },
490
- ],
491
- } as MutationResult<TDetails>;
483
+ return withFusionDetails(
484
+ finalizeMutation(completedMutation, error.freshness === "unchanged", THEN_RUN_STALE),
485
+ { publication: error.publication, command: error.command, freshness: error.freshness },
486
+ error.message,
487
+ );
492
488
  }
493
489
  {
494
490
  const parts: string[] = [errorMessage(error)];
@@ -1,30 +1,31 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { computeLineHash } from "../core/hash.ts";
4
- import { anchorPattern, createAnchorFormatter, parseAnchorToken } from "./anchor-format.ts";
5
- import { getState } from "./state.ts";
6
-
7
- test("anchor formatter snapshots configured hash length and hashes undisplayed content", () => {
8
- const state = getState();
9
- const previous = state.config;
10
- try {
11
- state.config = { ...previous, hashLen: 6 };
12
- const formatter = createAnchorFormatter();
13
- state.config = { ...previous, hashLen: 4 };
14
-
15
- assert.equal(formatter.hashLen, 6);
16
- assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
17
- assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
18
- assert.match(formatter.token(3, "full content"), new RegExp(anchorPattern(6)));
19
- assert.doesNotMatch(formatter.token(3, "full content"), new RegExp(anchorPattern(4)));
20
- assert.equal(
21
- formatter.row(3, "full content", "full…"),
22
- `3#${computeLineHash(3, "full content", 6)}│full…`,
23
- );
24
- assert.equal(createAnchorFormatter().hashLen, 4);
25
- } finally {
26
- state.config = previous;
27
- }
4
+ import {
5
+ anchorPattern,
6
+ createAnchorFormatter,
7
+ parseAnchorToken,
8
+ parseHashline,
9
+ parseDisplayRow,
10
+ plainRow,
11
+ } from "./anchor-format.ts";
12
+
13
+ test("anchor formatter binds the supplied hash length and hashes undisplayed content", () => {
14
+ const formatter = createAnchorFormatter(6);
15
+ const shortFormatter = createAnchorFormatter(4);
16
+
17
+ assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
18
+ assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
19
+ assert.match(formatter.token(3, "full content"), new RegExp(anchorPattern(6)));
20
+ assert.doesNotMatch(formatter.token(3, "full content"), new RegExp(anchorPattern(4)));
21
+ assert.equal(
22
+ formatter.row(3, "full content", "full…"),
23
+ `3#${computeLineHash(3, "full content", 6)}│full…`,
24
+ );
25
+ assert.equal(
26
+ shortFormatter.token(3, "full content"),
27
+ `3#${computeLineHash(3, "full content", 4)}`,
28
+ );
28
29
  });
29
30
 
30
31
  test("anchor tokens parse at any hash length so wrong lengths can be explained", () => {
@@ -39,3 +40,69 @@ test("anchor rows expose carriage returns while checksums retain source content"
39
40
  assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
40
41
  assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
41
42
  });
43
+
44
+ test("anchor syntax rejects characters absent from the checksum alphabet", () => {
45
+ const pattern = new RegExp(anchorPattern(4));
46
+ for (const hash of ["IIII", "LLLL", "OOOO", "UUUU", "abcd"]) {
47
+ assert.doesNotMatch(`1#${hash}`, pattern);
48
+ assert.equal(parseAnchorToken(`1#${hash}`), undefined);
49
+ assert.equal(parseHashline(`1#${hash}│content`), null);
50
+ }
51
+ });
52
+
53
+ test("display rows accept supported hash lengths and preserve nested anchor-like content", () => {
54
+ for (const hashLen of [2, 4, 6, 8]) {
55
+ const formatter = createAnchorFormatter(hashLen);
56
+ assert.deepEqual(parseHashline(formatter.row(12, "12#abc│content")), {
57
+ lineNo: "12",
58
+ content: "12#abc│content",
59
+ });
60
+ }
61
+ for (const row of ["0#ABCD│text", "01#ABCD│text", "12#A│text", "12#AAAAAAAAA│text"]) {
62
+ assert.equal(parseHashline(row), null);
63
+ }
64
+ });
65
+
66
+ test("plain rows expose carriage returns without creating editable anchors", () => {
67
+ assert.equal(plainRow(12, "a\rb│12#ABCD│nested"), "12│a␍b│12#ABCD│nested");
68
+ assert.equal(plainRow(1, ""), "1│");
69
+ assert.equal(parseHashline(plainRow(12, "content")), null);
70
+ assert.equal(parseAnchorToken("12"), undefined);
71
+ });
72
+
73
+ test("display row parsing accepts plain and anchored rows without changing their content", () => {
74
+ for (const hashLen of [2, 4, 6, 8]) {
75
+ const anchored = createAnchorFormatter(hashLen).row(12, " nested 7#ABCD│content");
76
+ assert.deepEqual(parseDisplayRow(anchored), {
77
+ lineNo: "12",
78
+ content: " nested 7#ABCD│content",
79
+ });
80
+ assert.deepEqual(parseDisplayRow(anchored), parseHashline(anchored));
81
+ }
82
+ assert.deepEqual(parseDisplayRow("123│ �│7#ABCD│nested"), {
83
+ lineNo: "123",
84
+ content: " �│7#ABCD│nested",
85
+ });
86
+ assert.deepEqual(parseDisplayRow(plainRow(9, "a\rb")), { lineNo: "9", content: "a␍b" });
87
+ assert.deepEqual(parseDisplayRow("1│"), { lineNo: "1", content: "" });
88
+ });
89
+
90
+ test("display row parsing rejects headers, notices, and invalid line references", () => {
91
+ for (const row of [
92
+ "",
93
+ "file.txt · 2 matches",
94
+ "[Invalid UTF-8: plain preview]",
95
+ "No matches found",
96
+ "0│text",
97
+ "01│text",
98
+ "-1│text",
99
+ " 1│text",
100
+ "1:text",
101
+ "0#ABCD│text",
102
+ "01#ABCD│text",
103
+ "1#A│text",
104
+ "1#IIII│text",
105
+ ]) {
106
+ assert.equal(parseDisplayRow(row), null, row);
107
+ }
108
+ });
@@ -1,12 +1,20 @@
1
- import { computeLineHash } from "../core/hash.ts";
2
- import { getState } from "./state.ts";
1
+ import { computeLineHash, HASH_ALPHABET, HASH_LEN_MIN, HASH_LEN_MAX } from "../core/hash.ts";
2
+
3
+ function anchorSource(hashQuantifier: string): string {
4
+ return `([1-9][0-9]*)#([${HASH_ALPHABET}]${hashQuantifier})`;
5
+ }
3
6
 
4
7
  /** Schema pattern for a `LINE#HASH` anchor whose hash has exactly `hashLen` characters. */
5
8
  export function anchorPattern(hashLen: number): string {
6
- return `^([1-9][0-9]*)#([0-9A-Z]{${hashLen}})$`;
9
+ return `^${anchorSource(`{${hashLen}}`)}$`;
7
10
  }
8
11
 
9
- const ANCHOR_TOKEN = /^([1-9][0-9]*)#([0-9A-Z]+)$/;
12
+ /** Separates a row's line reference from its displayed content. */
13
+ const ROW_SEPARATOR = "│";
14
+ const ANCHOR_TOKEN = new RegExp(`^${anchorSource("+")}$`);
15
+ const HASHLINE_ROW = new RegExp(
16
+ `^${anchorSource(`{${HASH_LEN_MIN},${HASH_LEN_MAX}}`)}${ROW_SEPARATOR}(.*)$`,
17
+ );
10
18
 
11
19
  /** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
12
20
  export function parseAnchorToken(value: string): { line: number; hash: string } | undefined {
@@ -14,9 +22,31 @@ export function parseAnchorToken(value: string): { line: number; hash: string }
14
22
  return match ? { line: Number(match[1]), hash: match[2]! } : undefined;
15
23
  }
16
24
 
17
- /** Anchor serialization bound to one hash-length snapshot. */
25
+ export interface HashlineRow {
26
+ /** Line number as written in the anchor (string form). */
27
+ lineNo: string;
28
+ /** Line content with the `LINE#HASH│` prefix removed. */
29
+ content: string;
30
+ }
31
+
32
+ /** Parse a display row at any supported hash length; return null for non-anchor text. */
33
+ export function parseHashline(line: string): HashlineRow | null {
34
+ const match = HASHLINE_ROW.exec(line);
35
+ return match ? { lineNo: match[1], content: match[3] } : null;
36
+ }
37
+
38
+ const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`);
39
+
40
+ /** Parse an anchored row or a non-editable `LINE│content` row; null for other text. */
41
+ export function parseDisplayRow(line: string): HashlineRow | null {
42
+ const anchored = parseHashline(line);
43
+ if (anchored) return anchored;
44
+ const match = PLAIN_ROW.exec(line);
45
+ return match ? { lineNo: match[1], content: match[2] } : null;
46
+ }
47
+
48
+ /** Anchor serialization bound to a caller-supplied hash length. */
18
49
  export interface AnchorFormatter {
19
- readonly hashLen: number;
20
50
  reference(line: number, hash: string): string;
21
51
  token(line: number, content: string): string;
22
52
  row(line: number, content: string, displayContent?: string): string;
@@ -27,15 +57,19 @@ export function displayCarriageReturns(text: string): string {
27
57
  return text.replace(/\r/g, "␍");
28
58
  }
29
59
 
30
- export function createAnchorFormatter(hashLen = getState().config.hashLen): AnchorFormatter {
60
+ /** Non-editable `LINE│content` row for text that cannot carry an anchor. */
61
+ export function plainRow(line: number, displayContent: string): string {
62
+ return `${line}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`;
63
+ }
64
+
65
+ export function createAnchorFormatter(hashLen: number): AnchorFormatter {
31
66
  const reference = (line: number, hash: string) => `${line}#${hash}`;
32
67
  const token = (line: number, content: string) =>
33
68
  reference(line, computeLineHash(line, content, hashLen));
34
69
  return {
35
- hashLen,
36
70
  token,
37
71
  reference,
38
72
  row: (line, content, displayContent = content) =>
39
- `${token(line, content)}│${displayCarriageReturns(displayContent)}`,
73
+ `${token(line, content)}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`,
40
74
  };
41
75
  }
package/src/pi/budgets.ts CHANGED
@@ -1,12 +1,17 @@
1
1
  /**
2
- * Model-facing output byte budgets.
2
+ * Fixed model-facing output budgets.
3
3
  *
4
4
  * README "Output budgets" documents each value; change both together. Result
5
- * and notice text derive their size wording from these constants.
5
+ * and notice text derive their size wording from these constants. Budgets that
6
+ * users can configure (read line and byte limits, grep line limit) live in the
7
+ * settings schema in config.ts; Pi's own total-output limit stays with Pi.
6
8
  *
7
9
  * @module pi-hashline-edit/pi
8
10
  */
9
11
 
12
+ /** grep line preview, in UTF-16 units, excluding its partial-line label. */
13
+ export const GREP_MAX_LINE_LENGTH = 500;
14
+
10
15
  /** Each diagnostic or anchor block: failure details, input-anchor checks, candidate neighborhoods, mutation anchors. */
11
16
  export const MAX_BLOCK_BYTES = 16 * 1024;
12
17
  /** One recovery-candidate or cited row inside a failure diagnostic. */