@ricsam/r5d-worker 0.0.122 → 0.0.124

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 (67) hide show
  1. package/README.md +6 -3
  2. package/dist/cjs/command-launcher.cjs +76 -2
  3. package/dist/cjs/control-command-policy.cjs +177 -0
  4. package/dist/cjs/main.cjs +541 -247
  5. package/dist/cjs/package.json +1 -1
  6. package/dist/cjs/project-checkout-garbage.cjs +32 -3
  7. package/dist/cjs/project-workspace-state.cjs +51 -35
  8. package/dist/cjs/project-worktrees.cjs +79 -34
  9. package/dist/cjs/recovery-journal-protocol.cjs +56 -0
  10. package/dist/cjs/recovery-journal-runtime.cjs +133 -0
  11. package/dist/cjs/recovery-journal-thread.cjs +9 -0
  12. package/dist/cjs/recovery-journal.cjs +735 -0
  13. package/dist/cjs/recovery-store.cjs +8 -0
  14. package/dist/cjs/session-file-mutations.cjs +61 -0
  15. package/dist/cjs/working-tree-mirror.cjs +1 -0
  16. package/dist/cjs/workspace-command-sync-policy.cjs +37 -8
  17. package/dist/cjs/workspace-filesystem-executor-thread.cjs +36 -0
  18. package/dist/cjs/workspace-filesystem-executor.cjs +327 -0
  19. package/dist/cjs/workspace-filesystem-job-types.cjs +134 -0
  20. package/dist/cjs/workspace-filesystem-jobs.cjs +57 -0
  21. package/dist/cjs/workspace-git-sync.cjs +275 -201
  22. package/dist/cjs/workspace-mount-hold-fence.cjs +120 -0
  23. package/dist/mjs/command-launcher.mjs +75 -2
  24. package/dist/mjs/control-command-policy.mjs +146 -0
  25. package/dist/mjs/main.mjs +549 -253
  26. package/dist/mjs/package.json +1 -1
  27. package/dist/mjs/project-checkout-garbage.mjs +30 -2
  28. package/dist/mjs/project-workspace-state.mjs +51 -35
  29. package/dist/mjs/project-worktrees.mjs +74 -34
  30. package/dist/mjs/recovery-journal-protocol.mjs +30 -0
  31. package/dist/mjs/recovery-journal-runtime.mjs +112 -0
  32. package/dist/mjs/recovery-journal-thread.mjs +8 -0
  33. package/dist/mjs/recovery-journal.mjs +687 -0
  34. package/dist/mjs/recovery-store.mjs +8 -0
  35. package/dist/mjs/session-file-mutations.mjs +37 -0
  36. package/dist/mjs/working-tree-mirror.mjs +1 -0
  37. package/dist/mjs/workspace-command-sync-policy.mjs +37 -8
  38. package/dist/mjs/workspace-filesystem-executor-thread.mjs +38 -0
  39. package/dist/mjs/workspace-filesystem-executor.mjs +287 -0
  40. package/dist/mjs/workspace-filesystem-job-types.mjs +106 -0
  41. package/dist/mjs/workspace-filesystem-jobs.mjs +51 -0
  42. package/dist/mjs/workspace-git-sync.mjs +264 -202
  43. package/dist/mjs/workspace-mount-hold-fence.mjs +95 -0
  44. package/dist/types/command-launcher.d.ts +42 -0
  45. package/dist/types/control-command-policy.d.ts +53 -0
  46. package/dist/types/main.d.ts +31 -19
  47. package/dist/types/project-checkout-garbage.d.ts +19 -2
  48. package/dist/types/project-workspace-state.d.ts +9 -9
  49. package/dist/types/project-worktrees.d.ts +49 -5
  50. package/dist/types/recovery-journal-protocol.d.ts +35 -0
  51. package/dist/types/recovery-journal-runtime.d.ts +12 -0
  52. package/dist/types/recovery-journal-stall-fixture.d.ts +1 -0
  53. package/dist/types/recovery-journal-thread.d.ts +1 -0
  54. package/dist/types/recovery-journal.d.ts +246 -0
  55. package/dist/types/recovery-store.d.ts +6 -0
  56. package/dist/types/session-file-mutations.d.ts +22 -0
  57. package/dist/types/workspace-command-sync-policy.d.ts +22 -7
  58. package/dist/types/workspace-filesystem-executor-thread.d.ts +1 -0
  59. package/dist/types/workspace-filesystem-executor.d.ts +123 -0
  60. package/dist/types/workspace-filesystem-job-types.d.ts +246 -0
  61. package/dist/types/workspace-filesystem-jobs.d.ts +7 -0
  62. package/dist/types/workspace-git-sync.d.ts +113 -7
  63. package/dist/types/workspace-mount-hold-fence.d.ts +42 -0
  64. package/package.json +1 -1
  65. package/dist/cjs/project-snapshot-recovery-runner.cjs +0 -171
  66. package/dist/mjs/project-snapshot-recovery-runner.mjs +0 -135
  67. package/dist/types/project-snapshot-recovery-runner.d.ts +0 -10
