@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,3 +1,10 @@
1
+ /**
2
+ * File mutation commit: target checks, atomic publication, freshness, and
3
+ * revision tracking.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+
1
8
  import {
2
9
  chmod,
3
10
  lstat,
@@ -10,46 +17,66 @@ import {
10
17
  stat,
11
18
  link,
12
19
  } from "node:fs/promises";
13
- import { constants, type Stats } from "node:fs";
20
+ import type { BigIntStats, Stats } from "node:fs";
14
21
  import { dirname, join } from "node:path";
15
22
  import { createHash } from "node:crypto";
16
- import { decodeEditableText, unwritableTextReason } from "../core/text.ts";
17
- import { errorMessage } from "../core/errors.ts";
18
- import { OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
19
-
20
- export type PublicationStatus = "NOT_PUBLISHED" | "PUBLISHED" | "UNKNOWN";
21
- export type CommitMode = "create" | "overwrite";
23
+ import { decodeEditableText, unwritableTextError } from "../core/text.ts";
24
+ import {
25
+ errnoCode,
26
+ filesystemErrorCode,
27
+ HashlineError,
28
+ type ErrorCode,
29
+ type HashlineErrorArguments,
30
+ } from "../core/errors.ts";
31
+ import { cancellationError, FileChangedDuringReadError, throwIfCancelled } from "./error-text.ts";
32
+ import { withFileRead } from "./file-read.ts";
33
+ import type { Freshness, MutationStage, PublicationStatus } from "./report-schema.ts";
22
34
 
23
- export interface CommitOptions {
24
- mode: CommitMode;
25
- expectedRevision?: string;
26
- signal?: AbortSignal;
27
- /** Caller-supplied revision of the current file, skipping the readFile + SHA-256 in inspectTarget. */
28
- knownBeforeRevision?: string;
29
- }
35
+ /**
36
+ * How a commit treats the target. `create` requires that it not exist. `overwrite` requires
37
+ * that it exist; with `baseRevision` (read-modify-write), the target must still hold the bytes
38
+ * that revision names, and that revision stands in for hashing the target again.
39
+ */
40
+ export type CommitOptions = { readonly signal?: AbortSignal } & (
41
+ | { readonly mode: "create" }
42
+ | { readonly mode: "overwrite"; readonly baseRevision?: string }
43
+ );
30
44
 
31
45
  export interface MutationVersions {
32
46
  baseRevision?: string;
33
47
  publishedRevision: string;
34
- observedRevision: string;
48
+ /** Absent when a concurrent change prevented a stable observation after publication. */
49
+ observedRevision?: string;
35
50
  }
36
51
 
37
- export interface CommitResult extends MutationVersions {
38
- created: boolean;
39
- publication: "NOT_PUBLISHED" | "PUBLISHED";
40
- }
52
+ export type CommitResult = MutationVersions &
53
+ (
54
+ | { readonly created: true; readonly publication: "PUBLISHED"; readonly baseRevision?: never }
55
+ | { readonly created: false; readonly publication: "PUBLISHED"; readonly baseRevision: string }
56
+ | {
57
+ readonly created: false;
58
+ readonly publication: "NOT_PUBLISHED";
59
+ readonly baseRevision: string;
60
+ readonly observedRevision: string;
61
+ }
62
+ );
41
63
 
