@criogaid/pi-hashline-edit 0.8.0 → 0.10.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 +13 -10
  2. package/README.zh-CN.md +12 -9
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +118 -293
  7. package/src/core/apply.ts +63 -165
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/ranges.test.ts +16 -8
  16. package/src/core/ranges.ts +10 -6
  17. package/src/core/regex.ts +3 -4
  18. package/src/core/replace.test.ts +47 -1
  19. package/src/core/replace.ts +19 -13
  20. package/src/core/search-analysis.test.ts +24 -27
  21. package/src/core/search-analysis.ts +34 -65
  22. package/src/core/search-matrix.testing.ts +0 -2
  23. package/src/core/search.ts +1 -1
  24. package/src/core/text.test.ts +5 -5
  25. package/src/core/text.ts +5 -12
  26. package/src/core/types.ts +7 -43
  27. package/src/integration/config-registration.test.ts +2 -2
  28. package/src/integration/fusion-dispatch.test.ts +2 -5
  29. package/src/integration/grep-flags.test.ts +0 -14
  30. package/src/integration/grep-js-completeness.test.ts +34 -8
  31. package/src/integration/grep-line-candidates.test.ts +4 -8
  32. package/src/integration/grep-matrix.test.ts +3 -7
  33. package/src/integration/grep-path-matrix.test.ts +5 -5
  34. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  35. package/src/integration/grep-process-limits.test.ts +78 -0
  36. package/src/integration/grep-rg.test.ts +123 -25
  37. package/src/integration/grep-scan-budget.test.ts +2 -2
  38. package/src/integration/grep-translation.test.ts +12 -27
  39. package/src/integration/large-text.test.ts +1 -47
  40. package/src/integration/model-budget-lifecycle.test.ts +13 -3
  41. package/src/integration/mutation-file-types.testing.ts +1 -1
  42. package/src/integration/npm-package.testing.ts +1 -1
  43. package/src/integration/publication-read-changes.test.ts +125 -47
  44. package/src/integration/replace-worker-boundary.test.ts +21 -11
  45. package/src/integration/report-replay.test.ts +21 -23
  46. package/src/integration/utf8-errors.test.ts +1 -1
  47. package/src/pi/AGENTS.md +16 -16
  48. package/src/pi/action-fusion.test.ts +168 -300
  49. package/src/pi/action-fusion.ts +148 -111
  50. package/src/pi/anchor-format.test.ts +9 -9
  51. package/src/pi/anchor-format.ts +6 -8
  52. package/src/pi/argument-diagnostics.ts +52 -207
  53. package/src/pi/argument-error.ts +2 -1
  54. package/src/pi/argument-format.test.ts +20 -22
  55. package/src/pi/argument-validation.test.ts +382 -418
  56. package/src/pi/argument-validation.ts +5 -8
  57. package/src/pi/budgets.ts +5 -4
  58. package/src/pi/config.test.ts +5 -2
  59. package/src/pi/config.ts +4 -6
  60. package/src/pi/diagnostic-buffer.test.ts +12 -1
  61. package/src/pi/diagnostic-buffer.ts +1 -2
  62. package/src/pi/directory-sync.test.ts +0 -1
  63. package/src/pi/edit-tool.ts +173 -226
  64. package/src/pi/error-text.ts +4 -8
  65. package/src/pi/execute.test.ts +165 -266
  66. package/src/pi/failure-context.test.ts +144 -126
  67. package/src/pi/failure-context.ts +45 -94
  68. package/src/pi/failure-path.test.ts +168 -141
  69. package/src/pi/file-commit.test.ts +110 -53
  70. package/src/pi/file-commit.ts +90 -137
  71. package/src/pi/file-snapshot.test.ts +3 -5
  72. package/src/pi/fusion-card.test.ts +4 -1
  73. package/src/pi/fusion-card.ts +16 -24
  74. package/src/pi/grep-candidates.test.ts +2 -101
  75. package/src/pi/grep-candidates.ts +23 -69
  76. package/src/pi/grep-matrix.test.ts +2 -2
  77. package/src/pi/grep-order.test.ts +4 -4
  78. package/src/pi/grep-output.ts +62 -96
  79. package/src/pi/grep-render.ts +1 -1
  80. package/src/pi/grep-reread.ts +92 -0
  81. package/src/pi/grep-scope.ts +40 -42
  82. package/src/pi/grep-search.ts +22 -31
  83. package/src/pi/grep-tool.ts +55 -82
  84. package/src/pi/grep.test.ts +81 -46
  85. package/src/pi/model-budgets.test.ts +25 -23
  86. package/src/pi/model-budgets.ts +6 -38
  87. package/src/pi/mutation-result.test.ts +44 -35
  88. package/src/pi/mutation-result.ts +51 -20
  89. package/src/pi/mutation-runner.ts +126 -70
  90. package/src/pi/output-budgets.test.ts +38 -16
  91. package/src/pi/path.ts +1 -1
  92. package/src/pi/pi.test.ts +3 -1
  93. package/src/pi/read-tool.ts +5 -5
  94. package/src/pi/regex-worker-contract.ts +3 -13
  95. package/src/pi/regex-worker.ts +1 -10
  96. package/src/pi/registration.test.ts +82 -20
  97. package/src/pi/render.test.ts +79 -42
  98. package/src/pi/render.ts +69 -63
  99. package/src/pi/replace-regex.ts +14 -2
  100. package/src/pi/replace-tool.ts +22 -83
  101. package/src/pi/replace-worker.ts +1 -1
  102. package/src/pi/replace.test.ts +9 -5
  103. package/src/pi/report-cause.ts +3 -8
  104. package/src/pi/report-failure.testing.ts +1 -2
  105. package/src/pi/report-schema.ts +65 -81
  106. package/src/pi/report.test.ts +171 -25
  107. package/src/pi/report.ts +33 -87
  108. package/src/pi/result-safety.test.ts +177 -189
  109. package/src/pi/rg-process.test.ts +77 -63
  110. package/src/pi/rg-process.ts +48 -64
  111. package/src/pi/rg-regex.ts +40 -400
  112. package/src/pi/schema.ts +12 -0
  113. package/src/pi/text-stream.test.ts +0 -21
  114. package/src/pi/text-stream.ts +14 -21
  115. package/src/pi/write-tool.ts +33 -62
  116. package/src/pi/write.test.ts +1 -3
  117. package/src/testing/regex-translation-corpus.ts +12 -12
  118. package/src/pi/replace-worker-contract.ts +0 -10
