@yu_robotics/remote-cli 1.6.189 → 1.6.193

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 (110) hide show
  1. package/README.md +119 -14
  2. package/dist/client/MessageHandler.d.ts.map +1 -1
  3. package/dist/client/MessageHandler.js +2 -1
  4. package/dist/client/MessageHandler.js.map +1 -1
  5. package/dist/commands/delegationStorage.d.ts +15 -0
  6. package/dist/commands/delegationStorage.d.ts.map +1 -0
  7. package/dist/commands/delegationStorage.js +59 -0
  8. package/dist/commands/delegationStorage.js.map +1 -0
  9. package/dist/commands/start.d.ts +2 -0
  10. package/dist/commands/start.d.ts.map +1 -1
  11. package/dist/commands/start.js +42 -18
  12. package/dist/commands/start.js.map +1 -1
  13. package/dist/delegation/DelegatedWorkerSessionStore.d.ts +6 -0
  14. package/dist/delegation/DelegatedWorkerSessionStore.d.ts.map +1 -1
  15. package/dist/delegation/DelegatedWorkerSessionStore.js +25 -2
  16. package/dist/delegation/DelegatedWorkerSessionStore.js.map +1 -1
  17. package/dist/delegation/DelegatedWorkspaceManager.d.ts +119 -2
  18. package/dist/delegation/DelegatedWorkspaceManager.d.ts.map +1 -1
  19. package/dist/delegation/DelegatedWorkspaceManager.js +551 -65
  20. package/dist/delegation/DelegatedWorkspaceManager.js.map +1 -1
  21. package/dist/delegation/DelegationManager.d.ts +20 -0
  22. package/dist/delegation/DelegationManager.d.ts.map +1 -1
  23. package/dist/delegation/DelegationManager.js +267 -41
  24. package/dist/delegation/DelegationManager.js.map +1 -1
  25. package/dist/delegation/DelegationOwnership.d.ts +33 -0
  26. package/dist/delegation/DelegationOwnership.d.ts.map +1 -0
  27. package/dist/delegation/DelegationOwnership.js +397 -0
  28. package/dist/delegation/DelegationOwnership.js.map +1 -0
  29. package/dist/delegation/GitCheckpoint.d.ts.map +1 -1
  30. package/dist/delegation/GitCheckpoint.js +14 -5
  31. package/dist/delegation/GitCheckpoint.js.map +1 -1
  32. package/dist/delegation/LegacyWorkspaceCleanup.d.ts +100 -0
  33. package/dist/delegation/LegacyWorkspaceCleanup.d.ts.map +1 -0
  34. package/dist/delegation/LegacyWorkspaceCleanup.js +864 -0
  35. package/dist/delegation/LegacyWorkspaceCleanup.js.map +1 -0
  36. package/dist/delegation/OwnershipRuntime.d.ts +50 -0
  37. package/dist/delegation/OwnershipRuntime.d.ts.map +1 -0
  38. package/dist/delegation/OwnershipRuntime.js +411 -0
  39. package/dist/delegation/OwnershipRuntime.js.map +1 -0
  40. package/dist/delegation/WorkspaceDisposal.d.ts +23 -0
  41. package/dist/delegation/WorkspaceDisposal.d.ts.map +1 -0
  42. package/dist/delegation/WorkspaceDisposal.js +212 -0
  43. package/dist/delegation/WorkspaceDisposal.js.map +1 -0
  44. package/dist/delegation/contract.d.ts +1 -1
  45. package/dist/delegation/contract.d.ts.map +1 -1
  46. package/dist/delegation/contract.js +2 -1
  47. package/dist/delegation/contract.js.map +1 -1
  48. package/dist/executor/AcpExecutor.d.ts +2 -0
  49. package/dist/executor/AcpExecutor.d.ts.map +1 -1
  50. package/dist/executor/AcpExecutor.js +14 -1
  51. package/dist/executor/AcpExecutor.js.map +1 -1
  52. package/dist/executor/AgyExecutor.d.ts +2 -0
  53. package/dist/executor/AgyExecutor.d.ts.map +1 -1
  54. package/dist/executor/AgyExecutor.js +11 -1
  55. package/dist/executor/AgyExecutor.js.map +1 -1
  56. package/dist/executor/ClaudePersistentExecutor.d.ts +2 -0
  57. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  58. package/dist/executor/ClaudePersistentExecutor.js +13 -3
  59. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  60. package/dist/executor/CodexAppServerClient.d.ts +4 -0
  61. package/dist/executor/CodexAppServerClient.d.ts.map +1 -1
  62. package/dist/executor/CodexAppServerClient.js +15 -3
  63. package/dist/executor/CodexAppServerClient.js.map +1 -1
  64. package/dist/executor/CodexAppServerExecutor.d.ts +2 -0
  65. package/dist/executor/CodexAppServerExecutor.d.ts.map +1 -1
  66. package/dist/executor/CodexAppServerExecutor.js +7 -0
  67. package/dist/executor/CodexAppServerExecutor.js.map +1 -1
  68. package/dist/executor/DshExecutor.d.ts.map +1 -1
  69. package/dist/executor/DshExecutor.js +2 -1
  70. package/dist/executor/DshExecutor.js.map +1 -1
  71. package/dist/executor/IExecutor.d.ts +5 -1
  72. package/dist/executor/IExecutor.d.ts.map +1 -1
  73. package/dist/executor/ManagedProcessGroups.d.ts +30 -0
  74. package/dist/executor/ManagedProcessGroups.d.ts.map +1 -0
  75. package/dist/executor/ManagedProcessGroups.js +144 -0
  76. package/dist/executor/ManagedProcessGroups.js.map +1 -0
  77. package/dist/executor/PiExecutor.d.ts +2 -0
  78. package/dist/executor/PiExecutor.d.ts.map +1 -1
  79. package/dist/executor/PiExecutor.js +15 -0
  80. package/dist/executor/PiExecutor.js.map +1 -1
  81. package/dist/executor/ZCodeExecutor.d.ts.map +1 -1
  82. package/dist/executor/ZCodeExecutor.js +1 -0
  83. package/dist/executor/ZCodeExecutor.js.map +1 -1
  84. package/dist/executor/acp/AcpClient.d.ts +5 -0
  85. package/dist/executor/acp/AcpClient.d.ts.map +1 -1
  86. package/dist/executor/acp/AcpClient.js +20 -9
  87. package/dist/executor/acp/AcpClient.js.map +1 -1
  88. package/dist/executor/dsh/DshAcpClient.d.ts +1 -1
  89. package/dist/executor/dsh/DshAcpClient.d.ts.map +1 -1
  90. package/dist/executor/dsh/DshAcpClient.js +2 -2
  91. package/dist/executor/dsh/DshAcpClient.js.map +1 -1
  92. package/dist/executor/pi/PiClient.d.ts +2 -0
  93. package/dist/executor/pi/PiClient.d.ts.map +1 -1
  94. package/dist/executor/pi/PiClient.js +12 -2
  95. package/dist/executor/pi/PiClient.js.map +1 -1
  96. package/dist/executor/pi/PiTypes.d.ts +1 -0
  97. package/dist/executor/pi/PiTypes.d.ts.map +1 -1
  98. package/dist/executor/pi/PiTypes.js.map +1 -1
  99. package/dist/executor/zcode/ZCodeClient.d.ts +4 -0
  100. package/dist/executor/zcode/ZCodeClient.d.ts.map +1 -1
  101. package/dist/executor/zcode/ZCodeClient.js +13 -2
  102. package/dist/executor/zcode/ZCodeClient.js.map +1 -1
  103. package/dist/index.js +13 -5
  104. package/dist/index.js.map +1 -1
  105. package/dist/maintenance/release-notes.json +1 -1
  106. package/dist/utils/ProcessShutdown.d.ts +25 -0
  107. package/dist/utils/ProcessShutdown.d.ts.map +1 -0
  108. package/dist/utils/ProcessShutdown.js +54 -0
  109. package/dist/utils/ProcessShutdown.js.map +1 -0
  110. package/package.json +5 -4
