@leitwerk-dev/pi-session-transfer 0.0.0-bootstrap.0 → 0.2.1
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.
- package/LICENSE +13 -0
- package/README.md +65 -1
- package/dist/LICENSE +13 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +637 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -14
- package/src/client.ts +82 -0
- package/src/importer.ts +208 -0
- package/src/index.ts +196 -0
- package/src/local-state.ts +284 -0
- package/src/workspace-commit.ts +38 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
chmod,
|
|
4
|
+
link as linkFile,
|
|
5
|
+
lstat,
|
|
6
|
+
mkdir,
|
|
7
|
+
readdir,
|
|
8
|
+
readFile,
|
|
9
|
+
rename,
|
|
10
|
+
rm,
|
|
11
|
+
rmdir,
|
|
12
|
+
writeFile,
|
|
13
|
+
} from "node:fs/promises";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { isPathInside, type ParsedTransferLink } from "@leitwerk-dev/session-transfer";
|
|
16
|
+
|
|
17
|
+
const OWNER_MARKER = ".leitwerk-transfer-owner";
|
|
18
|
+
const STALE_IMPORT_MS = 2 * 60 * 60 * 1000;
|
|
19
|
+
|
|
20
|
+
export interface TransferReceipt {
|
|
21
|
+
version: 1;
|
|
22
|
+
origin: string;
|
|
23
|
+
grantId: string;
|
|
24
|
+
tokenHash: string;
|
|
25
|
+
attemptId: string;
|
|
26
|
+
destination: string;
|
|
27
|
+
sessionPath: string;
|
|
28
|
+
completedAt: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface TransferStateRecord {
|
|
32
|
+
version: 1;
|
|
33
|
+
phase: "temporary" | "committing" | "completed";
|
|
34
|
+
origin: string;
|
|
35
|
+
grantId: string;
|
|
36
|
+
tokenHash: string;
|
|
37
|
+
attemptId: string;
|
|
38
|
+
createdAt: string;
|
|
39
|
+
temporaryDirectory: string;
|
|
40
|
+
ownerId: string;
|
|
41
|
+
destination?: string;
|
|
42
|
+
sessionPath?: string;
|
|
43
|
+
completedAt?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function readJson<T>(file: string, fallback: T): Promise<T> {
|
|
47
|
+
try {
|
|
48
|
+
return JSON.parse(await readFile(file, "utf8")) as T;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return fallback;
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function atomicJson(file: string, value: unknown, exclusive = false): Promise<void> {
|
|
56
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
57
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
58
|
+
try {
|
|
59
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
60
|
+
if (exclusive) await linkFile(temporary, file);
|
|
61
|
+
else await rename(temporary, file);
|
|
62
|
+
await chmod(file, 0o600);
|
|
63
|
+
} finally {
|
|
64
|
+
await rm(temporary, { force: true });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function ownsDirectory(directory: string, ownerId: string, marker: string): Promise<boolean> {
|
|
69
|
+
try {
|
|
70
|
+
return (
|
|
71
|
+
(await lstat(directory)).isDirectory() &&
|
|
72
|
+
(await readFile(path.join(directory, marker), "utf8")).trim() === ownerId
|
|
73
|
+
);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function removeOwnedDirectory(
|
|
81
|
+
directory: string,
|
|
82
|
+
ownerId: string,
|
|
83
|
+
marker: string,
|
|
84
|
+
): Promise<void> {
|
|
85
|
+
if (!(await ownsDirectory(directory, ownerId, marker))) return;
|
|
86
|
+
// Keep the ownership proof until all imported children have been removed.
|
|
87
|
+
for (const name of await readdir(directory)) {
|
|
88
|
+
if (name !== marker) await rm(path.join(directory, name), { recursive: true, force: true });
|
|
89
|
+
}
|
|
90
|
+
await rm(path.join(directory, marker));
|
|
91
|
+
await rmdir(directory);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function tokenHash(token: string): string {
|
|
95
|
+
return createHash("sha256").update(token, "utf8").digest("hex");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function stateKey(link: ParsedTransferLink): string {
|
|
99
|
+
return createHash("sha256")
|
|
100
|
+
.update(`${link.origin}\0${link.grantId}\0${tokenHash(link.token)}`)
|
|
101
|
+
.digest("hex");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function completedReceipt(record: TransferStateRecord): TransferReceipt | null {
|
|
105
|
+
if (
|
|
106
|
+
record.phase !== "completed" ||
|
|
107
|
+
!record.destination ||
|
|
108
|
+
!record.sessionPath ||
|
|
109
|
+
!record.completedAt
|
|
110
|
+
) {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
version: 1,
|
|
115
|
+
origin: record.origin,
|
|
116
|
+
grantId: record.grantId,
|
|
117
|
+
tokenHash: record.tokenHash,
|
|
118
|
+
attemptId: record.attemptId,
|
|
119
|
+
destination: record.destination,
|
|
120
|
+
sessionPath: record.sessionPath,
|
|
121
|
+
completedAt: record.completedAt,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export class LocalTransferState {
|
|
126
|
+
private readonly agentRoot: string;
|
|
127
|
+
private readonly recordsRoot: string;
|
|
128
|
+
private stateTail: Promise<void> = Promise.resolve();
|
|
129
|
+
|
|
130
|
+
constructor(agentDir: string) {
|
|
131
|
+
this.agentRoot = path.resolve(agentDir);
|
|
132
|
+
this.recordsRoot = path.join(this.agentRoot, "leitwerk-session-transfer", "transfers");
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private recordFile(link: ParsedTransferLink): string {
|
|
136
|
+
return path.join(this.recordsRoot, `${stateKey(link)}.json`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private async serialized<T>(operation: () => Promise<T>): Promise<T> {
|
|
140
|
+
const previous = this.stateTail;
|
|
141
|
+
let release!: () => void;
|
|
142
|
+
this.stateTail = new Promise<void>((resolve) => {
|
|
143
|
+
release = resolve;
|
|
144
|
+
});
|
|
145
|
+
await previous;
|
|
146
|
+
try {
|
|
147
|
+
return await operation();
|
|
148
|
+
} finally {
|
|
149
|
+
release();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
markerName(ownerId?: string): string {
|
|
154
|
+
return ownerId ? `${OWNER_MARKER}-${ownerId}` : OWNER_MARKER;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async receipt(link: ParsedTransferLink): Promise<TransferReceipt | null> {
|
|
158
|
+
const record = await readJson<TransferStateRecord | null>(this.recordFile(link), null);
|
|
159
|
+
return record ? completedReceipt(record) : null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async begin(
|
|
163
|
+
link: ParsedTransferLink,
|
|
164
|
+
input: { attemptId: string; temporaryDirectory: string; ownerId: string },
|
|
165
|
+
): Promise<void> {
|
|
166
|
+
await this.serialized(async () => {
|
|
167
|
+
try {
|
|
168
|
+
await atomicJson(
|
|
169
|
+
this.recordFile(link),
|
|
170
|
+
{
|
|
171
|
+
version: 1,
|
|
172
|
+
phase: "temporary",
|
|
173
|
+
origin: link.origin,
|
|
174
|
+
grantId: link.grantId,
|
|
175
|
+
tokenHash: tokenHash(link.token),
|
|
176
|
+
attemptId: input.attemptId,
|
|
177
|
+
createdAt: new Date().toISOString(),
|
|
178
|
+
temporaryDirectory: input.temporaryDirectory,
|
|
179
|
+
ownerId: input.ownerId,
|
|
180
|
+
} satisfies TransferStateRecord,
|
|
181
|
+
true,
|
|
182
|
+
);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if ((error as NodeJS.ErrnoException).code === "EEXIST") {
|
|
185
|
+
throw new Error("A previous import for this link still has recovery state", {
|
|
186
|
+
cause: error,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async recordCommitTargets(
|
|
195
|
+
link: ParsedTransferLink,
|
|
196
|
+
targets: Required<Pick<TransferStateRecord, "destination" | "sessionPath">>,
|
|
197
|
+
): Promise<void> {
|
|
198
|
+
await this.serialized(async () => {
|
|
199
|
+
const file = this.recordFile(link);
|
|
200
|
+
const record = await readJson<TransferStateRecord | null>(file, null);
|
|
201
|
+
if (!record || record.phase === "completed") {
|
|
202
|
+
throw new Error("Transfer recovery state is missing or already complete");
|
|
203
|
+
}
|
|
204
|
+
await atomicJson(file, { ...record, ...targets, phase: "committing" });
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async complete(
|
|
209
|
+
link: ParsedTransferLink,
|
|
210
|
+
input: { destination: string; sessionPath: string; completedAt: string },
|
|
211
|
+
): Promise<TransferReceipt> {
|
|
212
|
+
return this.serialized(async () => {
|
|
213
|
+
const file = this.recordFile(link);
|
|
214
|
+
const record = await readJson<TransferStateRecord | null>(file, null);
|
|
215
|
+
if (!record) throw new Error("Transfer recovery state is missing");
|
|
216
|
+
const completed: TransferStateRecord = { ...record, ...input, phase: "completed" };
|
|
217
|
+
await atomicJson(file, completed);
|
|
218
|
+
return completedReceipt(completed) as TransferReceipt;
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async discard(link: ParsedTransferLink): Promise<void> {
|
|
223
|
+
await this.serialized(async () => {
|
|
224
|
+
const file = this.recordFile(link);
|
|
225
|
+
const record = await readJson<TransferStateRecord | null>(file, null);
|
|
226
|
+
if (!record) return;
|
|
227
|
+
if (record.phase === "completed") throw new Error("Completed imports cannot be discarded");
|
|
228
|
+
if (
|
|
229
|
+
record.destination &&
|
|
230
|
+
(await ownsDirectory(record.destination, record.ownerId, this.markerName(record.ownerId)))
|
|
231
|
+
) {
|
|
232
|
+
throw new Error("A reserved import must retain its recovery state");
|
|
233
|
+
}
|
|
234
|
+
await removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);
|
|
235
|
+
await rm(file, { force: true });
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async reconcile(): Promise<void> {
|
|
240
|
+
await this.serialized(async () => {
|
|
241
|
+
let names: string[];
|
|
242
|
+
try {
|
|
243
|
+
names = await readdir(this.recordsRoot);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
for (const name of names.filter((candidate) => candidate.endsWith(".json"))) {
|
|
249
|
+
const file = path.join(this.recordsRoot, name);
|
|
250
|
+
try {
|
|
251
|
+
const record = await readJson<TransferStateRecord | null>(file, null);
|
|
252
|
+
if (!record) continue;
|
|
253
|
+
if (
|
|
254
|
+
record.phase !== "completed" &&
|
|
255
|
+
Date.now() - Date.parse(record.createdAt) <= STALE_IMPORT_MS
|
|
256
|
+
) {
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const destinationMarker = this.markerName(record.ownerId);
|
|
260
|
+
const ownsDestination = record.destination
|
|
261
|
+
? await ownsDirectory(record.destination, record.ownerId, destinationMarker)
|
|
262
|
+
: false;
|
|
263
|
+
if (record.phase === "completed") {
|
|
264
|
+
if (ownsDestination && record.destination) {
|
|
265
|
+
await rm(path.join(record.destination, destinationMarker), { force: true });
|
|
266
|
+
}
|
|
267
|
+
await removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (ownsDestination && record.destination) {
|
|
271
|
+
await removeOwnedDirectory(record.destination, record.ownerId, destinationMarker);
|
|
272
|
+
}
|
|
273
|
+
if (record.sessionPath && isPathInside(this.agentRoot, record.sessionPath)) {
|
|
274
|
+
await rm(record.sessionPath, { force: true });
|
|
275
|
+
}
|
|
276
|
+
await removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);
|
|
277
|
+
await rm(file, { force: true });
|
|
278
|
+
} catch {
|
|
279
|
+
// Keep the record for a later reconciliation attempt.
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { chmod, lstat, mkdir, readdir, rename, rmdir, utimes, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
export async function reserveWorkspaceDestination(
|
|
5
|
+
destination: string,
|
|
6
|
+
marker: { name: string; ownerId: string },
|
|
7
|
+
): Promise<void> {
|
|
8
|
+
// mkdir is the exclusive claim: never replace even an empty existing directory.
|
|
9
|
+
await mkdir(destination, { recursive: false, mode: 0o700 });
|
|
10
|
+
try {
|
|
11
|
+
await writeFile(path.join(destination, marker.name), `${marker.ownerId}\n`, {
|
|
12
|
+
mode: 0o600,
|
|
13
|
+
flag: "wx",
|
|
14
|
+
});
|
|
15
|
+
} catch (error) {
|
|
16
|
+
// An unsuccessful marker write must not recursively remove any intervening data.
|
|
17
|
+
await rmdir(destination).catch(() => undefined);
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function populateWorkspaceDestination(source: string, destination: string) {
|
|
23
|
+
const metadata = await lstat(source);
|
|
24
|
+
// Staging stays writable for moves and recovery; restore the imported mode last.
|
|
25
|
+
await chmod(source, (metadata.mode & 0o7777) | 0o700);
|
|
26
|
+
for (const name of await readdir(source)) {
|
|
27
|
+
await rename(path.join(source, name), path.join(destination, name));
|
|
28
|
+
}
|
|
29
|
+
return metadata;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function restoreWorkspaceMetadata(
|
|
33
|
+
destination: string,
|
|
34
|
+
metadata: { mode: number; atime: Date; mtime: Date },
|
|
35
|
+
): Promise<void> {
|
|
36
|
+
await chmod(destination, metadata.mode & 0o7777);
|
|
37
|
+
await utimes(destination, metadata.atime, metadata.mtime);
|
|
38
|
+
}
|