@@ -23,35 +23,31 @@
23
23
 
24
24
  import { realpath } from "node:fs/promises";
25
25
  import { basename, dirname, resolve } from "node:path";
26
- import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
26
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
27
27
  import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
28
28
  import { Type, type Static, type TObject, type TProperties } from "typebox";
29
29
  import { commitFreshness, observeFreshness, type FreshnessObservation } from "./file-commit.ts";
30
30
  import {
31
+ CommandNotRun,
31
32
  commandText,
32
- finalizeMutation,
33
33
  type CommandFacts,
34
34
  type MutationOutcome,
35
35
  type MutationResultDetails,
36
36
  } from "./mutation-result.ts";
37
37
  import { errnoCode, errorMessage } from "../core/errors.ts";
38
38
  import { throwIfCancelled } from "./error-text.ts";
39
- import { causeOf, CommandNotRun, type ReportDetails } from "./report.ts";
40
- import type { OutputBudgets } from "./budgets.ts";
41
39
  import type {
42
40
  ActionFusionProgress,
43
41
  CommandResult,
44
42
  CommandStatus,
45
43
  Freshness,
46
44
  MutationToolName,
47
- SuccessReport,
48
45
  } from "./report-schema.ts";
49
- export type { ActionFusionProgress } from "./report-schema.ts";
50
46
 
51
47
  const MILLISECONDS_PER_SECOND = 1_000;
