@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
@@ -18,10 +18,9 @@ import {
18
18
  link,
19
19
  type FileHandle,
20
20
  } from "node:fs/promises";
21
- import type { BigIntStats, Stats } from "node:fs";
22
21
  import { dirname, join } from "node:path";
23
22
  import { byteRevision } from "./file-revision.ts";
24
- import { decodeEditableText, unwritableTextError } from "../core/text.ts";
23
+ import { unwritableTextError } from "../core/text.ts";
25
24
  import {
26
25
  errnoCode,
27
26
  filesystemErrorCode,
@@ -30,31 +29,44 @@ import {
30
29
  HashlineError,
31
30
  } from "../core/errors.ts";
32
31
  import { FileChangedDuringReadError, throwIfCancelled } from "./error-text.ts";
33
- import { withFileRead } from "./file-read.ts";
32
+ import { readFileRevision, requireRegularFile } from "./file-read.ts";
34
33
  import type { Freshness, PublicationStatus } from "./report-schema.ts";
35
34
 
36
35
  /**
37
- * How a commit treats the target. `create` requires that it not exist. `overwrite` requires
38
- * that it exist; with `baseRevision` (read-modify-write), the target must still hold the bytes
39
- * that revision names, and that revision stands in for hashing the target again.
36
+ * How a commit treats the target. `create` requires that it not exist. `overwrite` requires that
37
+ * it exist and replaces it whole. `update` (read-modify-write) also requires that it still hold
38
+ * the bytes `baseRevision` names, and that revision stands in for hashing the target again.
40
39
  */
41
- type CommitOptions = { readonly signal?: AbortSignal } & (
40
+ export type CommitIntent =
42
41
  | { readonly mode: "create" }
43
- | { readonly mode: "overwrite"; readonly baseRevision?: string }
44
- );
42
+ | { readonly mode: "overwrite" }
43
+ | { readonly mode: "update"; readonly baseRevision: string };
45
44
 
46
- /** The published bytes' revision and, when stable, the revision observed right after. */
47
- interface CommitRevisions {
48
- readonly publishedRevision: string;
49
- /** Absent when a concurrent change prevented a stable observation after publication. */
50
- readonly observedRevision?: string;
51
- }
45
+ type ReplaceMode = Exclude<CommitIntent["mode"], "create">;
46
+
47
+ /** What publication does, decided once the target has been inspected. */
48
+ type PublishPlan =
49
+ | { readonly kind: "create" }
50
+ | {
51
+ readonly kind: "replace";
52
+ readonly mode: ReplaceMode;
53
+ readonly target: TargetInfo;
54
+ /** The revision the target holds before the commit; an update's base revision. */
55
+ readonly beforeRevision: string;
56
+ };
52
57
 
53
- export type CommitResult = CommitRevisions &
54
- (
55
- | { readonly publication: "PUBLISHED" }
56
- | { readonly publication: "NOT_PUBLISHED"; readonly observedRevision: string }
57
- );
58
+ /**
59
+ * The published bytes' revision, and whether the target still held them right after the
60
+ * commit; an unstable observation after publication means another writer changed it. Content
61
+ * equal to the target's is not published, and the target is unchanged.
62
+ */
63
+ export type CommitResult = { readonly publishedRevision: string } & (
64
+ | { readonly publication: "NOT_PUBLISHED"; readonly freshness: "unchanged" }
65
+ | {
66
+ readonly publication: "PUBLISHED";
67
+ readonly freshness: Extract<Freshness, "unchanged" | "changed">;
68
+ }
69
+ );
58
70
 
59
71
  /**
60
72
  * A mutation failure with what it published. Every other failure of a mutation
@@ -75,65 +87,8 @@ export class FileMutationError extends HashlineError<"PUBLISH_FAILED" | "POST_PR
75
87
  }
76
88
  }
77
89
 
78
- function requireRegularFile(target: Stats | BigIntStats): void {
79
- if (!target.isFile())
80
- throw new HashlineError("NOT_REGULAR_FILE", PATH_ERROR_MESSAGES.NOT_REGULAR_FILE);
81
- }
82
-
83
- const REGULAR_FILE_READ_CHUNK_BYTES = 64 * 1024;
84
-
85
- /** Read a regular file in full, even when the filesystem returns short reads. */
86
- async function readRegularFileBytes(
87
- handle: FileHandle,
88
- size: bigint,
89
- signal: AbortSignal | undefined,
90
- ): Promise<Buffer> {
91
- const chunks: Buffer[] = [];
92
- let position = 0n;
93
- while (position < size) {
94
- throwIfCancelled(signal);
95
- const remaining = size - position;
96
- const length = Number(
97
- remaining < BigInt(REGULAR_FILE_READ_CHUNK_BYTES)
98
- ? remaining
99
- : BigInt(REGULAR_FILE_READ_CHUNK_BYTES),
100
- );
101
- const buffer = Buffer.allocUnsafe(length);
102
- const result = await handle.read({
103
- buffer,
104
- offset: 0,
105
- length,
106
- position: Number(position),
107
- });
108
- if (result.bytesRead <= 0 || result.bytesRead > length) throw new FileChangedDuringReadError();
109
- chunks.push(buffer.subarray(0, result.bytesRead));
110
- position += BigInt(result.bytesRead);
111
- }
112
- return Buffer.concat(chunks);
113
- }
114
-
115
- /** Check the opened object before reading; a FIFO must not block even if the path changed. */
116
- async function readRegularFile(path: string, signal?: AbortSignal): Promise<Buffer> {
117
- return withFileRead(path, signal, async (handle, before) => {
118
- requireRegularFile(before);
119
- return readRegularFileBytes(handle, before.size, signal);
120
- });
121
- }
122
-
123
- async function fileRevision(path: string, signal?: AbortSignal): Promise<string> {
124
- return byteRevision(await readRegularFile(path, signal));
125
- }
126
-
127
- /** Decode and bind a mutation snapshot to the exact bytes read. */
128
- export async function readEditableSnapshot(path: string, signal: AbortSignal | undefined) {
129
- try {
130
- const bytes = await readRegularFile(path, signal);
131
- return { text: decodeEditableText(bytes), baseRevision: byteRevision(bytes) };
132
- } catch (error) {
133
- throwIfCancelled(signal);
134
- throw error;
135
- }
136
- }
90
+ /** Observations of a published target run to completion: the report must state what was published. */
91
+ const UNCANCELLABLE = new AbortController().signal;
137
92
 
138
93
  /**
139
94
  * A failure of a filesystem step before publication: the step is the message, the failure its
@@ -152,11 +107,11 @@ function stepError(step: string, error: unknown): HashlineError {
152
107
  async function requireBaseRevision(
153
108
  path: string,
154
109
  baseRevision: string,
155
- signal: AbortSignal | undefined,
110
+ signal: AbortSignal,
156
111
  ): Promise<void> {
157
112
  let currentRevision: string;
158
113
  try {
159
- currentRevision = await fileRevision(path, signal);
114
+ currentRevision = await readFileRevision(path, signal);
160
115
  } catch (error) {
161
116
  throwIfCancelled(signal);
162
117
  throw stepError("Unable to recheck target revision.", error);
@@ -207,22 +162,59 @@ async function inspectTarget(path: string): Promise<TargetInfo | undefined> {
207
162
  return { publishPath, modeBits: target.mode };
208
163
  }
209
164
 
210
- async function requireOverwriteTarget(path: string, baseRevision: string | undefined) {
165
+ async function requireExistingTarget(path: string, mode: ReplaceMode) {
211
166
  const target = await inspectTarget(path);
212
167
  if (!target)
213
168
  throw new HashlineError("PATH_NOT_FOUND", PATH_ERROR_MESSAGES.PATH_NOT_FOUND, {
214
169
  facts: { missing: [path] },
215
170
  // Read-modify-write tools have no mode to change.
216
- next: baseRevision === undefined ? "useCreate" : undefined,
171
+ ...(mode === "overwrite" ? { next: "useCreate" as const } : {}),
217
172
  });
218
173
  return target;
219
174
  }
220
175
 
176
+ /** Inspect the target once and decide how to publish over it. */
177
+ async function planPublication(
178
+ path: string,
179
+ intent: CommitIntent,
180
+ signal: AbortSignal,
181
+ ): Promise<PublishPlan> {
182
+ if (intent.mode === "create") {
183
+ if (await inspectTarget(path))
184
+ throw new HashlineError("TARGET_EXISTS", "Target already exists.");
185
+ throwIfCancelled(signal);
186
+ return { kind: "create" };
187
+ }
188
+ const { mode } = intent;
189
+ const target = await requireExistingTarget(path, mode);
190
+ throwIfCancelled(signal);
191
+ if (mode === "update")
192
+ return { kind: "replace", mode, target, beforeRevision: intent.baseRevision };
193
+ try {
194
+ return { kind: "replace", mode, target, beforeRevision: await readFileRevision(path, signal) };
195
+ } catch (error) {
196
+ throwIfCancelled(signal);
197
+ throw stepError("Unable to read target revision.", error);
198
+ }
199
+ }
200
+
201
+ /** Before replacing: an update's base revision still holds and the path names the inspected file. */
202
+ async function recheckReplace(
203
+ path: string,
204
+ plan: Extract<PublishPlan, { readonly kind: "replace" }>,
205
+ signal: AbortSignal,
206
+ ): Promise<void> {
207
+ if (plan.mode === "update") await requireBaseRevision(path, plan.beforeRevision, signal);
208
+ const current = await requireExistingTarget(path, plan.mode);
209
+ throwIfCancelled(signal);
210
+ if (current.publishPath !== plan.target.publishPath)
211
+ throw new HashlineError("FILE_CHANGED", "Target path resolves to a different file.");
212
+ }
213
+
221
214
  async function writeAndSyncTemp(
222
215
  tempPath: string,
223
216
  content: Buffer,
224
- modeBits: number | undefined,
225
- signal: AbortSignal | undefined,
217
+ signal: AbortSignal,
226
218
  ): Promise<void> {
227
219
  throwIfCancelled(signal);
228
220
  // A new file takes the umask's default mode; its private temp directory hides it until publication.
@@ -233,13 +225,12 @@ async function writeAndSyncTemp(
233
225
  } finally {
234
226
  await handle.close();
235
227
  }
236
- if (modeBits !== undefined) await chmod(tempPath, modeBits & 0o7777);
237
228
  }
238
229
 
239
230
  async function publishCreate(
240
231
  tempPath: string,
241
232
  targetPath: string,
242
- signal: AbortSignal | undefined,
233
+ signal: AbortSignal,
243
234
  ): Promise<void> {
244
235
  // link() creates an unclobberable directory entry on the same filesystem, avoiding create/replace races.
245
236
  throwIfCancelled(signal);
@@ -258,7 +249,7 @@ async function publishCreate(
258
249
  async function publishReplace(
259
250
  tempPath: string,
260
251
  targetPath: string,
261
- signal: AbortSignal | undefined,
252
+ signal: AbortSignal,
262
253
  ): Promise<void> {
263
254
  // rename() replaces the directory entry atomically without deleting the old file first; readers observe old or new.
264
255
  throwIfCancelled(signal);
@@ -299,52 +290,47 @@ async function makeTempDirectory(directory: string): Promise<string> {
299
290
  return mkdtemp(prefix);
300
291
  }
301
292
 
293
+ /** After the publish syscall succeeds, an unstable target is a change by another writer. */
294
+ async function publishedFreshness(
295
+ path: string,
296
+ revision: string,
297
+ ): Promise<"unchanged" | "changed"> {
298
+ try {
299
+ return (await readFileRevision(path, UNCANCELLABLE)) === revision ? "unchanged" : "changed";
300
+ } catch (error) {
301
+ if (error instanceof FileChangedDuringReadError) return "changed";
302
+ throw new FileMutationError(
303
+ "POST_PROCESS_FAILED",
304
+ "PUBLISHED",
305
+ "Final revision could not be read.",
306
+ { cause: error },
307
+ );
308
+ }
309
+ }
310
+
302
311
  /** Validate the target, skip identical content, otherwise sync and publish. Callers own the file queue. */
303
312
  export async function commitFile(
304
313
  path: string,
305
314
  content: string,
306
- options: CommitOptions,
315
+ intent: CommitIntent,
316
+ signal: AbortSignal,
307
317
  ): Promise<CommitResult> {
308
- // Tools reject such input in prepareArguments, but a transformation can still produce it
318
+ // The argument boundary rejects such input, but a transformation can still produce it
309
319
  // (a regex without `u` can split a surrogate pair), so publication keeps the final check.
310
320
  const unwritable = unwritableTextError(content);
311
321
  if (unwritable) throw unwritable;
312
322
  const bytes = Buffer.from(content, "utf8");
313
- const { mode } = options;
314
- const baseRevision = mode === "overwrite" ? options.baseRevision : undefined;
315
- const target =
316
- mode === "overwrite" ? await requireOverwriteTarget(path, baseRevision) : undefined;
317
- if (mode === "create" && (await inspectTarget(path)))
318
- throw new HashlineError("TARGET_EXISTS", "Target already exists.");
319
- throwIfCancelled(options.signal);
323
+ // Hash before reading the target's revision, so no hashing time separates that read from the
324
+ // no-change decision below.
320
325
  const publishedRevision = byteRevision(bytes);
321
- const verifyOverwrite = async (initial: TargetInfo) => {
322
- if (baseRevision !== undefined) await requireBaseRevision(path, baseRevision, options.signal);
323
- const current = await requireOverwriteTarget(path, baseRevision);
324
- throwIfCancelled(options.signal);
325
- if (current.publishPath !== initial.publishPath)
326
- throw new HashlineError("FILE_CHANGED", "Target path resolves to a different file.");
327
- };
328
- let beforeRevision = baseRevision;
329
- if (target && beforeRevision === undefined) {
330
- try {
331
- beforeRevision = await fileRevision(path, options.signal);
332
- } catch (error) {
333
- throwIfCancelled(options.signal);
334
- throw stepError("Unable to read target revision.", error);
335
- }
336
- }
326
+ const plan = await planPublication(path, intent, signal);
337
327
  // Check a bound snapshot even when the transformation produced no change.
338
- if (target && beforeRevision === publishedRevision) {
339
- await verifyOverwrite(target);
340
- return {
341
- publishedRevision,
342
- observedRevision: publishedRevision,
343
- publication: "NOT_PUBLISHED",
344
- };
328
+ if (plan.kind === "replace" && plan.beforeRevision === publishedRevision) {
329
+ await recheckReplace(path, plan, signal);
330
+ return { publication: "NOT_PUBLISHED", publishedRevision, freshness: "unchanged" };
345
331
  }
346
332
 
347
- const publishPath = target?.publishPath ?? path;
333
+ const publishPath = plan.kind === "replace" ? plan.target.publishPath : path;
348
334
  const publishDirectory = dirname(publishPath);
349
335
  let tempDir: string;
350
336
  try {
@@ -355,47 +341,35 @@ export async function commitFile(
355
341
  });
356
342
  }
357
343
  const tempPath = join(tempDir, "content");
358
- let published = false;
359
344
  try {
360
- await writeAndSyncTemp(tempPath, bytes, target?.modeBits, options.signal);
361
- if (target) {
362
- await verifyOverwrite(target);
363
- await publishReplace(tempPath, publishPath, options.signal);
364
- } else {
365
- await publishCreate(tempPath, publishPath, options.signal);
366
- }
367
- published = true;
368
- await syncDirectory(publishDirectory);
369
- const committed: CommitResult = {
370
- publishedRevision,
371
- publication: "PUBLISHED",
372
- };
373
345
  try {
374
- return { ...committed, observedRevision: await fileRevision(path) };
346
+ await writeAndSyncTemp(tempPath, bytes, signal);
347
+ if (plan.kind === "replace") {
348
+ await chmod(tempPath, plan.target.modeBits & 0o7777);
349
+ await recheckReplace(path, plan, signal);
350
+ await publishReplace(tempPath, publishPath, signal);
351
+ } else {
352
+ await publishCreate(tempPath, publishPath, signal);
353
+ }
375
354
  } catch (error) {
376
- // Another writer is replacing the published bytes: report a changed target, not a failed
377
- // mutation whose retry would apply it again.
378
- if (error instanceof FileChangedDuringReadError) return committed;
379
- throw new FileMutationError(
380
- "POST_PROCESS_FAILED",
381
- "PUBLISHED",
382
- "Final revision could not be read.",
383
- { cause: error },
384
- );
355
+ if (error instanceof HashlineError) throw error;
356
+ throw new HashlineError("PUBLISH_FAILED", "Unable to prepare or publish target.", {
357
+ cause: error,
358
+ });
385
359
  }
386
- } catch (error) {
387
- // Already classified, including cancellation and every publication failure.
388
- if (error instanceof HashlineError) throw error;
389
- if (published)
360
+ await syncDirectory(publishDirectory).catch((error: unknown) => {
390
361
  throw new FileMutationError(
391
362
  "POST_PROCESS_FAILED",
392
363
  "PUBLISHED",
393
364
  "Post-publication processing failed.",
394
365
  { cause: error },
395
366
  );
396
- throw new HashlineError("PUBLISH_FAILED", "Unable to prepare or publish target.", {
397
- cause: error,
398
367
  });
368
+ return {
369
+ publication: "PUBLISHED",
370
+ publishedRevision,
371
+ freshness: await publishedFreshness(path, publishedRevision),
372
+ };
399
373
  } finally {
400
374
  // Best effort: a leftover temporary directory changes neither the publication nor the recovery.
401
375
  await rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
@@ -411,29 +385,22 @@ export type FreshnessObservation =
411
385
  readonly error: unknown;
412
386
  };
413
387
 
414
- /** Freshness known from the commit result alone, before any later observation. */
415
- export function commitFreshness(commit: CommitRevisions): FreshnessObservation {
416
- return {
417
- freshness: commit.publishedRevision === commit.observedRevision ? "unchanged" : "changed",
418
- };
419
- }
420
-
421
388
  /**
422
- * Read the target again and compare it with the published revision. With
423
- * `settle`, two reads across a turn of the event loop catch a write in progress.
389
+ * Read the target again and compare it with the published revision. Before a command,
390
+ * two reads across a turn of the event loop catch a write in progress.
424
391
  * A failed read is itself an observation: the mutation is already published, so
425
392
  * a concurrent change or deletion must not suggest retrying it.
426
393
  */
427
394
  export async function observeFreshness(
428
395
  path: string,
429
396
  publishedRevision: string,
430
- settle = false,
397
+ phase: "before-command" | "after-command",
431
398
  ): Promise<FreshnessObservation> {
432
399
  try {
433
- const first = await fileRevision(path);
434
- if (settle) {
400
+ const first = await readFileRevision(path, UNCANCELLABLE);
401
+ if (phase === "before-command") {
435
402
  await new Promise<void>((resolve) => setImmediate(resolve));
436
- if ((await fileRevision(path)) !== first) return { freshness: "changed" };
403
+ if ((await readFileRevision(path, UNCANCELLABLE)) !== first) return { freshness: "changed" };
437
404
  }
438
405
  return { freshness: first === publishedRevision ? "unchanged" : "changed" };
439
406
  } catch (error) {
@@ -1,9 +1,17 @@
1
- /** Guard file reads with metadata observations; byte revisions still own search and commit freshness. */
2
- import { constants, type BigIntStats } from "node:fs";
3
- import { open, stat, type FileHandle } from "node:fs/promises";
4
- import { errnoCode } from "../core/errors.ts";
5
- import { Utf8DecodingError } from "../core/text.ts";
1
+ /** Guard snapshots and streamed revisions with the same handle and path observations. */
2
+ import { constants, createReadStream, type BigIntStats, type Stats } from "node:fs";
3
+ import { open, stat } from "node:fs/promises";
4
+ import { errnoCode, HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
5
+ import { decodeEditableText } from "../core/text.ts";
6
6
  import { FileChangedDuringReadError, throwIfCancelled } from "./error-text.ts";
7
+ import { createRevisionHasher } from "./file-revision.ts";
8
+
9
+ const READ_CHUNK_BYTES = 64 * 1024;
10
+
11
+ export function requireRegularFile(target: Stats | BigIntStats): void {
12
+ if (!target.isFile())
13
+ throw new HashlineError("NOT_REGULAR_FILE", PATH_ERROR_MESSAGES.NOT_REGULAR_FILE);
14
+ }
7
15
 
8
16
  function sameObservation(before: BigIntStats, after: BigIntStats): boolean {
9
17
  return (
@@ -15,46 +23,129 @@ function sameObservation(before: BigIntStats, after: BigIntStats): boolean {
15
23
  );
16
24
  }
17
25
 
26
+ type ByteConsumer = {
27
+ readonly onChunk: (bytes: Buffer) => void | Promise<void>;
28
+ } & (
29
+ | { readonly extent: "size" }
30
+ | { readonly extent: "eof"; readonly onEnd: () => void | Promise<void> }
31
+ );
32
+
33
+ /** Fill each block before handing it to a consumer, even when the handle returns short reads. */
34
+ async function* sizedChunks(
35
+ handle: Awaited<ReturnType<typeof open>>,
36
+ before: BigIntStats,
37
+ signal: AbortSignal,
38
+ allocate: (length: number) => Buffer,
39
+ ) {
40
+ requireRegularFile(before);
41
+ for (let position = 0n; position < before.size; ) {
42
+ const length = Math.min(Number(before.size - position), READ_CHUNK_BYTES);
43
+ const buffer = allocate(length);
44
+ let offset = 0;
45
+ while (offset < length) {
46
+ throwIfCancelled(signal);
47
+ const remaining = length - offset;
48
+ const { bytesRead } = await handle.read({
49
+ buffer,
50
+ offset,
51
+ length: remaining,
52
+ position: Number(position + BigInt(offset)),
53
+ });
54
+ throwIfCancelled(signal);
55
+ if (bytesRead <= 0 || bytesRead > remaining) throw new FileChangedDuringReadError();
56
+ offset += bytesRead;
57
+ }
58
+ yield buffer;
59
+ position += BigInt(length);
60
+ }
61
+ }
62
+
18
63
  /**
19
- * Compare the opened file and current path before accepting bytes or an encoding error.
20
- * This detects observable writes/replacements, not changes hidden by filesystem timestamp resolution.
21
- * The callback owns its stream; the handle closes on success, failure, and cancellation.
64
+ * Hash the actual bytes and check the opened file and current path before returning their revision.
65
+ * Metadata cannot detect changes hidden by timestamp resolution.
66
+ * Mutations bind to the initial size of a regular file. Only editable snapshots retain the chunks.
67
+ * Text scans use Node’s read-ahead to EOF, including virtual files that report zero size.
22
68
  */
23
- export async function withFileRead<T>(
69
+ export async function readFileRevision(
24
70
  path: string,
25
- signal: AbortSignal | undefined,
26
- read: (handle: FileHandle, before: BigIntStats) => Promise<T>,
27
- ): Promise<T> {
71
+ signal: AbortSignal,
72
+ consumer?: ByteConsumer,
73
+ ): Promise<string> {
28
74
  throwIfCancelled(signal);
29
75
  const flags = constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NONBLOCK);
30
76
  const handle = await open(path, flags);
31
77
  try {
32
78
  throwIfCancelled(signal);
33
79
  const before = await handle.stat({ bigint: true });
34
- const outcome = await read(handle, before).then(
35
- (value) => ({ ok: true, value }) as const,
36
- (error: unknown) => ({ ok: false, error }) as const,
37
- );
38
80
  throwIfCancelled(signal);
39
- if (outcome.ok || outcome.error instanceof Utf8DecodingError) {
40
- const after = await handle.stat({ bigint: true });
41
- let current: BigIntStats;
42
- try {
43
- current = await stat(path, { bigint: true });
44
- } catch (error) {
45
- if (errnoCode(error) === "ENOENT") {
46
- throw new FileChangedDuringReadError();
47
- }
48
- throw error;
81
+ const revision = createRevisionHasher();
82
+ try {
83
+ // Snapshots retain blocks. A revision alone can reuse its first block up to the final slice.
84
+ let scratch: Buffer | undefined;
85
+ const chunks =
86
+ consumer?.extent === "eof"
87
+ ? createReadStream(path, {
88
+ fd: handle,
89
+ autoClose: false,
90
+ highWaterMark: READ_CHUNK_BYTES,
91
+ })
92
+ : sizedChunks(
93
+ handle,
94
+ before,
95
+ signal,
96
+ consumer
97
+ ? Buffer.allocUnsafe
98
+ : (length) => (scratch ??= Buffer.allocUnsafe(length)).subarray(0, length),
99
+ );
100
+ for await (const chunk of chunks) {
101
+ // Keep cancellation in the consumer so it cannot emit a stream error during teardown.
102
+ throwIfCancelled(signal);
103
+ // The Node stream has no encoding set; both sources produce Buffers.
104
+ const bytes = chunk as Buffer;
105
+ revision.update(bytes);
106
+ const pending = consumer?.onChunk(bytes);
107
+ if (pending) await pending;
49
108
  }
50
- throwIfCancelled(signal);
51
- if (!sameObservation(before, after) || !sameObservation(before, current)) {
52
- throw new FileChangedDuringReadError();
109
+ if (consumer?.extent === "eof") {
110
+ throwIfCancelled(signal);
111
+ await consumer.onEnd();
53
112
  }
113
+ } catch (error) {
114
+ throwIfCancelled(signal);
115
+ throw error;
54
116
  }
55
- if (!outcome.ok) throw outcome.error;
56
- return outcome.value;
117
+ throwIfCancelled(signal);
118
+ const after = await handle.stat({ bigint: true });
119
+ let current: BigIntStats;
120
+ try {
121
+ current = await stat(path, { bigint: true });
122
+ } catch (error) {
123
+ if (errnoCode(error) === "ENOENT") throw new FileChangedDuringReadError();
124
+ throw error;
125
+ }
126
+ throwIfCancelled(signal);
127
+ if (!sameObservation(before, after) || !sameObservation(before, current))
128
+ throw new FileChangedDuringReadError();
129
+ return revision.digest();
57
130
  } finally {
58
131
  await handle.close();
59
132
  }
60
133
  }
134
+
135
+ /** Decode and bind a mutation snapshot to the exact bytes read. */
136
+ export async function readEditableSnapshot(path: string, signal: AbortSignal) {
137
+ const chunks: Buffer[] = [];
138
+ try {
139
+ const baseRevision = await readFileRevision(path, signal, {
140
+ extent: "size",
141
+ onChunk: (bytes) => {
142
+ chunks.push(bytes);
143
+ },
144
+ });
145
+ const bytes = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
146
+ return { text: decodeEditableText(bytes), baseRevision };
147
+ } catch (error) {
148
+ throwIfCancelled(signal);
149
+ throw error;
150
+ }
151
+ }