42
- export class FileMutationError extends Error {
43
- readonly stage: "prepare" | "commit" | "post_process";
64
+ /**
65
+ * A mutation failure with the stage it reached and what it published. Other
66
+ * failures of a mutation tool happened while preparing and published nothing.
67
+ */
68
+ export class FileMutationError<C extends ErrorCode = ErrorCode> extends HashlineError<C> {
69
+ readonly stage: MutationStage;
44
70
  readonly publication: PublicationStatus;
45
71
 
46
72
  constructor(
47
- stage: "prepare" | "commit" | "post_process",
73
+ code: C,
74
+ stage: MutationStage,
48
75
  publication: PublicationStatus,
49
76
  message: string,
50
- options?: { cause?: unknown },
77
+ ...options: HashlineErrorArguments<NoInfer<C>>
51
78
  ) {
52
- super(message, options);
79
+ super(code, message, ...options);
53
80
  this.name = "FileMutationError";
54
81
  this.stage = stage;
55
82
  this.publication = publication;
@@ -60,21 +87,16 @@ export function byteRevision(content: string | Uint8Array): string {
60
87
  return createHash("sha256").update(content).digest("hex");
61
88
  }
62
89
 
63
- function requireRegularFile(target: Stats): void {
64
- if (!target.isFile()) throw prepareError("target is not a regular file");
90
+ function requireRegularFile(target: Stats | BigIntStats): void {
91
+ if (!target.isFile()) throw prepareError("NOT_REGULAR_FILE", "Target is not a regular file.");
65
92
  }
66
93
 
67
94
  /** Check the opened object before reading; a FIFO must not block even if the path changed. */
68
95
  async function readRegularFile(path: string, signal?: AbortSignal): Promise<Buffer> {
69
- throwIfCancelled(signal);
70
- const flags = constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NONBLOCK);
71
- const handle = await open(path, flags);
72
- try {
73
- requireRegularFile(await handle.stat());
74
- return await handle.readFile({ signal });
75
- } finally {
76
- await handle.close();
77
- }
96
+ return withFileRead(path, signal, async (handle, before) => {
97
+ requireRegularFile(before);
98
+ return handle.readFile({ signal });
99
+ });
78
100
  }
79
101
 
80
102
  export async function fileRevision(path: string): Promise<string> {
@@ -82,78 +104,79 @@ export async function fileRevision(path: string): Promise<string> {
82
104
  }
83
105
 
84
106
  /** Decode and bind a mutation snapshot to the exact bytes read. */
85
- export async function readEditableSnapshot(
86
- path: string,
87
- displayPath: string,
88
- signal?: AbortSignal,
89
- ) {
107
+ export async function readEditableSnapshot(path: string, signal?: AbortSignal) {
90
108
  try {
91
109
  const bytes = await readRegularFile(path, signal);
92
110
  return { text: decodeEditableText(bytes), baseRevision: byteRevision(bytes) };
93
111
  } catch (error) {
94
- if (signal?.aborted)
95
- throw prepareError(
96
- `${OPERATION_ABORTED} before apply; ${displayPath} was not changed.`,
97
- error,
98
- );
99
- if (error instanceof FileMutationError) throw error;
100
- throw new Error(`Error reading ${displayPath}: ${errorMessage(error)}`);
112
+ if (signal?.aborted) throw asPrepareError(cancellationError());
113
+ throw error;
101
114
  }
102
115
  }
103
116
 
104
117
  /** Publish a read-modify-write result against its source revision. Callers own the queue. */
105
- export async function commitReplacement(
118
+ export function commitReplacement(
106
119
  path: string,
107
- displayPath: string,
108
120
  text: string,
109
121
  baseRevision: string,
110
122
  signal?: AbortSignal,
111
- ) {
112
- try {
113
- return await commitFile(path, text, {
114
- mode: "overwrite",
115
- expectedRevision: baseRevision,
116
- knownBeforeRevision: baseRevision,
117
- signal,
118
- });
119
- } catch (error) {
120
- if (error instanceof FileMutationError) throw error;
121
- throw new FileMutationError(
122
- "commit",
123
- "UNKNOWN",
124
- `Error writing ${displayPath}: ${errorMessage(error)}`,
125
- { cause: error },
126
- );
127
- }
123
+ ): Promise<CommitResult> {
124
+ return commitFile(path, text, { mode: "overwrite", baseRevision, signal });
125
+ }
126
+
127
+ function prepareError<C extends ErrorCode>(
128
+ code: C,
129
+ message: string,
130
+ ...options: HashlineErrorArguments<NoInfer<C>>
131
+ ): FileMutationError<C> {
132
+ return new FileMutationError(code, "prepare", "NOT_PUBLISHED", message, ...options);
133
+ }
134
+
135
+ /** A classified failure before any publication step keeps its code, facts, cause, and recovery. */
136
+ function asPrepareError<C extends ErrorCode>(error: HashlineError<C>): FileMutationError<C> {
137
+ // The original constructor already enforced its code's facts; preserve that correlated tuple.
138
+ return prepareError(
139
+ error.errorCode,
140
+ error.message,
141
+ ...([
142
+ {
143
+ cause: error.cause,
144
+ next: error.next,
145
+ facts: error.facts,
146
+ },
147
+ ] as HashlineErrorArguments<C>),
148
+ );
128
149
  }
129
150
 
130
- function prepareError(message: string, cause?: unknown): FileMutationError {
131
- return new FileMutationError("prepare", "NOT_PUBLISHED", message, { cause });
151
+ function throwIfCancelledBeforePublication(signal: AbortSignal | undefined): void {
152
+ if (signal?.aborted) throw asPrepareError(cancellationError());
132
153
  }
133
154
 
134
- function errorCode(error: unknown): string | undefined {
135
- return typeof error === "object" &&
136
- error !== null &&
137
- "code" in error &&
138
- typeof error.code === "string"
139
- ? error.code
140
- : undefined;
155
+ /** A failed filesystem step keeps the classification of its cause. */
156
+ function causeCode(error: unknown, fallback: ErrorCode): ErrorCode {
157
+ return error instanceof HashlineError
158
+ ? error.errorCode
159
+ : (filesystemErrorCode(error) ?? fallback);
141
160
  }
142
161
 
143
- interface TargetInfo {
144
- existed: boolean;
145
- publishPath: string;
146
- beforeRevision?: string;
147
- modeBits?: number;
162
+ /** A prepare-stage failure of a filesystem step: the step is the message, the failure its cause. */
163
+ function stepError(step: string, error: unknown): FileMutationError {
164
+ return prepareError(causeCode(error, "FILESYSTEM_ERROR"), step, { cause: error });
148
165
  }
149
166
 
150
- async function inspectTarget(path: string, knownBeforeRevision?: string): Promise<TargetInfo> {
167
+ type TargetInfo = { readonly publishPath: string } & (
168
+ | { readonly existed: true; readonly beforeRevision: string; readonly modeBits: number }
169
+ | { readonly existed: false; readonly beforeRevision?: never; readonly modeBits?: never }
170
+ );
171
+
172
+ /** The target's state before publication; a known revision stands in for hashing it again. */
173
+ async function inspectTarget(path: string, knownRevision?: string): Promise<TargetInfo> {
151
174
  let entry;
152
175
  try {
153
176
  entry = await lstat(path);
154
177
  } catch (error) {
155
- if (errorCode(error) === "ENOENT") return { existed: false, publishPath: path };
156
- throw prepareError(`unable to inspect target: ${errorMessage(error)}`, error);
178
+ if (errnoCode(error) === "ENOENT") return { existed: false, publishPath: path };
179
+ throw stepError("Unable to inspect target.", error);
157
180
  }
158
181
 
159
182
  let publishPath = path;
@@ -161,7 +184,9 @@ async function inspectTarget(path: string, knownBeforeRevision?: string): Promis
161
184
  try {
162
185
  publishPath = await realpath(path);
163
186
  } catch (error) {
164
- throw prepareError(`target symlink cannot be resolved: ${errorMessage(error)}`, error);
187
+ throw prepareError("SYMLINK_UNRESOLVED", "Target symlink cannot be resolved.", {
188
+ cause: error,
189
+ });
165
190
  }
166
191
  }
167
192
 
@@ -169,20 +194,23 @@ async function inspectTarget(path: string, knownBeforeRevision?: string): Promis
169
194
  try {
170
195
  target = await stat(publishPath);
171
196
  } catch (error) {
172
- throw prepareError(`unable to inspect target: ${errorMessage(error)}`, error);
197
+ throw stepError("Unable to inspect target.", error);
173
198
  }
174
199
  requireRegularFile(target);
175
200
  if (target.nlink > 1)
176
- throw prepareError("target has multiple hard links; refusing to split the link set");
201
+ throw prepareError(
202
+ "MULTIPLE_HARD_LINKS",
203
+ "Target has multiple hard links; publishing would split the link set.",
204
+ );
177
205
 
178
206
  let beforeRevision: string;
179
- if (knownBeforeRevision !== undefined) {
180
- beforeRevision = knownBeforeRevision;
207
+ if (knownRevision !== undefined) {
208
+ beforeRevision = knownRevision;
181
209
  } else {
182
210
  try {
183
211
  beforeRevision = await fileRevision(publishPath);
184
212
  } catch (error) {
185
- throw prepareError(`unable to read target revision: ${errorMessage(error)}`, error);
213
+ throw stepError("Unable to read target revision.", error);
186
214
  }
187
215
  }
188
216
  return {
@@ -220,18 +248,20 @@ async function publishCreate(
220
248
  try {
221
249
  await link(tempPath, targetPath);
222
250
  } catch (error) {
223
- if (errorCode(error) === "EEXIST" || errorCode(error) === "ENOTEMPTY") {
251
+ if (errnoCode(error) === "EEXIST" || errnoCode(error) === "ENOTEMPTY") {
224
252
  throw new FileMutationError(
253
+ "TARGET_EXISTS",
225
254
  "commit",
226
255
  "NOT_PUBLISHED",
227
- "target appeared during create; refusing to overwrite it",
256
+ "Target appeared during create.",
228
257
  { cause: error },
229
258
  );
230
259
  }
231
260
  throw new FileMutationError(
261
+ "PUBLISH_FAILED",
232
262
  "commit",
233
263
  "UNKNOWN",
234
- `unable to publish new target: ${errorMessage(error)}`,
264
+ "Unable to publish new target.",
235
265
  { cause: error },
236
266
  );
237
267
  }
@@ -248,9 +278,10 @@ async function publishReplace(
248
278
  await rename(tempPath, targetPath);
249
279
  } catch (error) {
250
280
  throw new FileMutationError(
281
+ "PUBLISH_FAILED",
251
282
  "commit",
252
283
  "UNKNOWN",
253
- `unable to publish replacement: ${errorMessage(error)}`,
284
+ "Unable to publish replacement.",
254
285
  { cause: error },
255
286
  );
256
287
  }
@@ -263,7 +294,7 @@ async function syncDirectory(path: string): Promise<void> {
263
294
  await handle.sync();
264
295
  } catch (error) {
265
296
  // Some filesystems do not support directory fsync; preserve real I/O failures.
266
- if (errorCode(error) !== "EINVAL" && errorCode(error) !== "ENOTSUP") throw error;
297
+ if (errnoCode(error) !== "EINVAL" && errnoCode(error) !== "ENOTSUP") throw error;
267
298
  } finally {
268
299
  await handle.close();
269
300
  }
@@ -277,58 +308,41 @@ export async function commitFile(
277
308
  ): Promise<CommitResult> {
278
309
  // Tools reject such input in prepareArguments, but a transformation can still produce it
279
310
  // (a regex without `u` can split a surrogate pair), so publication keeps the final check.
280
- const unwritable = unwritableTextReason(content);
281
- if (unwritable) throw prepareError(unwritable);
311
+ const unwritable = unwritableTextError(content);
312
+ if (unwritable) throw asPrepareError(unwritable);
282
313
  const bytes = Buffer.from(content, "utf8");
283
- const target = await inspectTarget(path, options.knownBeforeRevision);
284
314
  const { mode } = options;
315
+ const baseRevision = mode === "overwrite" ? options.baseRevision : undefined;
316
+ const target = await inspectTarget(path, baseRevision);
285
317
  if (mode === "create" && target.existed)
286
- throw prepareError("target already exists; use mode=overwrite");
318
+ throw prepareError("TARGET_EXISTS", "Target already exists.");
287
319
  if (mode === "overwrite" && !target.existed)
288
- throw prepareError("target does not exist; use mode=create");
289
- if (mode === "create" && options.expectedRevision !== undefined)
290
- throw prepareError("expectedRevision cannot be combined with mode=create");
291
- if (
292
- options.expectedRevision !== undefined &&
293
- (!target.beforeRevision || target.beforeRevision !== options.expectedRevision)
294
- ) {
295
- throw prepareError("expectedRevision does not match the current file");
296
- }
297
- try {
298
- throwIfCancelled(options.signal);
299
- } catch (error) {
300
- throw prepareError(`${OPERATION_ABORTED} before publication`, error);
301
- }
320
+ throw prepareError("PATH_NOT_FOUND", "Target does not exist.", { next: "useCreate" });
321
+ throwIfCancelledBeforePublication(options.signal);
302
322
  const publishedRevision = byteRevision(bytes);
303
323
  // Mode, revision, target safety, and cancellation checks still apply to no-ops.
304
324
  if (target.beforeRevision === publishedRevision) {
305
- let currentRevision = target.beforeRevision;
306
- if (options.knownBeforeRevision !== undefined) {
325
+ // A base revision was not hashed from the target here; confirm the target still holds it.
326
+ if (baseRevision !== undefined) {
327
+ let currentRevision: string;
307
328
  try {
308
- throwIfCancelled(options.signal);
329
+ throwIfCancelledBeforePublication(options.signal);
309
330
  currentRevision = await fileRevision(target.publishPath);
310
- throwIfCancelled(options.signal);
331
+ throwIfCancelledBeforePublication(options.signal);
311
332
  } catch (error) {
312
- if (options.signal?.aborted)
313
- throw prepareError(`${OPERATION_ABORTED} before publication`, error);
314
- throw prepareError(`unable to read target revision: ${errorMessage(error)}`, error);
315
- }
316
- if (options.expectedRevision !== undefined && currentRevision !== options.expectedRevision) {
317
- throw prepareError("expectedRevision does not match the current file");
318
- }
319
- if (currentRevision !== publishedRevision) {
320
- target.beforeRevision = currentRevision;
333
+ if (options.signal?.aborted) throw asPrepareError(cancellationError());
334
+ throw stepError("Unable to read target revision.", error);
321
335
  }
336
+ if (currentRevision !== baseRevision)
337
+ throw prepareError("FILE_CHANGED", "File changed after it was read.");
322
338
  }
323
- if (target.beforeRevision === publishedRevision) {
324
- return {
325
- created: false,
326
- baseRevision: target.beforeRevision,
327
- publishedRevision,
328
- observedRevision: currentRevision,
329
- publication: "NOT_PUBLISHED",
330
- };
331
- }
339
+ return {
340
+ created: false,
341
+ baseRevision: target.beforeRevision,
342
+ publishedRevision,
343
+ observedRevision: publishedRevision,
344
+ publication: "NOT_PUBLISHED",
345
+ };
332
346
  }
333
347
 
334
348
  const publishPath = target.publishPath;
@@ -339,9 +353,10 @@ export async function commitFile(
339
353
  tempDir = await mkdtemp(join(publishDirectory, ".hashline-commit-"));
340
354
  } catch (error) {
341
355
  throw new FileMutationError(
356
+ "PUBLISH_FAILED",
342
357
  "commit",
343
358
  "NOT_PUBLISHED",
344
- `unable to prepare temporary publication area: ${errorMessage(error)}`,
359
+ "Unable to prepare temporary publication area.",
345
360
  { cause: error },
346
361
  );
347
362
  }
@@ -350,34 +365,38 @@ export async function commitFile(
350
365
  let failure: unknown;
351
366
  try {
352
367
  await writeAndSyncTemp(tempPath, bytes, target.modeBits, options.signal);
353
- if (mode === "overwrite" && options.expectedRevision !== undefined) {
368
+ if (baseRevision !== undefined) {
354
369
  let currentRevision: string;
355
370
  try {
356
371
  currentRevision = await fileRevision(publishPath);
357
372
  } catch (error) {
358
- throw prepareError(`unable to recheck target revision: ${errorMessage(error)}`, error);
373
+ throw stepError("Unable to recheck target revision.", error);
359
374
  }
360
- if (currentRevision !== options.expectedRevision)
361
- throw prepareError("expectedRevision changed before publication");
375
+ if (currentRevision !== baseRevision)
376
+ throw prepareError("FILE_CHANGED", "File changed before publication.");
362
377
  }
363
378
  if (mode === "create") await publishCreate(tempPath, publishPath, options.signal);
364
379
  else await publishReplace(tempPath, publishPath, options.signal);
365
380
  published = true;
366
381
  await syncDirectory(publishDirectory);
382
+ const committed: CommitResult = {
383
+ ...(target.existed
384
+ ? { created: false, baseRevision: target.beforeRevision }
385
+ : { created: true, baseRevision: target.beforeRevision }),
386
+ publishedRevision,
387
+ publication: "PUBLISHED",
388
+ };
367
389
  try {
368
- const observedRevision = await fileRevision(publishPath);
369
- return {
370
- created: mode === "create",
371
- baseRevision: target.beforeRevision,
372
- publishedRevision,
373
- observedRevision,
374
- publication: "PUBLISHED",
375
- };
390
+ return { ...committed, observedRevision: await fileRevision(publishPath) };
376
391
  } catch (error) {
392
+ // Another writer is replacing the published bytes: report a changed target, not a failed
393
+ // mutation whose retry would apply it again.
394
+ if (error instanceof FileChangedDuringReadError) return committed;
377
395
  throw new FileMutationError(
396
+ "POST_PROCESS_FAILED",
378
397
  "post_process",
379
398
  "PUBLISHED",
380
- `target was published but final revision could not be read: ${errorMessage(error)}`,
399
+ "Final revision could not be read.",
381
400
  { cause: error },
382
401
  );
383
402
  }
@@ -386,15 +405,20 @@ export async function commitFile(
386
405
  if (error instanceof FileMutationError) throw error;
387
406
  if (published)
388
407
  throw new FileMutationError(
408
+ "POST_PROCESS_FAILED",
389
409
  "post_process",
390
410
  "PUBLISHED",
391
- `target was published but post-publication processing failed: ${errorMessage(error)}`,
411
+ "Post-publication processing failed.",
392
412
  { cause: error },
393
413
  );
414
+ // Cancellation keeps its own record; any other failure here stopped before publication.
415
+ if (error instanceof HashlineError && error.errorCode === "OPERATION_ABORTED")
416
+ throw new FileMutationError("OPERATION_ABORTED", "commit", "NOT_PUBLISHED", error.message);
394
417
  throw new FileMutationError(
418
+ "PUBLISH_FAILED",
395
419
  "commit",
396
420
  "NOT_PUBLISHED",
397
- `unable to prepare or publish target: ${errorMessage(error)}`,
421
+ "Unable to prepare or publish target.",
398
422
  { cause: error },
399
423
  );
400
424
  } finally {
@@ -406,9 +430,10 @@ export async function commitFile(
406
430
  throw error;
407
431
  }
408
432
  throw new FileMutationError(
433
+ "POST_PROCESS_FAILED",
409
434
  "post_process",
410
435
  "PUBLISHED",
411
- `target was published but temporary cleanup failed: ${errorMessage(error)}`,
436
+ "Temporary cleanup failed.",
412
437
  {
413
438
  cause:
414
439
  failure === undefined
@@ -419,3 +444,45 @@ export async function commitFile(
419
444
  }
420
445
  }
421
446
  }
447
+
448
+ /** What the commit layer knows about the target relative to its published revision. */
449
+ export type FreshnessObservation =
450
+ | { readonly freshness: Exclude<Freshness, "unknown">; readonly error?: never }
451
+ | {
452
+ readonly freshness: "unknown";
453
+ /** Why the revision could not be read. */
454
+ readonly error: unknown;
455
+ };
456
+
457
+ /** Freshness known from the commit result alone, before any later observation. */
458
+ export function commitFreshness(commit: MutationVersions): FreshnessObservation {
459
+ return {
460
+ freshness: commit.publishedRevision === commit.observedRevision ? "unchanged" : "changed",
461
+ };
462
+ }
463
+
464
+ /**
465
+ * Read the target again and compare it with the published revision. With
466
+ * `settle`, two reads across a turn of the event loop catch a write in progress.
467
+ * A failed read is itself an observation: the mutation is already published, so
468
+ * a concurrent change or deletion must not suggest retrying it.
469
+ */
470
+ export async function observeFreshness(
471
+ path: string,
472
+ publishedRevision: string,
473
+ settle = false,
474
+ ): Promise<FreshnessObservation> {
475
+ try {
476
+ const first = await fileRevision(path);
477
+ if (settle) {
478
+ await new Promise<void>((resolve) => setImmediate(resolve));
479
+ if ((await fileRevision(path)) !== first) return { freshness: "changed" };
480
+ }
481
+ return { freshness: first === publishedRevision ? "unchanged" : "changed" };
482
+ } catch (error) {
483
+ // A write observed during the read has already moved the target off the published revision.
484
+ if (error instanceof FileChangedDuringReadError) return { freshness: "changed" };
485
+ if (errnoCode(error) === "ENOENT") return { freshness: "missing" };
486
+ return { freshness: "unknown", error };
487
+ }
488
+ }
@@ -0,0 +1,29 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { withFileRead } from "./file-read.ts";
7
+
8
+ for (const replacement of ["", "汉字\n"]) {
9
+ test(`${replacement ? "same-size rewrite" : "truncation"} during a whole-file read → rejects the unstable snapshot`, async (t) => {
10
+ const directory = await mkdtemp(join(tmpdir(), "hashline-file-read-"));
11
+ t.after(() => rm(directory, { recursive: true, force: true }));
12
+ const path = join(directory, "source.txt");
13
+ await writeFile(path, "中文\n");
14
+ await utimes(path, new Date(0), new Date(0));
15
+ await assert.rejects(
16
+ withFileRead(path, undefined, async (handle) => {
17
+ const bytes = await handle.readFile();
18
+ await writeFile(path, replacement);
19
+ return bytes;
20
+ }),
21
+ /File changed/,
22
+ );
23
+ assert.equal(await readFile(path, "utf8"), replacement);
24
+ assert.equal(
25
+ (await withFileRead(path, undefined, (handle) => handle.readFile())).toString("utf8"),
26
+ replacement,
27
+ );
28
+ });
29
+ }
@@ -0,0 +1,60 @@
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";
6
+ import { FileChangedDuringReadError, throwIfCancelled } from "./error-text.ts";
7
+
8
+ function sameObservation(before: BigIntStats, after: BigIntStats): boolean {
9
+ return (
10
+ before.dev === after.dev &&
11
+ before.ino === after.ino &&
12
+ before.size === after.size &&
13
+ before.mtimeNs === after.mtimeNs &&
14
+ before.ctimeNs === after.ctimeNs
15
+ );
16
+ }
17
+
18
+ /**
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.
22
+ */
23
+ export async function withFileRead<T>(
24
+ path: string,
25
+ signal: AbortSignal | undefined,
26
+ read: (handle: FileHandle, before: BigIntStats) => Promise<T>,
27
+ ): Promise<T> {
28
+ throwIfCancelled(signal);
29
+ const flags = constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NONBLOCK);
30
+ const handle = await open(path, flags);
31
+ try {
32
+ throwIfCancelled(signal);
33
+ 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
+ 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;
49
+ }
50
+ throwIfCancelled(signal);
51
+ if (!sameObservation(before, after) || !sameObservation(before, current)) {
52
+ throw new FileChangedDuringReadError();
53
+ }
54
+ }
55
+ if (!outcome.ok) throw outcome.error;
56
+ return outcome.value;
57
+ } finally {
58
+ await handle.close();
59
+ }
60
+ }
@@ -11,7 +11,7 @@ test("snapshot cancelled while opening → rejects as an unpublished cancellatio
11
11
  const path = join(directory, "file.txt");
12
12
  await writeFile(path, "before\n");
13
13
  const controller = new AbortController();
14
- const reading = readEditableSnapshot(path, "file.txt", controller.signal);
14
+ const reading = readEditableSnapshot(path, controller.signal);
15
15
  controller.abort();
16
16
  await assert.rejects(
17
17
  reading,