52
48
 
53
49
  // Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
54
- const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / 1_000;
50
+ const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
55
51
 
56
52
  // Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
57
53
  const COMMAND_DESCRIPTION =
@@ -63,7 +59,7 @@ export const ACTION_FUSION_GUIDELINES = [
63
59
  "When a check covers several changes, run it once after all of those changes.",
64
60
  ];
65
61
 
66
- type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionToolContext) => void;
62
+ type ProgressReporter = (progress: ActionFusionProgress) => void;
67
63
 
68
64
  function createThenRunSchema(tool: MutationToolName) {
69
65
  return Type.Optional(
@@ -85,6 +81,7 @@ function createThenRunSchema(tool: MutationToolName) {
85
81
  ),
86
82
  );
87
83
  }
84
+
88
85
  /** Add the optional then_run field to a mutation schema when Action Fusion is enabled. */
89
86
  export function withThenRunSchema<P extends TProperties>(
90
87
  schema: TObject<P>,
@@ -98,6 +95,7 @@ export function withThenRunSchema<P extends TProperties>(
98
95
  )
99
96
  : schema;
100
97
  }
98
+
101
99
  export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
102
100
 
103
101
  /** Name then_run in a mutation tool's description when Action Fusion is enabled. */
@@ -107,8 +105,18 @@ export function withThenRunDescription(description: string, actionFusion: boolea
107
105
  : description;
108
106
  }
109
107
 
108
+ /** What a fused call leaves for the mutation runner to report; Fusion builds no result itself. */
109
+ export interface FusedMutation<TDetails, TTool extends MutationToolName> {
110
+ readonly outcome: MutationOutcome<TDetails, TTool>;
111
+ readonly observation: FreshnessObservation;
112
+ /** Absent when the call has no then_run. */
113
+ readonly command?: CommandFacts;
114
+ /** Preserve the session tool's request to stop after this tool batch. */
115
+ readonly terminate?: boolean;
116
+ }
117
+
110
118
  /** Keep command state independent of its diagnostic text and of file publication. */