@@ -0,0 +1,864 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.LegacyWorkspaceCleanup = void 0;
40
+ exports.hasLegacyDiscardTombstone = hasLegacyDiscardTombstone;
41
+ exports.completedLegacyDiscard = completedLegacyDiscard;
42
+ const crypto_1 = require("crypto");
43
+ const child_process_1 = require("child_process");
44
+ const fs_1 = require("fs");
45
+ const promises_1 = __importDefault(require("fs/promises"));
46
+ const path_1 = __importDefault(require("path"));
47
+ const GitCheckpoint_1 = require("./GitCheckpoint");
48
+ const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
49
+ const HASH = /^[a-f0-9]{64}$/;
50
+ const RECORD_LIMIT = 128 * 1024;
51
+ const PLAN_LIMIT = 8 * 1024 * 1024;
52
+ const digest = (value) => (0, crypto_1.createHash)('sha256').update(value).digest('hex');
53
+ const inside = (root, target) => {
54
+ const relative = path_1.default.relative(root, target);
55
+ return relative === '' || (!path_1.default.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path_1.default.sep}`));
56
+ };
57
+ const missing = (error) => error.code === 'ENOENT';
58
+ const errorText = (error) => error instanceof Error ? error.message : 'Unknown inspection failure';
59
+ function metadata(bytes) {
60
+ try {
61
+ return JSON.parse(bytes.toString('utf8'));
62
+ }
63
+ catch {
64
+ throw new Error('Invalid cleanup metadata JSON');
65
+ }
66
+ }
67
+ class Budget {
68
+ limits;
69
+ entries = 0;
70
+ bytes = 0;
71
+ deadline;
72
+ constructor(limits) {
73
+ this.limits = limits;
74
+ this.deadline = Date.now() + limits.seconds * 1000;
75
+ }
76
+ check(entries = 0, bytes = 0) {
77
+ this.entries += entries;
78
+ this.bytes += bytes;
79
+ if (this.entries > this.limits.entries || this.bytes > this.limits.bytes || Date.now() > this.deadline) {
80
+ throw new Error('Inventory budget exhausted; increase explicit scan limits and create a new plan');
81
+ }
82
+ }
83
+ }
84
+ /** Linux mount information includes same-device bind mounts; dev comparisons alone do not. */
85
+ async function localMountPoints() {
86
+ if (process.platform !== 'linux')
87
+ throw new Error('Mount-boundary verification is unavailable on this platform; discard is disabled');
88
+ const data = await boundedRead('/proc/self/mountinfo', 4 * 1024 * 1024, false);
89
+ return data.toString('utf8').trim().split('\n').map(line => {
90
+ const mount = line.split(' ')[4];
91
+ if (!mount?.startsWith('/'))
92
+ throw new Error('Unrecognized mount information');
93
+ return mount.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
94
+ });
95
+ }
96
+ async function canonicalDirectory(directory) {
97
+ const stat = await promises_1.default.lstat(directory);
98
+ if (!stat.isDirectory() || stat.isSymbolicLink() || !Number.isSafeInteger(stat.ino) || stat.ino <= 0
99
+ || await promises_1.default.realpath(directory) !== directory) {
100
+ throw new Error('Noncanonical or symbolic-link directory');
101
+ }
102
+ }
103
+ async function boundedRead(file, limit = RECORD_LIMIT, ordinary = true) {
104
+ const before = await promises_1.default.lstat(file);
105
+ if (!before.isFile() || before.isSymbolicLink() || !Number.isSafeInteger(before.ino) || before.ino <= 0
106
+ || before.size > limit)
107
+ throw new Error('Unsafe or oversized metadata file');
108
+ const handle = await promises_1.default.open(file, fs_1.constants.O_RDONLY | (fs_1.constants.O_NOFOLLOW ?? 0) | (fs_1.constants.O_NONBLOCK ?? 0));
109
+ try {
110
+ const opened = await handle.stat();
111
+ if (!opened.isFile() || before.dev !== opened.dev || before.ino !== opened.ino)
112
+ throw new Error('Metadata identity changed');
113
+ const buffer = Buffer.alloc(limit + 1);
114
+ let size = 0;
115
+ while (size <= limit) {
116
+ const { bytesRead } = await handle.read(buffer, size, buffer.length - size, size);
117
+ if (!bytesRead)
118
+ break;
119
+ size += bytesRead;
120
+ }
121
+ const after = await handle.stat();
122
+ if (size > limit || (ordinary && (opened.size !== size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs))) {
123
+ throw new Error('Metadata changed or exceeded its bound');
124
+ }
125
+ return buffer.subarray(0, size);
126
+ }
127
+ finally {
128
+ await handle.close();
129
+ }
130
+ }
131
+ async function entries(directory, budget) {
132
+ await canonicalDirectory(directory);
133
+ const names = [];
134
+ const handle = await promises_1.default.opendir(directory);
135
+ for await (const entry of handle) {
136
+ budget.check(1);
137
+ names.push(entry.name);
138
+ }
139
+ return names.sort();
140
+ }
141
+ async function durableWrite(file, value, exclusive = false) {
142
+ await canonicalDirectory(path_1.default.dirname(file));
143
+ const bytes = JSON.stringify(value);
144
+ if (Buffer.byteLength(bytes) > PLAN_LIMIT)
145
+ throw new Error('Cleanup metadata is too large');
146
+ const temporary = exclusive ? file : `${file}.${(0, crypto_1.randomUUID)()}.tmp`;
147
+ const handle = await promises_1.default.open(temporary, 'wx', 0o600);
148
+ try {
149
+ await handle.writeFile(bytes);
150
+ await handle.sync();
151
+ }
152
+ finally {
153
+ await handle.close();
154
+ }
155
+ if (!exclusive)
156
+ await promises_1.default.rename(temporary, file);
157
+ // Directory fsync is supported on Unix; Windows rejects directory handles.
158
+ if (process.platform !== 'win32') {
159
+ const parent = await promises_1.default.open(path_1.default.dirname(file), 'r');
160
+ try {
161
+ await parent.sync();
162
+ }
163
+ finally {
164
+ await parent.close();
165
+ }
166
+ }
167
+ }
168
+ /** Admission must treat both pending and completed tombstones as unavailable, never as an exit receipt. */
169
+ async function hasLegacyDiscardTombstone(workerRoot, laneId) {
170
+ if (!UUID.test(laneId))
171
+ throw new Error('Invalid lane ID');
172
+ try {
173
+ await canonicalDirectory(workerRoot);
174
+ const directory = path_1.default.join(workerRoot, 'legacy-discarded');
175
+ await canonicalDirectory(directory);
176
+ await promises_1.default.lstat(path_1.default.join(directory, `${laneId}.json`));
177
+ return true;
178
+ }
179
+ catch (error) {
180
+ if (missing(error))
181
+ return false;
182
+ throw error;
183
+ }
184
+ }
185
+ /** A completed explicit loss retires only the original checkout, never an artifact or native session. */
186
+ async function completedLegacyDiscard(workspaceRoot, laneId, taskId, charge) {
187
+ if (!UUID.test(laneId) || !UUID.test(taskId))
188
+ return undefined;
189
+ try {
190
+ await canonicalDirectory(workspaceRoot);
191
+ await canonicalDirectory(path_1.default.join(workspaceRoot, 'lanes'));
192
+ const workerRoot = path_1.default.join(path_1.default.dirname(workspaceRoot), 'delegation-workers');
193
+ await canonicalDirectory(workerRoot);
194
+ const markers = path_1.default.join(workerRoot, 'legacy-discarded');
195
+ await canonicalDirectory(markers);
196
+ const markerBytes = await boundedRead(path_1.default.join(markers, `${laneId}.json`));
197
+ charge?.(markerBytes.length);
198
+ const marker = metadata(markerBytes);
199
+ const receipt = await boundedRead(path_1.default.join(workspaceRoot, 'lanes', `${laneId}.json`));
200
+ charge?.(receipt.length);
201
+ const workspace = metadata(receipt);
202
+ if (marker.version !== 1 || marker.state !== 'removed' || marker.kind !== undefined || marker.scratchId !== undefined
203
+ || marker.laneId !== laneId || marker.taskId !== taskId || workspace.laneId !== laneId || workspace.taskId !== taskId
204
+ || marker.workspaceFingerprint !== digest(receipt) || !HASH.test(marker.fingerprint) || !HASH.test(marker.planHash)
205
+ || marker.directory !== workspace.directory || marker.sourceRoot !== workspace.source?.root
206
+ || marker.commonDirectory !== workspace.source?.commonDirectory
207
+ || marker.directory !== path_1.default.join(workspaceRoot, 'trees', digest(marker.sourceRoot), laneId)
208
+ || typeof marker.registration !== 'string' || path_1.default.dirname(marker.registration) !== path_1.default.join(marker.commonDirectory, 'worktrees'))
209
+ return undefined;
210
+ await canonicalDirectory(marker.sourceRoot);
211
+ await canonicalDirectory(marker.commonDirectory);
212
+ await canonicalDirectory(path_1.default.dirname(marker.directory));
213
+ try {
214
+ await canonicalDirectory(path_1.default.dirname(marker.registration));
215
+ }
216
+ catch (error) {
217
+ if (!missing(error))
218
+ throw error;
219
+ }
220
+ for (const location of [marker.directory, marker.registration]) {
221
+ try {
222
+ await promises_1.default.lstat(location);
223
+ return undefined;
224
+ }
225
+ catch (error) {
226
+ if (!missing(error))
227
+ throw error;
228
+ }
229
+ }
230
+ return { fingerprint: marker.fingerprint, planHash: marker.planHash };
231
+ }
232
+ catch {
233
+ // Missing, legacy, malformed or inaccessible evidence is not retirement proof.
234
+ return undefined;
235
+ }
236
+ }
237
+ /**
238
+ * Offline-only, explicit loss of checkout contents. Artifacts, refs, and native records are retained.
239
+ * A ready label is not strict reclamation proof. Lane discard never manufactures
240
+ * the reclaiming/reclaimed receipts required for safe native rehydration.
241
+ * Shared ownership fences cooperating CLI writers, not arbitrary OS-user filesystem mutations.
242
+ * Scan deadlines are checked between I/O operations; they do not cancel stalled filesystem reads.
243
+ */
244
+ class LegacyWorkspaceCleanup {
245
+ dependencies;
246
+ root;
247
+ workerRoot;
248
+ workspaceRoot;
249
+ constructor(remoteCliDirectory, dependencies = {}) {
250
+ this.dependencies = dependencies;
251
+ this.root = path_1.default.resolve(remoteCliDirectory);
252
+ this.workerRoot = path_1.default.join(this.root, 'delegation-workers');
253
+ this.workspaceRoot = path_1.default.join(this.root, 'delegation-workspaces');
254
+ }
255
+ async scan(limits = { entries: 100_000, bytes: 1024 ** 3, seconds: 120 }) {
256
+ this.validateLimits(limits);
257
+ const inventory = { version: 1, root: this.root, incomplete: false, limits,
258
+ items: [], excluded: [], artifacts: [], discardedCheckouts: [] };
259
+ const budget = new Budget(limits);
260
+ try {
261
+ await promises_1.default.lstat(this.root);
262
+ }
263
+ catch (error) {
264
+ if (missing(error))
265
+ return inventory;
266
+ throw error;
267
+ }
268
+ try {
269
+ await canonicalDirectory(this.root);
270
+ const mounts = await (this.dependencies.mountPoints ?? localMountPoints)();
271
+ for (const bucket of ['lanes', 'artifacts', 'trees']) {
272
+ const location = path_1.default.join(this.workspaceRoot, bucket);
273
+ try {
274
+ await promises_1.default.lstat(location);
275
+ }
276
+ catch (error) {
277
+ if (missing(error))
278
+ continue;
279
+ throw error;
280
+ }
281
+ await canonicalDirectory(this.workspaceRoot);
282
+ if (bucket === 'lanes') {
283
+ for (const name of await entries(location, budget)) {
284
+ const laneId = name.slice(0, -5);
285
+ if (!name.endsWith('.json') || !UUID.test(laneId))
286
+ continue;
287
+ const data = await boundedRead(path_1.default.join(location, name));
288
+ budget.check(0, data.length);
289
+ const workspace = metadata(data);
290
+ const discarded = await completedLegacyDiscard(this.workspaceRoot, laneId, workspace.taskId, bytes => budget.check(0, bytes));
291
+ budget.check();
292
+ if (discarded)
293
+ inventory.discardedCheckouts.push({ laneId, taskId: workspace.taskId,
294
+ directory: workspace.directory, ...discarded });
295
+ }
296
+ }
297
+ else if (bucket === 'artifacts') {
298
+ for (const name of await entries(location, budget)) {
299
+ budget.check();
300
+ if (!UUID.test(name.slice(0, -5)) || !name.endsWith('.json'))
301
+ throw new Error('Unknown artifact metadata');
302
+ const data = await boundedRead(path_1.default.join(location, name));
303
+ budget.check(0, data.length);
304
+ const artifact = metadata(data);
305
+ if (typeof artifact.threadId !== 'string' || artifact.threadId.length > 200
306
+ || !Number.isSafeInteger(artifact.workspaceGeneration) || !['pending', 'retained', 'applied'].includes(artifact.disposition))
307
+ throw new Error('Invalid artifact summary metadata');
308
+ inventory.artifacts.push({ taskId: name.slice(0, -5), threadId: artifact.threadId,
309
+ workspaceGeneration: artifact.workspaceGeneration, disposition: artifact.disposition });
310
+ }
311
+ }
312
+ else if (bucket === 'trees') {
313
+ for (const hash of await entries(location, budget)) {
314
+ budget.check();
315
+ const group = path_1.default.join(location, hash);
316
+ if (!HASH.test(hash)) {
317
+ inventory.excluded.push({ directory: group, reason: 'Unknown repository bucket' });
318
+ continue;
319
+ }
320
+ try {
321
+ await this.safeBoundary(group, mounts);
322
+ for (const lane of await entries(group, budget)) {
323
+ budget.check();
324
+ const directory = path_1.default.join(group, lane);
325
+ try {
326
+ inventory.items.push(await this.inspect(directory, mounts, budget));
327
+ }
328
+ catch (error) {
329
+ inventory.excluded.push({ directory, reason: errorText(error) });
330
+ if (/budget|EACCES|changed/i.test(errorText(error)))
331
+ inventory.incomplete = true;
332
+ }
333
+ }
334
+ }
335
+ catch (error) {
336
+ inventory.excluded.push({ directory: group, reason: errorText(error) });
337
+ inventory.incomplete = true;
338
+ }
339
+ }
340
+ }
341
+ }
342
+ await this.scanScratch(inventory, mounts, budget);
343
+ }
344
+ catch (error) {
345
+ inventory.incomplete = true;
346
+ inventory.excluded.push({ directory: this.workspaceRoot, reason: errorText(error) });
347
+ }
348
+ return inventory;
349
+ }
350
+ async scanScratch(inventory, mounts, budget) {
351
+ try {
352
+ await promises_1.default.lstat(this.workspaceRoot);
353
+ }
354
+ catch (error) {
355
+ if (missing(error))
356
+ return;
357
+ throw error;
358
+ }
359
+ await this.safeBoundary(this.workspaceRoot, mounts);
360
+ const candidates = new Map();
361
+ for (const name of await entries(this.workspaceRoot, budget)) {
362
+ if (!name.startsWith('integration-'))
363
+ continue;
364
+ const directory = path_1.default.join(this.workspaceRoot, name);
365
+ const id = name.slice('integration-'.length);
366
+ if (!UUID.test(id))
367
+ inventory.excluded.push({ directory, reason: 'Unknown integration scratch directory; retained' });
368
+ else
369
+ candidates.set(id, directory);
370
+ }
371
+ const receipts = path_1.default.join(this.workspaceRoot, 'scratch');
372
+ let present = false;
373
+ try {
374
+ await promises_1.default.lstat(receipts);
375
+ present = true;
376
+ }
377
+ catch (error) {
378
+ if (!missing(error))
379
+ throw error;
380
+ }
381
+ if (present) {
382
+ for (const name of await entries(receipts, budget)) {
383
+ const receipt = path_1.default.join(receipts, name);
384
+ const id = name.slice(0, -5);
385
+ if (!name.endsWith('.json') || !UUID.test(id)) {
386
+ inventory.excluded.push({ directory: receipt, reason: 'Unknown scratch receipt; retained' });
387
+ }
388
+ else if (!candidates.has(id)) {
389
+ // Inspect orphan metadata without interpreting its directory as deletion authority.
390
+ let reason = 'Scratch checkout is absent; receipt retained';
391
+ try {
392
+ const bytes = await boundedRead(receipt);
393
+ budget.check(0, bytes.length);
394
+ const record = metadata(bytes);
395
+ if (record.id !== id || record.directory !== path_1.default.join(this.workspaceRoot, `integration-${id}`)) {
396
+ reason = 'Scratch receipt identity does not match its owned path; retained';
397
+ }
398
+ }
399
+ catch (error) {
400
+ reason = errorText(error);
401
+ if (/budget|EACCES|changed/i.test(reason))
402
+ inventory.incomplete = true;
403
+ }
404
+ inventory.excluded.push({ directory: receipt, reason });
405
+ }
406
+ }
407
+ }
408
+ for (const directory of candidates.values()) {
409
+ try {
410
+ inventory.items.push(await this.inspect(directory, mounts, budget));
411
+ }
412
+ catch (error) {
413
+ inventory.excluded.push({ directory, reason: errorText(error) });
414
+ if (/budget|EACCES|changed/i.test(errorText(error)))
415
+ inventory.incomplete = true;
416
+ }
417
+ }
418
+ }
419
+ async plan(file, limits) {
420
+ const destination = path_1.default.resolve(file);
421
+ this.assertExternal(destination);
422
+ const inventory = await this.scan(limits);
423
+ if (inventory.incomplete)
424
+ throw new Error('Incomplete inventory cannot become an executable plan');
425
+ const plan = { ...inventory, id: (0, crypto_1.randomUUID)(), createdAt: new Date().toISOString() };
426
+ await durableWrite(destination, plan, true);
427
+ return inventory;
428
+ }
429
+ async discard(file, flags) {
430
+ if (flags.discardContents !== true || flags.confirmWorkersStopped !== true) {
431
+ throw new Error('Require --discard-contents and --confirm-workers-stopped; stop the daemon and all native workers manually first');
432
+ }
433
+ const planPath = path_1.default.resolve(file);
434
+ this.assertExternal(planPath);
435
+ await canonicalDirectory(path_1.default.dirname(planPath));
436
+ const bytes = await boundedRead(planPath, PLAN_LIMIT);
437
+ const plan = metadata(bytes);
438
+ if (plan.version !== 1 || plan.root !== this.root || plan.incomplete !== false || !UUID.test(plan.id)
439
+ || !Array.isArray(plan.items) || plan.items.length > 100_000)
440
+ throw new Error('Invalid or incomplete cleanup plan');
441
+ this.validateLimits(plan.limits);
442
+ const planHash = digest(bytes);
443
+ const journalFile = `${planPath}.progress.json`;
444
+ const journal = { version: 1, planHash, items: {} };
445
+ try {
446
+ const previous = metadata(await boundedRead(journalFile, PLAN_LIMIT));
447
+ if (previous.version !== 1 || previous.planHash !== planHash || !previous.items || typeof previous.items !== 'object')
448
+ throw new Error('Cleanup progress does not match the frozen plan');
449
+ journal.items = previous.items;
450
+ }
451
+ catch (error) {
452
+ if (!missing(error))
453
+ throw error;
454
+ }
455
+ await canonicalDirectory(this.root);
456
+ await canonicalDirectory(this.workerRoot);
457
+ await this.assertOffline();
458
+ const ownership = await this.owner();
459
+ await ownership.acquire();
460
+ try {
461
+ await this.assertOffline();
462
+ const result = { removed: 0, errors: [] };
463
+ for (const item of plan.items) {
464
+ try {
465
+ this.validateItem(item);
466
+ const key = this.itemKey(item);
467
+ await ownership.withRepository(item.commonDirectory, async () => {
468
+ await this.assertOffline();
469
+ const mounts = await (this.dependencies.mountPoints ?? localMountPoints)();
470
+ await this.safeBoundary(this.workspaceRoot, mounts);
471
+ if (journal.items[key] === 'removed') {
472
+ await this.verifyIntent(item, planHash);
473
+ await this.confirmRemoved(item);
474
+ result.removed++;
475
+ return;
476
+ }
477
+ let pending = journal.items[key] === 'removing';
478
+ if (!pending && item.kind === 'scratch') {
479
+ let markerExists = false;
480
+ try {
481
+ await promises_1.default.lstat(this.markerPath(item));
482
+ markerExists = true;
483
+ }
484
+ catch (error) {
485
+ if (!missing(error))
486
+ throw error;
487
+ }
488
+ if (markerExists) {
489
+ // Recover a crash between the durable scratch intent and journal.
490
+ const state = await this.verifyIntent(item, planHash);
491
+ if (state === 'removed') {
492
+ await this.confirmRemoved(item);
493
+ journal.items[key] = 'removed';
494
+ await durableWrite(journalFile, journal);
495
+ result.removed++;
496
+ return;
497
+ }
498
+ pending = true;
499
+ }
500
+ }
501
+ let absent = false;
502
+ try {
503
+ await promises_1.default.lstat(item.directory);
504
+ }
505
+ catch (error) {
506
+ if (!missing(error))
507
+ throw error;
508
+ absent = true;
509
+ }
510
+ if (pending) {
511
+ await this.verifyIntent(item, planHash);
512
+ }
513
+ if (pending && absent)
514
+ await this.confirmRemoved(item);
515
+ else {
516
+ const current = await this.inspect(item.directory, mounts, new Budget(plan.limits));
517
+ if (current.fingerprint !== item.fingerprint || current.registration !== item.registration
518
+ || item.taskId !== undefined && (current.taskId !== item.taskId || current.workspaceFingerprint !== item.workspaceFingerprint)
519
+ || current.kind !== item.kind || current.scratchId !== item.scratchId || current.laneId !== item.laneId
520
+ || current.commonDirectory !== item.commonDirectory || current.sourceRoot !== item.sourceRoot)
521
+ throw new Error('Frozen checkout or receipt changed; create a new plan');
522
+ if (!pending) {
523
+ try {
524
+ await promises_1.default.lstat(this.markerPath(item));
525
+ throw new Error('Target has a prior discard intent; manual quiescent recovery is required');
526
+ }
527
+ catch (error) {
528
+ if (!missing(error))
529
+ throw error;
530
+ }
531
+ }
532
+ await promises_1.default.mkdir(path_1.default.dirname(this.markerPath(item)), { recursive: true, mode: 0o700 });
533
+ await this.tombstone(item, planHash, 'pending');
534
+ journal.items[key] = 'removing';
535
+ await durableWrite(journalFile, journal);
536
+ await (this.dependencies.remove ?? (async (source, directory) => { await (0, GitCheckpoint_1.runGit)(source, ['worktree', 'remove', '--force', directory]); }))(item.sourceRoot, item.directory);
537
+ await this.confirmRemoved(item);
538
+ }
539
+ await this.tombstone(item, planHash, 'removed');
540
+ journal.items[key] = 'removed';
541
+ await durableWrite(journalFile, journal);
542
+ result.removed++;
543
+ });
544
+ }
545
+ catch (error) {
546
+ result.errors.push(`${this.itemKey(item)}: ${errorText(error)}`);
547
+ }
548
+ }
549
+ return result;
550
+ }
551
+ finally {
552
+ await ownership.release();
553
+ }
554
+ }
555
+ async owner() {
556
+ if (this.dependencies.ownership)
557
+ return this.dependencies.ownership(this.workerRoot);
558
+ // Shared with daemon admission. No stale-PID takeover or private cleanup lock.
559
+ const modulePath = './DelegationOwnership';
560
+ const { DelegationOwnership } = await Promise.resolve(`${modulePath}`).then(s => __importStar(require(s)));
561
+ return new DelegationOwnership(this.workerRoot);
562
+ }
563
+ async assertOffline() {
564
+ if (this.dependencies.assertOffline)
565
+ return this.dependencies.assertOffline();
566
+ try {
567
+ const config = metadata(await boundedRead(path_1.default.join(this.root, 'config.json')));
568
+ const service = config.service;
569
+ if (service?.running === true)
570
+ throw new Error('Daemon is recorded as running; stop it explicitly before discard');
571
+ if (service?.pid !== undefined) {
572
+ if (!Number.isSafeInteger(service.pid) || service.pid <= 0)
573
+ throw new Error('Unknown daemon PID state');
574
+ try {
575
+ process.kill(service.pid, 0);
576
+ throw new Error('Configured daemon PID still exists');
577
+ }
578
+ catch (error) {
579
+ if (error.code !== 'ESRCH')
580
+ throw error;
581
+ }
582
+ }
583
+ }
584
+ catch (error) {
585
+ if (!missing(error))
586
+ throw error;
587
+ }
588
+ const home = path_1.default.dirname(this.root);
589
+ const unit = path_1.default.join(home, '.config', 'systemd', 'user', 'remote-cli.service');
590
+ if (process.platform === 'linux') {
591
+ let installed = false;
592
+ try {
593
+ await promises_1.default.lstat(unit);
594
+ installed = true;
595
+ }
596
+ catch (error) {
597
+ if (!missing(error))
598
+ throw error;
599
+ }
600
+ if (installed) {
601
+ const status = await new Promise((resolve, reject) => {
602
+ (0, child_process_1.execFile)('systemctl', ['--user', 'show', 'remote-cli.service', '--property=ActiveState,MainPID', '--no-pager'], { timeout: 5000, maxBuffer: 16 * 1024, encoding: 'utf8' }, (error, stdout) => {
603
+ if (error)
604
+ reject(new Error('Cannot verify user service state; stop and verify it manually'));
605
+ else
606
+ resolve(stdout);
607
+ });
608
+ });
609
+ const values = Object.fromEntries(status.trim().split('\n').map(line => line.split('=')));
610
+ if (values.ActiveState !== 'inactive' || values.MainPID !== '0')
611
+ throw new Error('User service is active or uncertain; stop it explicitly before discard');
612
+ }
613
+ }
614
+ // This check is a veto, never evidence of worker exit. The explicit offline
615
+ // attestation and root owner are also mandatory, including for older daemons.
616
+ }
617
+ async safeBoundary(directory, mounts) {
618
+ await canonicalDirectory(directory);
619
+ if (mounts.some(mount => inside(directory, mount)))
620
+ throw new Error('Mounted directory or descendant is excluded');
621
+ }
622
+ validateLimits(limits) {
623
+ if (!limits || !Number.isSafeInteger(limits.entries) || limits.entries < 1 || limits.entries > 1_000_000
624
+ || !Number.isSafeInteger(limits.bytes) || limits.bytes < 1 || limits.bytes > 1024 ** 4
625
+ || !Number.isSafeInteger(limits.seconds) || limits.seconds < 1 || limits.seconds > 3600)
626
+ throw new Error('Invalid inventory limits');
627
+ }
628
+ validateItem(item) {
629
+ if (!item || !UUID.test(item.laneId)
630
+ || (item.taskId !== undefined || item.workspaceFingerprint !== undefined)
631
+ && (!UUID.test(item.taskId ?? '') || !HASH.test(item.workspaceFingerprint ?? ''))
632
+ || typeof item.sourceRoot !== 'string' || !path_1.default.isAbsolute(item.sourceRoot)
633
+ || typeof item.commonDirectory !== 'string' || !path_1.default.isAbsolute(item.commonDirectory)
634
+ || typeof item.registration !== 'string' || !inside(path_1.default.join(item.commonDirectory, 'worktrees'), item.registration)
635
+ || item.registration === path_1.default.join(item.commonDirectory, 'worktrees') || !HASH.test(item.fingerprint)
636
+ || (item.kind !== undefined && item.kind !== 'scratch')
637
+ || (item.kind === 'scratch'
638
+ ? !UUID.test(item.scratchId ?? '') || item.directory !== path_1.default.join(this.workspaceRoot, `integration-${item.scratchId}`)
639
+ : item.scratchId !== undefined || item.directory !== path_1.default.join(this.workspaceRoot, 'trees', digest(item.sourceRoot), item.laneId)))
640
+ throw new Error('Foreign or invalid cleanup target');
641
+ if (inside(item.directory, this.root) || inside(item.directory, item.sourceRoot) || inside(this.workspaceRoot, item.sourceRoot))
642
+ throw new Error('Source repository overlaps managed storage');
643
+ }
644
+ assertExternal(file) {
645
+ if (inside(this.workspaceRoot, file) || inside(this.workerRoot, file))
646
+ throw new Error('Plan and progress must be outside managed workspace and worker storage');
647
+ }
648
+ async inspect(directory, mounts, budget) {
649
+ budget.check();
650
+ const name = path_1.default.basename(directory);
651
+ const scratchId = name.startsWith('integration-') ? name.slice('integration-'.length) : undefined;
652
+ let laneId = name;
653
+ if (!UUID.test(scratchId ?? laneId))
654
+ throw new Error('Unknown lane directory');
655
+ await this.safeBoundary(this.workspaceRoot, mounts);
656
+ await canonicalDirectory(this.workerRoot);
657
+ let receipt;
658
+ let laneBytes;
659
+ let workspace;
660
+ if (scratchId) {
661
+ await canonicalDirectory(path_1.default.join(this.workspaceRoot, 'scratch'));
662
+ receipt = await boundedRead(path_1.default.join(this.workspaceRoot, 'scratch', `${scratchId}.json`));
663
+ workspace = metadata(receipt);
664
+ laneId = workspace.laneId;
665
+ if (workspace.id !== scratchId || !UUID.test(laneId) || !UUID.test(workspace.taskId)
666
+ || workspace.directory !== directory || !Number.isFinite(workspace.updatedAt) || workspace.updatedAt <= 0
667
+ || !['allocating', 'present', 'conflict', 'cleanup-pending'].includes(workspace.state)
668
+ || !workspace.source || ['root', 'cwd', 'commonDirectory', 'relativeCwd'].some(key => typeof workspace.source[key] !== 'string')) {
669
+ throw new Error('Scratch receipt identity or state does not match its checkout; retained');
670
+ }
671
+ await canonicalDirectory(path_1.default.join(this.workspaceRoot, 'artifacts'));
672
+ laneBytes = await boundedRead(path_1.default.join(this.workspaceRoot, 'artifacts', `${workspace.taskId}.json`));
673
+ const artifact = metadata(laneBytes);
674
+ if (artifact.taskId !== workspace.taskId || artifact.laneId !== laneId || !artifact.source
675
+ || ['root', 'cwd', 'commonDirectory', 'relativeCwd'].some(key => artifact.source[key] !== workspace.source[key])) {
676
+ throw new Error('Scratch receipt and historical artifact identity do not match; retained');
677
+ }
678
+ }
679
+ else {
680
+ await canonicalDirectory(path_1.default.join(this.workspaceRoot, 'lanes'));
681
+ receipt = await boundedRead(path_1.default.join(this.workspaceRoot, 'lanes', `${laneId}.json`));
682
+ laneBytes = await boundedRead(path_1.default.join(this.workerRoot, `${laneId}.json`));
683
+ workspace = metadata(receipt);
684
+ const lane = metadata(laneBytes);
685
+ if (workspace.laneId !== laneId || lane.id !== laneId || lane.executorThreadId !== `delegate-lane-${laneId}`
686
+ || !UUID.test(workspace.taskId) || workspace.taskRef !== `refs/remote-cli/tasks/${workspace.taskId}`
687
+ || lane.threadId !== workspace.threadId || lane.workspaceGeneration !== workspace.workspaceGeneration
688
+ || !Number.isSafeInteger(workspace.workspaceGeneration) || workspace.workspaceGeneration < 0
689
+ || lane.workingDirectory !== workspace.source?.cwd || workspace.directory !== directory
690
+ || !['ready', 'dirty', 'preparing', 'running'].includes(lane.state))
691
+ throw new Error('Lane and workspace identity do not match');
692
+ }
693
+ budget.check(0, receipt.length + laneBytes.length);
694
+ const source = workspace.source;
695
+ const item = { ...(scratchId ? { kind: 'scratch', scratchId } : {}), laneId,
696
+ taskId: workspace.taskId, workspaceFingerprint: digest(receipt), directory, sourceRoot: source.root, commonDirectory: source.commonDirectory,
697
+ registration: path_1.default.join(source.commonDirectory, 'worktrees', 'unverified'), fingerprint: '0'.repeat(64), bytes: 0 };
698
+ this.validateItem(item);
699
+ await canonicalDirectory(source.root);
700
+ await canonicalDirectory(source.commonDirectory);
701
+ if (source.cwd !== path_1.default.join(source.root, source.relativeCwd) || !inside(source.root, source.cwd)
702
+ || (!scratchId && workspace.cwd !== path_1.default.join(directory, source.relativeCwd)))
703
+ throw new Error('Working directory identity changed');
704
+ await canonicalDirectory(source.cwd);
705
+ if (await promises_1.default.realpath(await (0, GitCheckpoint_1.gitText)(source.root, ['rev-parse', '--show-toplevel'])) !== source.root
706
+ || await promises_1.default.realpath(path_1.default.resolve(source.root, await (0, GitCheckpoint_1.gitText)(source.root, ['rev-parse', '--git-common-dir']))) !== source.commonDirectory)
707
+ throw new Error('Source registration changed');
708
+ await this.safeBoundary(directory, mounts);
709
+ const gitfile = (await boundedRead(path_1.default.join(directory, '.git'))).toString('utf8').trim();
710
+ if (!gitfile.startsWith('gitdir: '))
711
+ throw new Error('Unknown Git registration');
712
+ const registration = path_1.default.resolve(directory, gitfile.slice(8));
713
+ if (path_1.default.dirname(registration) !== path_1.default.join(source.commonDirectory, 'worktrees'))
714
+ throw new Error('Foreign Git registration');
715
+ await this.safeBoundary(registration, mounts);
716
+ for (const name of ['locked', 'config.worktree']) {
717
+ try {
718
+ await promises_1.default.lstat(path_1.default.join(registration, name));
719
+ throw new Error('Locked or separately configured worktree is excluded');
720
+ }
721
+ catch (error) {
722
+ if (!missing(error))
723
+ throw error;
724
+ }
725
+ }
726
+ const back = await boundedRead(path_1.default.join(registration, 'gitdir'));
727
+ const common = await boundedRead(path_1.default.join(registration, 'commondir'));
728
+ const head = await boundedRead(path_1.default.join(registration, 'HEAD'));
729
+ if (path_1.default.resolve(back.toString('utf8').trim()) !== path_1.default.join(directory, '.git')
730
+ || await promises_1.default.realpath(path_1.default.resolve(registration, common.toString('utf8').trim())) !== source.commonDirectory
731
+ || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(head.toString('utf8').trim()))
732
+ throw new Error('Registration is not an owned detached worktree');
733
+ if (!await this.registered(source.root, directory))
734
+ throw new Error('Worktree registration is missing');
735
+ const hash = (0, crypto_1.createHash)('sha256').update(receipt).update(laneBytes).update(back).update(common).update(head);
736
+ for (const location of [source.root, source.commonDirectory, registration]) {
737
+ const identity = await promises_1.default.lstat(location);
738
+ hash.update(JSON.stringify([location, identity.dev, identity.ino]));
739
+ }
740
+ const artifactDirectory = path_1.default.join(this.workspaceRoot, 'artifacts');
741
+ try {
742
+ await canonicalDirectory(artifactDirectory);
743
+ const artifact = await boundedRead(path_1.default.join(artifactDirectory, `${workspace.taskId}.json`));
744
+ budget.check(0, artifact.length);
745
+ hash.update(artifact);
746
+ }
747
+ catch (error) {
748
+ if (!missing(error))
749
+ throw error;
750
+ hash.update('no-artifact');
751
+ }
752
+ const rootStat = await promises_1.default.lstat(directory);
753
+ const beforeBytes = budget.bytes;
754
+ const walk = async (current, depth, device = rootStat.dev) => {
755
+ if (depth > 128)
756
+ throw new Error('Inventory depth budget exhausted');
757
+ budget.check();
758
+ const before = await promises_1.default.lstat(current);
759
+ if (!Number.isSafeInteger(before.ino) || before.ino <= 0 || before.dev !== device
760
+ || (!before.isFile() && !before.isDirectory() && !before.isSymbolicLink()))
761
+ throw new Error('Uncertain identity, device boundary, or special file is excluded');
762
+ hash.update(JSON.stringify([path_1.default.relative(directory, current), before.dev, before.ino, before.mode, before.size, before.mtimeMs, before.ctimeMs]));
763
+ if (before.isSymbolicLink()) {
764
+ // Git removes the link itself. Never enumerate or read its referent.
765
+ hash.update(await promises_1.default.readlink(current));
766
+ }
767
+ else if (before.isDirectory()) {
768
+ const names = await entries(current, budget);
769
+ if (names.includes('HEAD') && names.includes('objects') && names.includes('refs'))
770
+ throw new Error('Nested bare Git repository is excluded');
771
+ for (const name of names) {
772
+ if (name.toLowerCase() === '.git' && (current !== directory || name !== '.git'))
773
+ throw new Error('Nested Git repository is excluded');
774
+ await walk(path_1.default.join(current, name), depth + 1, device);
775
+ }
776
+ }
777
+ else {
778
+ const handle = await promises_1.default.open(current, fs_1.constants.O_RDONLY | (fs_1.constants.O_NOFOLLOW ?? 0) | (fs_1.constants.O_NONBLOCK ?? 0));
779
+ try {
780
+ const opened = await handle.stat();
781
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino)
782
+ throw new Error('Checkout identity changed');
783
+ const buffer = Buffer.alloc(64 * 1024);
784
+ while (true) {
785
+ budget.check();
786
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
787
+ if (!bytesRead)
788
+ break;
789
+ budget.check(0, bytesRead);
790
+ hash.update(buffer.subarray(0, bytesRead));
791
+ }
792
+ }
793
+ finally {
794
+ await handle.close();
795
+ }
796
+ }
797
+ const after = await promises_1.default.lstat(current);
798
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size
799
+ || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
800
+ throw new Error('Checkout changed during inventory');
801
+ };
802
+ await walk(directory, 0);
803
+ // Conflict stages and merge state can change without changing checkout bytes.
804
+ // Freeze the owned Git administrative files as well as the visible contents.
805
+ await walk(registration, 0, (await promises_1.default.lstat(registration)).dev);
806
+ return { ...item, registration, fingerprint: hash.digest('hex'), bytes: budget.bytes - beforeBytes };
807
+ }
808
+ async registered(source, directory) {
809
+ const output = await (0, GitCheckpoint_1.gitText)(source, ['-c', 'core.quotePath=false', 'worktree', 'list', '--porcelain']);
810
+ return output.split('\n').some(line => {
811
+ if (!line.startsWith('worktree '))
812
+ return false;
813
+ const value = line.slice(9);
814
+ return path_1.default.resolve(value.startsWith('"') ? JSON.parse(value) : value) === directory;
815
+ });
816
+ }
817
+ async confirmRemoved(item) {
818
+ await canonicalDirectory(item.sourceRoot);
819
+ await canonicalDirectory(item.commonDirectory);
820
+ for (const location of [item.directory, item.registration]) {
821
+ try {
822
+ await promises_1.default.lstat(location);
823
+ throw new Error('Removal is incomplete; manual quiescent recovery is required');
824
+ }
825
+ catch (error) {
826
+ if (!missing(error))
827
+ throw error;
828
+ }
829
+ }
830
+ if (await this.registered(item.sourceRoot, item.directory))
831
+ throw new Error('Removal registration remains; manual recovery is required');
832
+ }
833
+ async tombstone(item, planHash, state) {
834
+ await durableWrite(this.markerPath(item), {
835
+ ...(item.kind === 'scratch' ? { kind: 'scratch', scratchId: item.scratchId } : {}),
836
+ version: 1, laneId: item.laneId, directory: item.directory, fingerprint: item.fingerprint, planHash, state,
837
+ taskId: item.taskId, workspaceFingerprint: item.workspaceFingerprint,
838
+ sourceRoot: item.sourceRoot, commonDirectory: item.commonDirectory, registration: item.registration,
839
+ // Never an invented successful task, native-session reset, or process-exit receipt.
840
+ reason: item.kind === 'scratch' ? 'Explicit offline integration scratch discard; originating lane and native context are unchanged'
841
+ : 'Explicit offline checkout discard; native context must not be resumed automatically',
842
+ });
843
+ }
844
+ itemKey(item) {
845
+ return item?.kind === 'scratch' ? `scratch:${item.scratchId}` : item?.laneId ?? 'unknown';
846
+ }
847
+ markerPath(item) {
848
+ return path_1.default.join(this.workerRoot, item.kind === 'scratch' ? 'legacy-discarded-scratch' : 'legacy-discarded', `${item.scratchId ?? item.laneId}.json`);
849
+ }
850
+ async verifyIntent(item, planHash) {
851
+ await canonicalDirectory(path_1.default.dirname(this.markerPath(item)));
852
+ const marker = metadata(await boundedRead(this.markerPath(item)));
853
+ if (marker.planHash !== planHash || marker.fingerprint !== item.fingerprint || marker.laneId !== item.laneId
854
+ || marker.taskId !== item.taskId || marker.workspaceFingerprint !== item.workspaceFingerprint
855
+ || item.taskId !== undefined && (marker.sourceRoot !== item.sourceRoot
856
+ || marker.commonDirectory !== item.commonDirectory || marker.registration !== item.registration)
857
+ || marker.directory !== item.directory || marker.kind !== item.kind || marker.scratchId !== item.scratchId
858
+ || !['pending', 'removed'].includes(marker.state))
859
+ throw new Error('Discard intent changed; manual recovery is required');
860
+ return marker.state;
861
+ }
862
+ }
863
+ exports.LegacyWorkspaceCleanup = LegacyWorkspaceCleanup;
864
+ //# sourceMappingURL=LegacyWorkspaceCleanup.js.map