@@ -39,6 +39,14 @@ class WorkerRecoveryStore {
39
39
  close() {
40
40
  this.db.close();
41
41
  }
42
+ /**
43
+ * Run several store operations as one durable commit (one FULL fsync).
44
+ * Operations that open their own transaction nest as savepoints. A throw
45
+ * rolls the whole group back; callers treat that as a journal failure.
46
+ */
47
+ batch(operations) {
48
+ return this.db.transaction(operations)();
49
+ }
42
50
  row(requestId) {
43
51
  return this.db.query("SELECT * FROM operations WHERE request_id=? OR request_id=(SELECT operation_id FROM aliases WHERE request_id=?)").get(requestId, requestId);
44
52
  }
@@ -0,0 +1,37 @@
1
+ class SessionFileMutationTracker {
2
+ inFlight = /* @__PURE__ */ new Map();
3
+ /** Register a started mutation; it is forgotten when it settles, however it settles. */
4
+ track(sessionId, mutation) {
5
+ let mutations = this.inFlight.get(sessionId);
6
+ if (!mutations) {
7
+ mutations = /* @__PURE__ */ new Set();
8
+ this.inFlight.set(sessionId, mutations);
9
+ }
10
+ mutations.add(mutation);
11
+ const forget = () => {
12
+ const current = this.inFlight.get(sessionId);
13
+ if (!current) return;
14
+ current.delete(mutation);
15
+ if (current.size === 0) this.inFlight.delete(sessionId);
16
+ };
17
+ mutation.then(forget, forget);
18
+ return mutation;
19
+ }
20
+ count(sessionId) {
21
+ return this.inFlight.get(sessionId)?.size ?? 0;
22
+ }
23
+ /**
24
+ * Resolves once every mutation tracked for the session at the time of the
25
+ * call has settled. Mutations started later are not joined: the session's
26
+ * cancellation marker, recorded before this is awaited, makes their
27
+ * admission recheck refuse them.
28
+ */
29
+ settled(sessionId) {
30
+ const pending = [...this.inFlight.get(sessionId) ?? []];
31
+ if (pending.length === 0) return Promise.resolve();
32
+ return Promise.allSettled(pending).then(() => void 0);
33
+ }
34
+ }
35
+ export {
36
+ SessionFileMutationTracker
37
+ };
@@ -376,6 +376,7 @@ function filesEqual(leftPath, rightPath, entry) {
376
376
  const length = Math.min(leftBuffer.length, entry.size - offset);
377
377
  const leftRead = fs.readSync(left, leftBuffer, 0, length, offset);
378
378
  const rightRead = fs.readSync(right, rightBuffer, 0, length, offset);
379
+ if (leftRead <= 0 || rightRead <= 0) return false;
379
380
  if (leftRead !== rightRead || !leftBuffer.subarray(0, leftRead).equals(rightBuffer.subarray(0, rightRead))) return false;
380
381
  offset += leftRead;
381
382
  }
@@ -1,19 +1,48 @@
1
+ import { WorkspaceMountHoldAbortedError } from "./workspace-mount-hold-fence.mjs";
1
2
  function requiresCurrentSyncBarrier(target) {
2
3
  return target.type === "workspace" && target.rootProfile === "visible_projects";
3
4
  }
4
- async function reserveWorkspaceCommandAfterCurrentSync(target, coordinator, reserve) {
5
- if (!requiresCurrentSyncBarrier(target)) {
6
- reserve();
7
- return;
8
- }
5
+ async function reserveWorkspaceCommandAfterCurrentSync(target, coordinator, reserve, options = {}) {
9
6
  while (true) {
10
- const currentSync = coordinator.afterCurrent();
11
- await currentSync;
12
- if (currentSync !== coordinator.afterCurrent()) continue;
7
+ if (requiresCurrentSyncBarrier(target)) {
8
+ const currentSync = coordinator.afterCurrent();
9
+ await raceWithAbort(currentSync, options.signal);
10
+ if (currentSync !== coordinator.afterCurrent()) continue;
11
+ }
12
+ if (options.signal?.aborted) throw new WorkspaceMountHoldAbortedError(abortReason(options.signal));
13
+ const hold = coordinator.mountHold(target, options.signal);
14
+ if (hold) {
15
+ await hold;
16
+ continue;
17
+ }
13
18
  reserve();
14
19
  return;
15
20
  }
16
21
  }
22
+ function raceWithAbort(waited, signal) {
23
+ if (!signal) return waited;
24
+ if (signal.aborted) return Promise.reject(new WorkspaceMountHoldAbortedError(abortReason(signal)));
25
+ return new Promise((resolve, reject) => {
26
+ const onAbort = () => reject(new WorkspaceMountHoldAbortedError(abortReason(signal)));
27
+ signal.addEventListener("abort", onAbort, { once: true });
28
+ waited.then(
29
+ () => {
30
+ signal.removeEventListener("abort", onAbort);
31
+ resolve();
32
+ },
33
+ (error) => {
34
+ signal.removeEventListener("abort", onAbort);
35
+ reject(error instanceof Error ? error : new Error(String(error)));
36
+ }
37
+ );
38
+ });
39
+ }
40
+ function abortReason(signal) {
41
+ const reason = signal.reason;
42
+ if (reason instanceof Error) return reason.message;
43
+ if (typeof reason === "string" && reason) return reason;
44
+ return "Workspace command reservation was aborted";
45
+ }
17
46
  function shouldSerializeWorkspaceCommand(target) {
18
47
  return target.type === "workspace" && target.rootProfile === "canonical_sync";
19
48
  }
@@ -0,0 +1,38 @@
1
+ import { isMainThread, parentPort } from "node:worker_threads";
2
+ import {
3
+ isWorkspaceFilesystemJobKind,
4
+ serializeWorkspaceFilesystemError
5
+ } from "./workspace-filesystem-job-types.mjs";
6
+ import { workspaceFilesystemJobOperations } from "./workspace-filesystem-jobs.mjs";
7
+ if (isMainThread || !parentPort) {
8
+ throw new Error("The workspace filesystem executor thread must be started by the worker runtime");
9
+ }
10
+ const port = parentPort;
11
+ function runRequest(request) {
12
+ if (!isWorkspaceFilesystemJobKind(request.kind)) {
13
+ return {
14
+ type: "failure",
15
+ id: request.id,
16
+ error: serializeWorkspaceFilesystemError(new Error(`Unknown workspace filesystem job kind: ${String(request.kind)}`))
17
+ };
18
+ }
19
+ const operation = workspaceFilesystemJobOperations[request.kind];
20
+ const previousEnvironment = process.env;
21
+ process.env = { ...request.environment };
22
+ try {
23
+ const result = operation(request.input, {
24
+ progress: (progress) => port.postMessage({ type: "progress", id: request.id, progress })
25
+ });
26
+ return { type: "result", id: request.id, result };
27
+ } catch (error) {
28
+ return { type: "failure", id: request.id, error: serializeWorkspaceFilesystemError(error) };
29
+ } finally {
30
+ process.env = previousEnvironment;
31
+ }
32
+ }
33
+ port.on("message", (message) => {
34
+ if (!message || typeof message !== "object") return;
35
+ const request = message;
36
+ if (request.type !== "run" || typeof request.id !== "number") return;
37
+ port.postMessage(runRequest(request));
38
+ });
@@ -0,0 +1,287 @@
1
+ import path from "node:path";
2
+ import { Worker } from "node:worker_threads";
3
+ import { workerGitProcessEnvironment } from "./git-process-environment.mjs";
4
+ import {
5
+ describeWorkspaceFilesystemJob,
6
+ restoreWorkspaceFilesystemError
7
+ } from "./workspace-filesystem-job-types.mjs";
8
+ const WORKSPACE_FILESYSTEM_EXECUTOR_MAX_QUEUED = 32;
9
+ const WORKSPACE_FILESYSTEM_EXECUTOR_QUEUE_TIMEOUT_MS = 5 * 6e4;
10
+ const WORKSPACE_FILESYSTEM_EXECUTOR_STALL_LOG_INTERVAL_MS = 3e4;
11
+ class WorkspaceFilesystemExecutorError extends Error {
12
+ name = "WorkspaceFilesystemExecutorError";
13
+ }
14
+ class WorkspaceFilesystemExecutorThreadExitedError extends WorkspaceFilesystemExecutorError {
15
+ constructor(exitCode, description, cause) {
16
+ super(
17
+ `Workspace filesystem executor thread exited${exitCode === null ? "" : ` with code ${exitCode}`} while running ${description}; the filesystem state is whatever a process crash would have left`,
18
+ cause === void 0 ? void 0 : { cause }
19
+ );
20
+ this.exitCode = exitCode;
21
+ this.description = description;
22
+ }
23
+ exitCode;
24
+ description;
25
+ }
26
+ class WorkspaceFilesystemExecutor {
27
+ threadModulePath;
28
+ log;
29
+ now;
30
+ maxQueued;
31
+ queueTimeoutMs;
32
+ stallLogIntervalMs;
33
+ worker = null;
34
+ queue = [];
35
+ running = null;
36
+ nextJobId = 1;
37
+ failed = null;
38
+ closed = false;
39
+ /** Invoked once when the executor fails closed (thread exit under a running job). */
40
+ onFailure;
41
+ constructor(options) {
42
+ this.threadModulePath = options.threadModulePath;
43
+ this.log = options.log ?? ((line) => process.stderr.write(`${line}
44
+ `));
45
+ this.now = options.now ?? (() => Date.now());
46
+ this.maxQueued = options.maxQueued ?? WORKSPACE_FILESYSTEM_EXECUTOR_MAX_QUEUED;
47
+ this.queueTimeoutMs = options.queueTimeoutMs ?? WORKSPACE_FILESYSTEM_EXECUTOR_QUEUE_TIMEOUT_MS;
48
+ this.stallLogIntervalMs = options.stallLogIntervalMs ?? WORKSPACE_FILESYSTEM_EXECUTOR_STALL_LOG_INTERVAL_MS;
49
+ }
50
+ /**
51
+ * Run one job to completion on the executor thread. Resolves with the
52
+ * job's result; rejects with the job's own error (properties preserved),
53
+ * with a queue-wait or capacity error when the job never started, or with
54
+ * WorkspaceFilesystemExecutorThreadExitedError when the thread died under it.
55
+ */
56
+ run(kind, input, options = {}) {
57
+ const description = describeWorkspaceFilesystemJob(kind, input);
58
+ if (this.closed)
59
+ return Promise.reject(new WorkspaceFilesystemExecutorError(`Workspace filesystem executor is closed; refusing ${description}`));
60
+ if (this.failed) return Promise.reject(new WorkspaceFilesystemExecutorError(`${this.failed}; refusing ${description}`));
61
+ if (this.queue.length >= this.maxQueued) {
62
+ return Promise.reject(
63
+ new WorkspaceFilesystemExecutorError(
64
+ `Workspace filesystem executor queue is full (${this.queue.length} waiting behind ${this.describeRunning()}); refusing ${description}`
65
+ )
66
+ );
67
+ }
68
+ return new Promise((resolve, reject) => {
69
+ const job = {
70
+ id: this.nextJobId++,
71
+ kind,
72
+ input,
73
+ description,
74
+ onProgress: options.onProgress,
75
+ resolve: (result) => resolve(result),
76
+ reject,
77
+ queuedAtMs: this.now(),
78
+ queueTimer: void 0
79
+ };
80
+ this.queue.push(job);
81
+ if (this.running) {
82
+ job.queueTimer = setTimeout(() => this.expireQueued(job), this.queueTimeoutMs);
83
+ }
84
+ this.dispatch();
85
+ });
86
+ }
87
+ status() {
88
+ const running = this.running;
89
+ return {
90
+ running: running ? {
91
+ kind: running.kind,
92
+ description: running.description,
93
+ startedAtMs: running.startedAtMs,
94
+ ageMs: this.now() - running.startedAtMs
95
+ } : null,
96
+ queued: this.queue.length,
97
+ failed: this.failed
98
+ };
99
+ }
100
+ /**
101
+ * Stop accepting jobs, fail everything still queued and ask the thread to
102
+ * stop. A running job settles when the thread actually exits; a thread
103
+ * blocked in the kernel only exits with the process, which is the point.
104
+ */
105
+ close() {
106
+ if (this.closed) return;
107
+ this.closed = true;
108
+ for (const job of this.queue.splice(0)) {
109
+ if (job.queueTimer) clearTimeout(job.queueTimer);
110
+ job.reject(new WorkspaceFilesystemExecutorError(`Workspace filesystem executor is closed; ${job.description} did not start`));
111
+ }
112
+ const worker = this.worker;
113
+ if (worker && !this.running) {
114
+ this.worker = null;
115
+ void worker.terminate();
116
+ } else if (worker) {
117
+ void worker.terminate();
118
+ }
119
+ }
120
+ describeRunning() {
121
+ const running = this.running;
122
+ if (!running) return "an idle executor";
123
+ return `${running.description} (running for ${Math.round((this.now() - running.startedAtMs) / 1e3)}s)`;
124
+ }
125
+ expireQueued(job) {
126
+ const index = this.queue.indexOf(job);
127
+ if (index < 0) return;
128
+ this.queue.splice(index, 1);
129
+ job.queueTimer = void 0;
130
+ job.reject(
131
+ new WorkspaceFilesystemExecutorError(
132
+ `Workspace filesystem executor is blocked: ${this.describeRunning()} while ${job.description} waited ${Math.round((this.now() - job.queuedAtMs) / 1e3)}s for its turn; filesystem I/O may be stalled`
133
+ )
134
+ );
135
+ }
136
+ dispatch() {
137
+ if (this.running || this.closed || this.failed) return;
138
+ const job = this.queue.shift();
139
+ if (!job) {
140
+ this.worker?.unref();
141
+ return;
142
+ }
143
+ if (job.queueTimer) {
144
+ clearTimeout(job.queueTimer);
145
+ job.queueTimer = void 0;
146
+ }
147
+ let worker;
148
+ try {
149
+ worker = this.ensureWorker();
150
+ } catch (error) {
151
+ job.reject(error instanceof Error ? error : new Error(String(error)));
152
+ this.dispatch();
153
+ return;
154
+ }
155
+ const environment = {};
156
+ for (const [key, value] of Object.entries(workerGitProcessEnvironment(process.env))) if (value !== void 0) environment[key] = value;
157
+ const request = { type: "run", id: job.id, kind: job.kind, input: job.input, environment };
158
+ const startedAtMs = this.now();
159
+ const running = {
160
+ ...job,
161
+ startedAtMs,
162
+ stallTimer: setInterval(() => {
163
+ this.log(
164
+ `[r5d-worker] workspace filesystem job ${running.kind} (${running.description}) has run for ${Math.round((this.now() - startedAtMs) / 1e3)}s; filesystem I/O may be stalled (${this.queue.length} job(s) queued behind it)`
165
+ );
166
+ }, this.stallLogIntervalMs)
167
+ };
168
+ running.stallTimer.unref();
169
+ this.running = running;
170
+ worker.ref();
171
+ try {
172
+ worker.postMessage(request);
173
+ } catch (error) {
174
+ this.settleRunning(running, () => running.reject(error instanceof Error ? error : new Error(String(error))));
175
+ }
176
+ }
177
+ settleRunning(job, settle) {
178
+ if (this.running !== job) return;
179
+ clearInterval(job.stallTimer);
180
+ this.running = null;
181
+ settle();
182
+ this.dispatch();
183
+ }
184
+ ensureWorker() {
185
+ if (this.worker) return this.worker;
186
+ const worker = new Worker(this.threadModulePath);
187
+ this.worker = worker;
188
+ worker.on("message", (message) => this.onReply(worker, message));
189
+ worker.on("error", (error) => {
190
+ this.log(`[r5d-worker] workspace filesystem executor thread error: ${error.stack ?? error.message}`);
191
+ this.lastThreadError = error;
192
+ });
193
+ worker.on("exit", (code) => this.onExit(worker, code));
194
+ worker.unref();
195
+ return worker;
196
+ }
197
+ lastThreadError;
198
+ onReply(worker, message) {
199
+ if (this.worker !== worker) return;
200
+ const running = this.running;
201
+ if (!running || !message || typeof message !== "object" || message.id !== running.id) return;
202
+ if (message.type === "progress") {
203
+ running.onProgress?.(message.progress);
204
+ return;
205
+ }
206
+ if (message.type === "result") {
207
+ this.settleRunning(running, () => running.resolve(message.result));
208
+ return;
209
+ }
210
+ if (message.type === "failure") {
211
+ this.settleRunning(running, () => running.reject(restoreWorkspaceFilesystemError(message.error)));
212
+ }
213
+ }
214
+ onExit(worker, code) {
215
+ if (this.worker !== worker) return;
216
+ this.worker = null;
217
+ const cause = this.lastThreadError;
218
+ this.lastThreadError = void 0;
219
+ const running = this.running;
220
+ if (!running) {
221
+ if (!this.closed) this.dispatch();
222
+ return;
223
+ }
224
+ const failure = new WorkspaceFilesystemExecutorThreadExitedError(code, running.description, cause);
225
+ if (!this.closed) {
226
+ this.failed = `Workspace filesystem executor thread exited with code ${code} while running ${running.description}; the worker must restart and recover before it mutates the workspace again`;
227
+ this.log(`[r5d-worker] ${this.failed}`);
228
+ }
229
+ this.settleRunning(running, () => running.reject(failure));
230
+ for (const job of this.queue.splice(0)) {
231
+ if (job.queueTimer) clearTimeout(job.queueTimer);
232
+ job.reject(
233
+ new WorkspaceFilesystemExecutorError(
234
+ `${this.failed ?? "Workspace filesystem executor is closed"}; ${job.description} did not start`
235
+ )
236
+ );
237
+ }
238
+ if (!this.closed) this.onFailure?.(failure);
239
+ }
240
+ }
241
+ function workspaceFilesystemExecutorThreadModulePath() {
242
+ return path.join(path.dirname(__filename), `workspace-filesystem-executor-thread${path.extname(__filename)}`);
243
+ }
244
+ let processExecutor = null;
245
+ let inlineRunner = null;
246
+ function workspaceFilesystemExecutor() {
247
+ if (inlineRunner) return inlineRunner;
248
+ processExecutor ??= new WorkspaceFilesystemExecutor({ threadModulePath: workspaceFilesystemExecutorThreadModulePath() });
249
+ return processExecutor;
250
+ }
251
+ function installWorkspaceFilesystemExecutorFailureHandler(handler) {
252
+ processExecutor ??= new WorkspaceFilesystemExecutor({ threadModulePath: workspaceFilesystemExecutorThreadModulePath() });
253
+ processExecutor.onFailure = handler;
254
+ }
255
+ const workspaceFilesystemExecutorTestHarness = {
256
+ async runJobsInline(body) {
257
+ const { workspaceFilesystemJobOperations } = await import("./workspace-filesystem-jobs.mjs");
258
+ const previous = inlineRunner;
259
+ inlineRunner = {
260
+ async run(kind, input, options = {}) {
261
+ await Promise.resolve();
262
+ const operation = workspaceFilesystemJobOperations[kind];
263
+ return operation(input, { progress: (progress) => options.onProgress?.(progress) });
264
+ }
265
+ };
266
+ try {
267
+ return await body();
268
+ } finally {
269
+ inlineRunner = previous;
270
+ }
271
+ },
272
+ processExecutor() {
273
+ return processExecutor;
274
+ }
275
+ };
276
+ export {
277
+ WORKSPACE_FILESYSTEM_EXECUTOR_MAX_QUEUED,
278
+ WORKSPACE_FILESYSTEM_EXECUTOR_QUEUE_TIMEOUT_MS,
279
+ WORKSPACE_FILESYSTEM_EXECUTOR_STALL_LOG_INTERVAL_MS,
280
+ WorkspaceFilesystemExecutor,
281
+ WorkspaceFilesystemExecutorError,
282
+ WorkspaceFilesystemExecutorThreadExitedError,
283
+ installWorkspaceFilesystemExecutorFailureHandler,
284
+ workspaceFilesystemExecutor,
285
+ workspaceFilesystemExecutorTestHarness,
286
+ workspaceFilesystemExecutorThreadModulePath
287
+ };
@@ -0,0 +1,106 @@
1
+ const WORKSPACE_FILESYSTEM_JOB_KINDS = [
2
+ "checkout_durability_recovery",
3
+ "hydration_recovery",
4
+ "hydration_transaction",
5
+ "hydration_raw",
6
+ "checkout_transition_begin",
7
+ "checkout_transition_complete",
8
+ "outer_checkout_fsync",
9
+ "projection_merge",
10
+ "projection_mirror",
11
+ "projection_outer_apply",
12
+ "projection_receipt",
13
+ "project_snapshot_create",
14
+ "project_snapshot_apply",
15
+ "project_snapshot_persist",
16
+ "project_snapshot_rollback",
17
+ "project_snapshots_recover",
18
+ "project_branch_create",
19
+ "project_checkout_path_move"
20
+ ];
21
+ function isWorkspaceFilesystemJobKind(value) {
22
+ return typeof value === "string" && WORKSPACE_FILESYSTEM_JOB_KINDS.includes(value);
23
+ }
24
+ function summarizeIds(ids) {
25
+ if (ids.length === 0) return "no mounts";
26
+ const shown = ids.slice(0, 3).join(", ");
27
+ return ids.length > 3 ? `${ids.length} mounts (${shown}, \u2026)` : `${ids.length === 1 ? "mount" : "mounts"} ${shown}`;
28
+ }
29
+ function describeWorkspaceFilesystemJob(kind, input) {
30
+ switch (kind) {
31
+ case "checkout_durability_recovery":
32
+ case "hydration_recovery":
33
+ case "checkout_transition_begin":
34
+ case "checkout_transition_complete":
35
+ case "outer_checkout_fsync":
36
+ return `${kind.replaceAll("_", " ")} of ${input.workspacePath}`;
37
+ case "hydration_transaction": {
38
+ const hydration = input;
39
+ return `hydration of ${summarizeIds(hydration.hydrationMounts.map(({ id }) => id))} (durability ${summarizeIds(hydration.advancedDurabilityMounts.map(({ id }) => id))})`;
40
+ }
41
+ case "hydration_raw":
42
+ return `pre-clone hydration of ${summarizeIds(input.mounts.map(({ id }) => id))}`;
43
+ case "projection_merge":
44
+ return `merge projection of mount ${input.mount.id}`;
45
+ case "projection_mirror":
46
+ return `projection of mount ${input.mount.id}`;
47
+ case "projection_outer_apply": {
48
+ const apply = input;
49
+ return `outer-tree apply (${apply.removeMounts.length} removal(s), ${apply.materialize.length} merged subtree(s), ${apply.restoreFromHead.length} deferred restore(s))`;
50
+ }
51
+ case "projection_receipt":
52
+ return `projection receipt for ${summarizeIds(input.fsyncMounts.map(({ id }) => id))}`;
53
+ case "project_snapshot_create":
54
+ return `checkout snapshot of ${input.projectRoot}`;
55
+ case "project_snapshot_apply":
56
+ return `checkout snapshot restore into ${input.mirrors.map(({ targetPath }) => targetPath).join(", ") || "no checkouts"}`;
57
+ case "project_snapshot_persist":
58
+ return `checkout durability of ${input.snapshot.manifest.projectRoot}`;
59
+ case "project_snapshot_rollback":
60
+ return `checkout snapshot rollback of ${input.snapshot.manifest.projectRoot}`;
61
+ case "project_snapshots_recover":
62
+ return `interrupted checkout snapshot recovery under ${input.temporaryRoot}`;
63
+ case "project_branch_create": {
64
+ const create = input;
65
+ return `branch creation ${create.branchName} from ${create.sourceBranchName} in ${create.projectRoot}`;
66
+ }
67
+ case "project_checkout_path_move": {
68
+ const move = input;
69
+ return `checkout path move ${move.oldProjectRoot} \u2192 ${move.newProjectRoot}`;
70
+ }
71
+ }
72
+ }
73
+ function serializeWorkspaceFilesystemError(error, depth = 0) {
74
+ if (!(error instanceof Error)) return { name: "Error", message: String(error) };
75
+ const record = error;
76
+ const serialized = { name: error.name, message: error.message };
77
+ if (typeof error.stack === "string") serialized.stack = error.stack;
78
+ if (typeof record.code === "string") serialized.code = record.code;
79
+ if (record.branchMayExist === true) serialized.branchMayExist = true;
80
+ if (Array.isArray(record.cleanupFailures) && record.cleanupFailures.every((failure) => typeof failure === "string")) {
81
+ serialized.cleanupFailures = [...record.cleanupFailures];
82
+ }
83
+ if (depth < 4) {
84
+ if (Array.isArray(record.errors)) serialized.errors = record.errors.map((inner) => serializeWorkspaceFilesystemError(inner, depth + 1));
85
+ if (record.cause !== void 0) serialized.cause = serializeWorkspaceFilesystemError(record.cause, depth + 1);
86
+ }
87
+ return serialized;
88
+ }
89
+ function restoreWorkspaceFilesystemError(serialized) {
90
+ const cause = serialized.cause ? restoreWorkspaceFilesystemError(serialized.cause) : void 0;
91
+ const options = cause ? { cause } : void 0;
92
+ const error = serialized.errors ? new AggregateError(serialized.errors.map(restoreWorkspaceFilesystemError), serialized.message, options) : new Error(serialized.message, options);
93
+ error.name = serialized.name;
94
+ if (serialized.stack) error.stack = serialized.stack;
95
+ if (serialized.code !== void 0) error.code = serialized.code;
96
+ if (serialized.branchMayExist) error.branchMayExist = true;
97
+ if (serialized.cleanupFailures) error.cleanupFailures = [...serialized.cleanupFailures];
98
+ return error;
99
+ }
100
+ export {
101
+ WORKSPACE_FILESYSTEM_JOB_KINDS,
102
+ describeWorkspaceFilesystemJob,
103
+ isWorkspaceFilesystemJobKind,
104
+ restoreWorkspaceFilesystemError,
105
+ serializeWorkspaceFilesystemError
106
+ };
@@ -0,0 +1,51 @@
1
+ import {
2
+ createLinkedProjectBranch,
3
+ recoverStaleProjectWorktreeSnapshots,
4
+ runProjectSnapshotApplyJob,
5
+ runProjectSnapshotCreateJob,
6
+ runProjectSnapshotPersistJob,
7
+ runProjectSnapshotRollbackJob
8
+ } from "./project-worktrees.mjs";
9
+ import {
10
+ runCheckoutDurabilityRecoveryJob,
11
+ runCheckoutTransitionBeginJob,
12
+ runCheckoutTransitionCompleteJob,
13
+ runHydrationRawJob,
14
+ runHydrationRecoveryJob,
15
+ runHydrationTransactionJob,
16
+ runOuterCheckoutFsyncJob,
17
+ runProjectionMirrorJob,
18
+ runProjectionOuterApplyJob,
19
+ runProjectionReceiptJob
20
+ } from "./workspace-git-sync.mjs";
21
+ import { mergeWorkspaceProjectionMount } from "./workspace-merge-projection.mjs";
22
+ import { preserveProjectCheckoutPathMove } from "./workspace-path-move.mjs";
23
+ const workspaceFilesystemJobOperations = {
24
+ checkout_durability_recovery: (input) => runCheckoutDurabilityRecoveryJob(input),
25
+ hydration_recovery: (input) => runHydrationRecoveryJob(input),
26
+ hydration_transaction: (input) => runHydrationTransactionJob(input),
27
+ hydration_raw: (input) => runHydrationRawJob(input),
28
+ checkout_transition_begin: (input) => runCheckoutTransitionBeginJob(input),
29
+ checkout_transition_complete: (input) => runCheckoutTransitionCompleteJob(input),
30
+ outer_checkout_fsync: (input) => runOuterCheckoutFsyncJob(input),
31
+ projection_merge: (input) => mergeWorkspaceProjectionMount(input),
32
+ projection_mirror: (input) => runProjectionMirrorJob(input),
33
+ projection_outer_apply: (input) => runProjectionOuterApplyJob(input),
34
+ projection_receipt: (input) => runProjectionReceiptJob(input),
35
+ project_snapshot_create: (input, context) => runProjectSnapshotCreateJob(input, context),
36
+ project_snapshot_apply: (input) => runProjectSnapshotApplyJob(input),
37
+ project_snapshot_persist: (input) => runProjectSnapshotPersistJob(input),
38
+ project_snapshot_rollback: (input) => runProjectSnapshotRollbackJob(input),
39
+ project_snapshots_recover: (input, context) => recoverStaleProjectWorktreeSnapshots({
40
+ projectsRoot: input.projectsRoot,
41
+ temporaryRoot: input.temporaryRoot,
42
+ currentProcessId: input.currentProcessId,
43
+ currentOwnerSessionId: input.currentOwnerSessionId,
44
+ onProgress: context.progress
45
+ }),
46
+ project_branch_create: (input) => createLinkedProjectBranch(input),
47
+ project_checkout_path_move: (input) => preserveProjectCheckoutPathMove(input)
48
+ };
49
+ export {
50
+ workspaceFilesystemJobOperations
51
+ };