111
- export interface CommandOutcome {
119
+ interface CommandOutcome {
112
120
  readonly status: Exclude<CommandStatus, "skipped">;
113
121
  readonly result: CommandResult;
114
122
  /** Preserve the session tool's request to stop after this tool batch. */
@@ -116,7 +124,6 @@ export interface CommandOutcome {
116
124
  }
117
125
 
118
126
  type CommandRunner = (
119
- toolCallId: string,
120
127
  input: ThenRunInput,
121
128
  signal: AbortSignal | undefined,
122
129
  ctx: ExtensionToolContext,
@@ -124,7 +131,6 @@ type CommandRunner = (
124
131
  ) => Promise<CommandOutcome>;
125
132
 
126
133
  async function defaultCommandRunner(
127
- _toolCallId: string,
128
134
  input: ThenRunInput,
129
135
  signal: AbortSignal | undefined,
130
136
  ctx: ExtensionToolContext,
@@ -159,25 +165,113 @@ async function defaultCommandRunner(
159
165
  }
160
166
 
161
167
  async function canonicalQueueKey(path: string): Promise<string> {
168
+ const folded = (key: string) => (process.platform === "win32" ? key.toLowerCase() : key);
162
169
  const resolved = resolve(path);
163
170
  let current = resolved;
164
171
  const missing: string[] = [];
165
172
  while (true) {
166
173
  try {
167
- const canonical = resolve(await realpath(current), ...missing);
168
- return process.platform === "win32" ? canonical.toLowerCase() : canonical;
174
+ return folded(resolve(await realpath(current), ...missing));
169
175
  } catch (error) {
170
176
  const code = errnoCode(error);
171
177
  if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
172
178
  const parent = dirname(current);
173
- if (parent === current)
174
- return process.platform === "win32" ? resolved.toLowerCase() : resolved;
179
+ if (parent === current) return folded(resolved);
175
180
  missing.unshift(basename(current));
176
181
  current = parent;
177
182
  }
178
183
  }
179
184
  }
180
185
 
186
+ /**
187
+ * One then_run call's display state and the observers that follow it. Display callbacks are
188
+ * observers: their failures must not change publication or command execution, so the first is
189
+ * kept for the report. The tracker owns the heartbeat lifetime; Pi Bash owns timeout and
190
+ * process cleanup.
191
+ */
192
+ function createProgressTracker<TDetails extends object>({
193
+ toolCallId,
194
+ thenRun,
195
+ onProgress,
196
+ onUpdate,
197
+ }: {
198
+ toolCallId: string;
199
+ thenRun: ThenRunInput;
200
+ onProgress: ProgressReporter | undefined;
201
+ onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined;
202
+ }) {
203
+ let mutationDetails: TDetails | undefined;
204
+ let failure: unknown;
205
+ let commandResult: CommandResult | undefined;
206
+ let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
207
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
208
+
209
+ const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
210
+ const progress: ActionFusionProgress = {
211
+ toolCallId,
212
+ commandText: thenRun.command,
213
+ command,
214
+ freshness,
215
+ ...(commandResult ? { result: commandResult } : {}),
216
+ mutationCompleted: mutationDetails !== undefined,
217
+ ...(commandTiming
218
+ ? {
219
+ timing: {
220
+ timeoutSeconds: commandTiming.timeoutSeconds,
221
+ remainingSeconds: Math.max(
222
+ 0,
223
+ Math.ceil((commandTiming.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
224
+ ),
225
+ },
226
+ }
227
+ : {}),
228
+ };
229
+ for (const notify of [
230
+ () => onProgress?.(progress),
231
+ () => onUpdate?.({ content: [], details: { ...mutationDetails, actionFusion: progress } }),
232
+ ]) {
233
+ try {
234
+ notify();
235
+ } catch (error) {
236
+ failure ??= error;
237
+ }
238
+ }
239
+ };
240
+
241
+ /** Follow the running command's partial results. */
242
+ const followCommand: AgentToolUpdateCallback<unknown> = (partial) => {
243
+ // Pi Bash emits an initial update even for silent commands. Start its
244
+ // countdown here, after session permission hooks have allowed execution.
245
+ if (!commandTiming && thenRun.timeout !== undefined) {
246
+ commandTiming = {
247
+ timeoutSeconds: thenRun.timeout,
248
+ deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
249
+ };
250
+ if (onProgress || onUpdate) {
251
+ heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
252
+ heartbeat.unref();
253
+ }
254
+ }
255
+ commandResult = { content: partial.content, details: partial.details };
256
+ report("running", "unknown");
257
+ };
258
+
259
+ return {
260
+ report,
261
+ followCommand,
262
+ failure: () => failure,
263
+ mutationCompleted(details: TDetails) {
264
+ mutationDetails = details;
265
+ },
266
+ stopHeartbeat() {
267
+ if (heartbeat) clearInterval(heartbeat);
268
+ },
269
+ commandSettled(result: CommandResult) {
270
+ commandResult = result;
271
+ },
272
+ };
273
+ }
274
+
181
275
  export function createActionFusionExecutor(
182
276
  commandRunner: CommandRunner = defaultCommandRunner,
183
277
  onProgress?: ProgressReporter,
@@ -204,153 +298,96 @@ export function createActionFusionExecutor(
204
298
 
205
299
  return async function execute<TDetails extends object, TTool extends MutationToolName>({
206
300
  toolCallId,
207
- tool,
208
- displayPath,
209
301
  absolutePath,
210
302
  thenRun,
211
- budget,
212
303
  mutate,
213
304
  signal,
214
305
  ctx,
215
306
  onUpdate,
216
307
  }: {
217
308
  toolCallId: string;
218
- tool: TTool;
219
- /** The caller-supplied path, as the report states it. */
220
- displayPath: string;
221
309
  absolutePath: string;
222
310
  thenRun: ThenRunInput | undefined;
223
- budget: OutputBudgets;
224
- mutate: () => Promise<MutationOutcome<TDetails, NoInfer<TTool>>>;
311
+ mutate: () => Promise<MutationOutcome<TDetails, TTool>>;
225
312
  signal: AbortSignal | undefined;
226
313
  ctx: ExtensionToolContext;
227
314
  onUpdate?: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
228
- }): Promise<AgentToolResult<TDetails & ReportDetails<SuccessReport>>> {
229
- let completedMutation: MutationOutcome<TDetails, TTool> | undefined;
230
- let progressFailure: unknown;
231
- let commandResult: CommandResult | undefined;
232
- let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
233
- const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
234
- if (!thenRun) return;
235
- const progress: ActionFusionProgress = {
236
- toolCallId,
237
- commandText: thenRun.command,
238
- command,
239
- freshness,
240
- ...(commandResult ? { result: commandResult } : {}),
241
- mutationCompleted: completedMutation !== undefined,
242
- ...(commandTiming
243
- ? {
244
- timing: {
245
- timeoutSeconds: commandTiming.timeoutSeconds,
246
- remainingSeconds: Math.max(
247
- 0,
248
- Math.ceil((commandTiming.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
249
- ),
250
- },
251
- }
252
- : {}),
253
- };
254
- // Display callbacks are observers: their failures must not change publication or command execution.
255
- for (const notify of [
256
- () => onProgress?.(progress, ctx),
257
- () =>
258
- onUpdate?.({
259
- content: [],
260
- details: { ...completedMutation?.details, actionFusion: progress },
261
- }),
262
- ]) {
263
- try {
264
- notify();
265
- } catch (error) {
266
- progressFailure ??= error;
267
- }
268
- }
269
- };
315
+ }): Promise<FusedMutation<TDetails, TTool>> {
316
+ // Without a command, the mutation still waits for a fused call on the same file.
317
+ if (thenRun === undefined) {
318
+ return withQueue(absolutePath, async () => {
319
+ throwIfCancelled(signal);
320
+ const outcome = await mutate();
321
+ return { outcome, observation: commitFreshness(outcome.commit) };
322
+ });
323
+ }
324
+
325
+ const progress = createProgressTracker<TDetails>({
326
+ toolCallId,
327
+ thenRun,
328
+ onProgress,
329
+ onUpdate,
330
+ });
270
331
  /** A mutation that did not complete keeps its own failure; Fusion adds only the command status. */
271
332
  const notRun = (error: unknown, command: "skipped" | "cancelled") => {
272
- report(command, "unknown");
273
- return new CommandNotRun(error, command, causeOf(progressFailure, budget.fieldBytes));
333
+ progress.report(command, "unknown");
334
+ return new CommandNotRun(error, command, progress.failure());
274
335
  };
275
- report("waiting", "unknown");
276
- let terminate: boolean | undefined;
277
- const result = await withQueue(absolutePath, async () => {
336
+ progress.report("waiting", "unknown");
337
+ return withQueue(absolutePath, async () => {
278
338
  try {
279
339
  throwIfCancelled(signal);
280
340
  } catch (error) {
281
- if (thenRun !== undefined) throw notRun(error, "cancelled");
282
- throw error;
341
+ throw notRun(error, "cancelled");
283
342
  }
284
343
  let outcome: MutationOutcome<TDetails, TTool>;
285
344
  try {
286
345
  outcome = await mutate();
287
- completedMutation = outcome;
346
+ progress.mutationCompleted(outcome.details);
288
347
  } catch (error) {
289
- if (thenRun !== undefined) throw notRun(error, "skipped");
290
- throw error;
348
+ throw notRun(error, "skipped");
291
349
  }
292
350
 
293
351
  const { publishedRevision } = outcome.commit;
294
- report("waiting", "unknown");
295
- const settle = (observation: FreshnessObservation, command?: CommandFacts) => {
296
- if (command) report(command.status, observation.freshness);
297
- // The report states publication, freshness, and the command status once.
298
- return finalizeMutation(
299
- tool,
300
- displayPath,
352
+ progress.report("waiting", "unknown");
353
+ const settle = (observation: FreshnessObservation, command: CommandFacts) => {
354
+ progress.report(command.status, observation.freshness);
355
+ return {
301
356
  outcome,
302
357
  observation,
303
- command && { ...command, progressError: progressFailure },
304
- budget,
305
- );
358
+ command: { ...command, progressError: progress.failure() },
359
+ };
306
360
  };
307
- if (thenRun === undefined) return settle(commitFreshness(outcome.commit));
308
361
 
309
362
  // A completed mutation remains successful; the command is only started on a fresh target.
310
363
  const before = await observeFreshness(absolutePath, publishedRevision, true);
311
364
  if (signal?.aborted) return settle(before, { status: "cancelled" });
312
365
  if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
313
366
 
314
- report("running", "unchanged");
367
+ progress.report("running", "unchanged");
315
368
  let command: CommandOutcome;
316
- // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
317
- let heartbeat: ReturnType<typeof setInterval> | undefined;
318
369
  try {
319
- command = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
320
- // Pi Bash emits an initial update even for silent commands. Start its
321
- // countdown here, after session permission hooks have allowed execution.
322
- if (!commandTiming && thenRun.timeout !== undefined) {
323
- commandTiming = {
324
- timeoutSeconds: thenRun.timeout,
325
- deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
326
- };
327
- if (onProgress || onUpdate) {
328
- heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
329
- heartbeat.unref();
330
- }
331
- }
332
- commandResult = { content: partial.content, details: partial.details };
333
- report("running", "unknown");
334
- });
370
+ command = await commandRunner(thenRun, signal, ctx, progress.followCommand);
335
371
  } catch (error) {
336
372
  command = {
337
373
  status: signal?.aborted ? "cancelled" : "failed",
338
374
  result: { content: [{ type: "text", text: errorMessage(error) }] },
339
375
  };
340
376
  } finally {
341
- if (heartbeat) clearInterval(heartbeat);
377
+ progress.stopHeartbeat();
342
378
  }
343
- commandResult = command.result;
344
- terminate = command.terminate;
345
- return settle(await observeFreshness(absolutePath, publishedRevision), {
379
+ progress.commandSettled(command.result);
380
+ const settled = settle(await observeFreshness(absolutePath, publishedRevision), {
346
381
  status: command.status,
347
382
  result: command.result,
348
383
  });
384
+ return command.terminate === undefined
385
+ ? settled
386
+ : { ...settled, terminate: command.terminate };
349
387
  }).catch((error: unknown) => {
350
388
  // Failures before the mutation started (such as resolving the queue key) also skip the command.
351
- if (thenRun === undefined || error instanceof CommandNotRun) throw error;
389
+ if (error instanceof CommandNotRun) throw error;
352
390
  throw notRun(error, "skipped");
353
391
  });
354
- return terminate === undefined ? result : { ...result, terminate };
355
392
  };
356
393
  }
@@ -10,22 +10,22 @@ import {
10
10
  plainRow,
11
11
  } from "./anchor-format.ts";
12
12
 
13
+ function token(line: number, content: string, hashLen: number): string {
14
+ return createAnchorFormatter(hashLen).reference(line, computeLineHash(line, content, hashLen));
15
+ }
16
+
13
17
  test("anchor formatter binds the supplied hash length and hashes undisplayed content", () => {
14
18
  const formatter = createAnchorFormatter(6);
15
- const shortFormatter = createAnchorFormatter(4);
16
19
 
17
- assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
20
+ assert.equal(token(3, "full content", 6), `3#${computeLineHash(3, "full content", 6)}`);
18
21
  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)));
22
+ assert.match(token(3, "full content", 6), new RegExp(anchorPattern(6)));
23
+ assert.doesNotMatch(token(3, "full content", 6), new RegExp(anchorPattern(4)));
21
24
  assert.equal(
22
25
  formatter.row(3, "full content", "full…"),
23
26
  `3#${computeLineHash(3, "full content", 6)}│full…`,
24
27
  );
25
- assert.equal(
26
- shortFormatter.token(3, "full content"),
27
- `3#${computeLineHash(3, "full content", 4)}`,
28
- );
28
+ assert.equal(token(3, "full content", 4), `3#${computeLineHash(3, "full content", 4)}`);
29
29
  });
30
30
 
31
31
  test("anchor tokens parse at any hash length so wrong lengths can be explained", () => {
@@ -38,7 +38,7 @@ test("anchor tokens parse at any hash length so wrong lengths can be explained",
38
38
  test("anchor rows expose carriage returns while checksums retain source content", () => {
39
39
  const formatter = createAnchorFormatter(4);
40
40
  assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
41
- assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
41
+ assert.notEqual(token(1, "a\rb", 4), token(1, "a␍b", 4));
42
42
  });
43
43
 
44
44
  test("anchor syntax rejects characters absent from the checksum alphabet", () => {
@@ -9,8 +9,10 @@
9
9
 
10
10
  import { computeLineHash, HASH_ALPHABET, HASH_LEN_MIN, HASH_LEN_MAX } from "../core/hash.ts";
11
11
 
12
+ const LINE_NUMBER = "([1-9][0-9]*)";
13
+
12
14
  function anchorSource(hashQuantifier: string): string {
13
- return `([1-9][0-9]*)#([${HASH_ALPHABET}]${hashQuantifier})`;
15
+ return `${LINE_NUMBER}#([${HASH_ALPHABET}]${hashQuantifier})`;
14
16
  }
15
17
 
16
18
  /** Schema pattern for a `LINE#HASH` anchor whose hash has exactly `hashLen` characters. */
@@ -32,7 +34,7 @@ const HASHLINE_ROW = new RegExp(
32
34
  /** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
33
35
  export function parseAnchorToken(value: string): { line: number; hash: string } | undefined {
34
36
  const match = ANCHOR_TOKEN.exec(value);
35
- return match ? { line: Number(match[1]), hash: match[2]! } : undefined;
37
+ return match ? { line: Number(match[1]), hash: match[2] } : undefined;
36
38
  }
37
39
 
38
40
  interface HashlineRow {
@@ -48,7 +50,7 @@ export function parseHashline(line: string): HashlineRow | null {
48
50
  return match ? { lineNo: match[1], content: match[3] } : null;
49
51
  }
50
52
 
51
- const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`, "s");
53
+ const PLAIN_ROW = new RegExp(`^${LINE_NUMBER}${ROW_SEPARATOR}(.*)$`, "s");
52
54
 
53
55
  /** Parse an anchored row or a non-editable `LINE│content` row; null for other text. */
54
56
  export function parseDisplayRow(line: string): HashlineRow | null {
@@ -61,7 +63,6 @@ export function parseDisplayRow(line: string): HashlineRow | null {
61
63
  /** Anchor serialization bound to a caller-supplied hash length. */
62
64
  export interface AnchorFormatter {
63
65
  reference(line: number, hash: string): string;
64
- token(line: number, content: string): string;
65
66
  row(line: number, content: string, displayContent?: string): string;
66
67
  }
67
68
 
@@ -77,12 +78,9 @@ export function plainRow(line: number, displayContent: string): string {
77
78
 
78
79
  export function createAnchorFormatter(hashLen: number): AnchorFormatter {
79
80
  const reference = (line: number, hash: string) => `${line}#${hash}`;
80
- const token = (line: number, content: string) =>
81
- reference(line, computeLineHash(line, content, hashLen));
82
81
  return {
83
- token,
84
82
  reference,
85
83
  row: (line, content, displayContent = content) =>
86
- `${token(line, content)}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`,
84
+ `${reference(line, computeLineHash(line, content, hashLen))}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`,
87
85
  };
88
86
  }