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