wherever-dev 0.13.0 → 0.15.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 (45) hide show
  1. package/dist/index.js +514 -33
  2. package/dist/index.js.map +1 -1
  3. package/dist/protocol.d.ts +35 -0
  4. package/dist/protocol.d.ts.map +1 -1
  5. package/dist/protocol.js.map +1 -1
  6. package/dist/remote-candidates.d.ts +52 -0
  7. package/dist/remote-candidates.d.ts.map +1 -0
  8. package/dist/remote-candidates.js +147 -0
  9. package/dist/remote-candidates.js.map +1 -0
  10. package/dist/restore-jobs.d.ts +236 -0
  11. package/dist/restore-jobs.d.ts.map +1 -0
  12. package/dist/restore-jobs.js +716 -0
  13. package/dist/restore-jobs.js.map +1 -0
  14. package/dist/session-pool.d.ts +81 -8
  15. package/dist/session-pool.d.ts.map +1 -1
  16. package/dist/session-pool.js +159 -67
  17. package/dist/session-pool.js.map +1 -1
  18. package/dist/session-types.d.ts +12 -0
  19. package/dist/session-types.d.ts.map +1 -1
  20. package/package.json +1 -1
  21. package/public/_app/immutable/assets/0.BnOlDJL_.css +1 -0
  22. package/public/_app/immutable/chunks/{DdFruy3e.js → Bz1TwIe2.js} +2 -2
  23. package/public/_app/immutable/chunks/{DdFruy3e.js.map → Bz1TwIe2.js.map} +1 -1
  24. package/public/_app/immutable/chunks/{CyQq9q8L.js → C8qcA14p.js} +2 -2
  25. package/public/_app/immutable/chunks/{CyQq9q8L.js.map → C8qcA14p.js.map} +1 -1
  26. package/public/_app/immutable/chunks/{vSWNc7VF.js → txj4ly0C.js} +2 -2
  27. package/public/_app/immutable/chunks/{vSWNc7VF.js.map → txj4ly0C.js.map} +1 -1
  28. package/public/_app/immutable/entry/{app.BzMua2z6.js → app.D1b-njuQ.js} +3 -3
  29. package/public/_app/immutable/entry/{app.BzMua2z6.js.map → app.D1b-njuQ.js.map} +1 -1
  30. package/public/_app/immutable/entry/start.BAywGKzl.js +2 -0
  31. package/public/_app/immutable/entry/start.BAywGKzl.js.map +1 -0
  32. package/public/_app/immutable/nodes/{0.BDXduH3G.js → 0.CKIKfeo9.js} +2 -2
  33. package/public/_app/immutable/nodes/{0.BDXduH3G.js.map → 0.CKIKfeo9.js.map} +1 -1
  34. package/public/_app/immutable/nodes/{1.CqJo-807.js → 1.0v9Av_yb.js} +2 -2
  35. package/public/_app/immutable/nodes/{1.CqJo-807.js.map → 1.0v9Av_yb.js.map} +1 -1
  36. package/public/_app/immutable/nodes/2.FcSNf0tp.js +120 -0
  37. package/public/_app/immutable/nodes/2.FcSNf0tp.js.map +1 -0
  38. package/public/_app/version.json +1 -1
  39. package/public/index.html +11 -11
  40. package/public/service-worker.js +1 -1
  41. package/public/_app/immutable/assets/0.BS_EGmNW.css +0 -1
  42. package/public/_app/immutable/entry/start.B0ap2dTz.js +0 -2
  43. package/public/_app/immutable/entry/start.B0ap2dTz.js.map +0 -1
  44. package/public/_app/immutable/nodes/2.C6-6KHYk.js +0 -110
  45. package/public/_app/immutable/nodes/2.C6-6KHYk.js.map +0 -1
@@ -0,0 +1,716 @@
1
+ // Restore jobs: the server-side engine that materialises a MISSING working
2
+ // folder, either by CLONING a remote or by CREATING an empty folder.
3
+ //
4
+ // A session's transcript and the folder it refers to travel separately, so a
5
+ // synced transcript routinely names a clone that does not exist on this machine.
6
+ // Curing that is a RESTORE, and a restore runs as a JOB owned by this server and
7
+ // keyed by the resolved absolute TARGET PATH, never by the requesting socket,
8
+ // client or session (`docs/adr/0009`). Path-keying is what buys the three
9
+ // properties that make the feature usable at all on a phone: the clone SURVIVES
10
+ // a dropped socket or a locked screen, a reconnecting or second device
11
+ // re-attaches to the RUNNING job, and a second request for the same folder
12
+ // COALESCES instead of racing a competing clone into the same directory.
13
+ //
14
+ // This module is deliberately standalone: it knows nothing about WebSockets,
15
+ // sessions or the session pool. It has two independent consumers coming (a
16
+ // progress/completion broadcast to matching clients, and a per-folder existence
17
+ // cache invalidation), so it OWNS the observation seam rather than letting
18
+ // either consumer reach into its internals or be wired through the other.
19
+ //
20
+ // Transport is SSH ONLY (`docs/adr/0010`). There is no HTTPS fallback, no token
21
+ // and no credential setup: the box is assumed provisioned. That is exactly why
22
+ // `mapCloneFailure` below is a DELIVERABLE and not polish, and why the clone
23
+ // runs with every interactive prompt disabled: on an unprovisioned box the only
24
+ // remedy this feature can offer is NAMING precisely which one-line fix is
25
+ // missing, and it can only do that if git fails FAST instead of hanging
26
+ // invisibly at zero percent behind a prompt nobody can see.
27
+ import fs from 'node:fs';
28
+ import os from 'node:os';
29
+ import path from 'node:path';
30
+ import { spawn as nodeSpawn, execFileSync } from 'node:child_process';
31
+ /**
32
+ * The scope of the top-level repository. Submodules report under their own path
33
+ * (relative to the target) instead, because folding them into one number would
34
+ * be a fake global percentage: git restarts counting per submodule and nothing
35
+ * knows how many objects the remaining ones hold.
36
+ */
37
+ export const REPOSITORY_SCOPE = 'repository';
38
+ const DEFAULT_RETAIN_MS = 60_000;
39
+ /** ~5 frames per second: enough to look alive, far below git's frame rate. */
40
+ const DEFAULT_PROGRESS_INTERVAL_MS = 200;
41
+ /** Cap on retained stderr. Git failure output is short; a runaway remote is not. */
42
+ const MAX_STDERR_CHARS = 16_000;
43
+ /** Grace before SIGKILL when a cancelled child ignores SIGTERM. */
44
+ const KILL_GRACE_MS = 2_000;
45
+ // ---------------------------------------------------------------------------
46
+ // Safety
47
+ // ---------------------------------------------------------------------------
48
+ /**
49
+ * True iff `p` resolves to the home directory or somewhere beneath it.
50
+ *
51
+ * This mirrors `isWithinHome()` in `index.ts` (the HTTP layer's guard on
52
+ * /check-path and /autocomplete-path) rather than importing it, because
53
+ * `index.ts` is the CLI entry point and DISPATCHES on import: importing it from
54
+ * a library module would run the server. The later wiring task should collapse
55
+ * the two onto this one, since this module is the importable side.
56
+ *
57
+ * `os.homedir()` is read on every call, not captured at module load, so the home
58
+ * a test points `HOME` at is the home the guard enforces.
59
+ */
60
+ export function isWithinHome(p) {
61
+ const home = path.resolve(os.homedir());
62
+ const normalized = path.resolve(p);
63
+ return normalized === home || normalized.startsWith(home + path.sep);
64
+ }
65
+ /**
66
+ * Shape allowlist for a clone URL. SSH only (ADR 0010), plus `file://` so tests
67
+ * and fixtures need no network, no key and no provider CLI.
68
+ *
69
+ * This is an ALLOWLIST rather than a metacharacter denylist on purpose: the
70
+ * command-injection fix in the remote-repo provisioning path already forced every
71
+ * git/provider call onto an argv array with no shell, and this is the second
72
+ * layer. A denylist would be the thing that has to be exhaustive; an allowlist
73
+ * only has to be right about what git URLs look like. It also excludes git's own
74
+ * dangerous transports (`ext::`, `--upload-pack=`), which no argv array protects
75
+ * against.
76
+ */
77
+ const SCP_SSH_URL = /^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+:[A-Za-z0-9._~/-]+$/;
78
+ const SSH_URL = /^ssh:\/\/(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9.-]+(?::\d{1,5})?\/[A-Za-z0-9._~/-]+$/;
79
+ const FILE_URL = /^file:\/\/\/[A-Za-z0-9._~/+-]+$/;
80
+ export function isAllowedCloneUrl(url) {
81
+ if (!url || url.length > 2048)
82
+ return false;
83
+ // Control characters and newlines never appear in a real URL, and a leading
84
+ // dash would let the URL be read as an option however it is passed.
85
+ if (/[\u0000-\u001f\u007f]/.test(url))
86
+ return false;
87
+ if (url.startsWith('-'))
88
+ return false;
89
+ return SCP_SSH_URL.test(url) || SSH_URL.test(url) || FILE_URL.test(url);
90
+ }
91
+ // ---------------------------------------------------------------------------
92
+ // The git invocation
93
+ // ---------------------------------------------------------------------------
94
+ /**
95
+ * The clone argv. An ARRAY, never a shell string, and `--` before the operands
96
+ * so neither the URL nor the path can be read as an option.
97
+ *
98
+ * It carries NO `-c protocol.file.allow=...`: file-transport submodules are
99
+ * blocked by git since 2.38 (CVE-2022-39253) and that protection must never be
100
+ * relaxed for a real clone. The test fixtures need the relaxation, and they get
101
+ * it from their own process ENVIRONMENT (`GIT_CONFIG_COUNT` / `GIT_CONFIG_KEY_0`),
102
+ * which is why it must not live here.
103
+ */
104
+ export function buildCloneArgs(url, targetPath) {
105
+ return ['clone', '--progress', '--recurse-submodules', '--', url, targetPath];
106
+ }
107
+ /**
108
+ * The clone environment: every interactive prompt disabled, so a box missing a
109
+ * key, a known-hosts entry or a network route FAILS instead of hanging at zero
110
+ * percent behind an invisible prompt (ADR 0010). `ConnectTimeout` bounds the one
111
+ * case batch mode cannot: a host that accepts the TCP connection and then says
112
+ * nothing.
113
+ *
114
+ * The surrounding environment is INHERITED (a user's ssh config, agent socket
115
+ * and `GIT_SSH_COMMAND` are all legitimate and load-bearing on a real box); only
116
+ * the interactive levers are overridden.
117
+ */
118
+ export function buildCloneEnv(base = process.env) {
119
+ const env = { ...base };
120
+ env.GIT_TERMINAL_PROMPT = '0';
121
+ delete env.GIT_ASKPASS;
122
+ delete env.SSH_ASKPASS;
123
+ // ssh only reaches for a GUI askpass when it has a DISPLAY to draw on.
124
+ delete env.DISPLAY;
125
+ env.SSH_ASKPASS_REQUIRE = 'never';
126
+ const batch = '-o BatchMode=yes -o ConnectTimeout=10';
127
+ env.GIT_SSH_COMMAND = base.GIT_SSH_COMMAND ? `${base.GIT_SSH_COMMAND} ${batch}` : `ssh ${batch}`;
128
+ return env;
129
+ }
130
+ /**
131
+ * Map git's well-known failure signatures onto a named, actionable cause while
132
+ * keeping the raw stderr underneath.
133
+ *
134
+ * On an SSH-only, no-credential-setup design this IS the remedy: the product's
135
+ * job is to say precisely which one-line fix the box needs, not to perform it.
136
+ * An unrecognised failure is passed through verbatim rather than reworded, since
137
+ * a wrong guess costs more than raw git output.
138
+ */
139
+ export function mapCloneFailure(stderr, url) {
140
+ const host = extractHost(url) ?? 'the host';
141
+ const text = stderr || '';
142
+ if (/Host key verification failed|authenticity of host|No .* host key is known|known_hosts/i.test(text)) {
143
+ return {
144
+ cause: 'unknown-host',
145
+ message: `${host} is not in this machine's known_hosts, so SSH refused to connect. Connect once by hand on the server (ssh -T git@${host}) to record its host key, then retry.`,
146
+ stderr,
147
+ };
148
+ }
149
+ // Note what is NOT matched here: git's trailer "Please make sure you have the
150
+ // correct access rights and the repository exists" is printed for a missing
151
+ // key AND for a missing repository, so keying on it would report every
152
+ // wrong-URL clone as a credentials problem. The signature that really means
153
+ // "no key this host accepts" is ssh's own permission-denied line.
154
+ if (/Permission denied \(publickey|Permission denied, please try again|no matching host key|sign_and_send_pubkey/i.test(text)) {
155
+ return {
156
+ cause: 'no-key',
157
+ message: `No SSH key on this machine is accepted by ${host}. Add this machine's public key to your ${host} account, or load the right key into its ssh-agent. Wherever never sets credentials up for you.`,
158
+ stderr,
159
+ };
160
+ }
161
+ if (/Repository not found|remote: Not Found|does not appear to be a git repository|repository '[^']*' (?:does not exist|not found)|The requested repository does not exist/i.test(text)) {
162
+ return {
163
+ cause: 'not-found',
164
+ message: `Repository not found: ${url}. Either the URL is wrong, or this machine's key has no access to it. From here the two are indistinguishable, so check both.`,
165
+ stderr,
166
+ };
167
+ }
168
+ if (/Could not resolve hostname|Connection timed out|Network is unreachable|Connection refused|Temporary failure in name resolution|Operation timed out|No route to host/i.test(text)) {
169
+ return {
170
+ cause: 'network',
171
+ message: `Could not reach ${host}. This is a network problem, not a credentials one: check connectivity on the server and retry.`,
172
+ stderr,
173
+ };
174
+ }
175
+ return { cause: 'unknown', message: lastMeaningfulLine(text) || 'git clone failed', stderr };
176
+ }
177
+ /** The host part of an SSH URL, for naming it in a failure message. */
178
+ export function extractHost(url) {
179
+ if (url.startsWith('file://'))
180
+ return undefined;
181
+ if (url.startsWith('ssh://')) {
182
+ try {
183
+ return new URL(url).hostname || undefined;
184
+ }
185
+ catch {
186
+ return undefined;
187
+ }
188
+ }
189
+ const scp = /^(?:[^@\s]+@)?([^@:\s/]+):/.exec(url);
190
+ return scp?.[1];
191
+ }
192
+ function lastMeaningfulLine(text) {
193
+ const lines = text
194
+ .split(/\r?\n/)
195
+ .map((l) => l.trim())
196
+ .filter(Boolean);
197
+ return lines.length ? lines[lines.length - 1] : '';
198
+ }
199
+ // ---------------------------------------------------------------------------
200
+ // Progress parsing
201
+ // ---------------------------------------------------------------------------
202
+ const PHASE_PATTERNS = [
203
+ [/^Enumerating objects:/, 'enumerating'],
204
+ [/^Counting objects:/, 'counting'],
205
+ [/^Compressing objects:/, 'compressing'],
206
+ [/^Receiving objects:/, 'receiving'],
207
+ [/^Resolving deltas:/, 'resolving'],
208
+ [/^(?:Updating files|Checking out files):/, 'checking-out'],
209
+ [/^Filtering content:/, 'filtering'],
210
+ ];
211
+ /**
212
+ * Turns raw `git clone --progress` output into progress frames.
213
+ *
214
+ * The load-bearing detail: git REWRITES one line in place, emitting frames
215
+ * separated by CARRIAGE RETURNS inside a single newline-terminated chunk. A
216
+ * newline-only parser therefore sees almost nothing during the receiving phase,
217
+ * which is exactly the phase a long clone spends its time in. So `\r` is a frame
218
+ * separator here, on equal footing with `\n`.
219
+ *
220
+ * The parser is also what keeps submodules honestly scoped: git announces each
221
+ * one with its own `Cloning into '<abs path>'...`, so the scope switches to that
222
+ * submodule's path and its percentages are never mixed into the parent's.
223
+ */
224
+ export class GitProgressParser {
225
+ buffer = '';
226
+ scope = REPOSITORY_SCOPE;
227
+ target;
228
+ constructor(targetPath) {
229
+ this.target = path.resolve(targetPath);
230
+ }
231
+ /**
232
+ * Feed a chunk; get back the frames it completed. A trailing partial frame is
233
+ * BUFFERED rather than reported, so a half-read line can never be published as
234
+ * a wrong percentage.
235
+ */
236
+ push(chunk) {
237
+ this.buffer += chunk;
238
+ const parts = this.buffer.split(/\r\n|[\r\n]/);
239
+ this.buffer = parts.pop() ?? '';
240
+ const out = [];
241
+ for (const part of parts) {
242
+ const frame = this.parseLine(part);
243
+ if (frame)
244
+ out.push(frame);
245
+ }
246
+ return out;
247
+ }
248
+ parseLine(raw) {
249
+ const line = raw.replace(/^remote:\s*/, '').trim();
250
+ if (!line)
251
+ return null;
252
+ const cloningInto = /^Cloning into '(.+)'\.\.\.$/.exec(line);
253
+ if (cloningInto) {
254
+ this.scope = this.scopeFor(cloningInto[1]);
255
+ return this.frame('starting', null, line);
256
+ }
257
+ for (const [pattern, phase] of PHASE_PATTERNS) {
258
+ if (!pattern.test(line))
259
+ continue;
260
+ const pct = /(\d{1,3})%/.exec(line);
261
+ const percent = pct ? Math.min(100, parseInt(pct[1], 10)) : null;
262
+ return this.frame(phase, percent, line);
263
+ }
264
+ return null;
265
+ }
266
+ scopeFor(clonePath) {
267
+ const resolved = path.resolve(clonePath);
268
+ if (resolved === this.target)
269
+ return REPOSITORY_SCOPE;
270
+ const relative = path.relative(this.target, resolved);
271
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
272
+ return path.basename(resolved);
273
+ }
274
+ return relative;
275
+ }
276
+ frame(phase, percent, text) {
277
+ return { phase, scope: this.scope, percent, indeterminate: percent === null, text, at: Date.now() };
278
+ }
279
+ }
280
+ /**
281
+ * The path-keyed registry. One job per target path at a time; a second request
282
+ * for a running path coalesces onto it.
283
+ */
284
+ export class RestoreJobRegistry {
285
+ jobs = new Map();
286
+ observers = new Map();
287
+ retainMs;
288
+ progressIntervalMs;
289
+ spawnFn;
290
+ nextId = 1;
291
+ constructor(options = {}) {
292
+ this.retainMs = options.retainMs ?? DEFAULT_RETAIN_MS;
293
+ this.progressIntervalMs = options.progressIntervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS;
294
+ this.spawnFn = options.spawn ?? ((cmd, args, opts) => nodeSpawn(cmd, args, opts));
295
+ }
296
+ /**
297
+ * Start a restore job for a path, or JOIN the one already running there.
298
+ *
299
+ * Every refusal happens here, before anything is spawned or created, so an
300
+ * unsafe request never has a partial effect.
301
+ */
302
+ request(request) {
303
+ const raw = request.targetPath;
304
+ if (typeof raw !== 'string' || !raw.trim()) {
305
+ return { ok: false, reason: 'invalid-target', message: 'A target path is required.' };
306
+ }
307
+ const targetPath = path.resolve(expandTilde(raw.trim()));
308
+ if (!isWithinHome(targetPath)) {
309
+ return {
310
+ ok: false,
311
+ reason: 'outside-home',
312
+ message: `Refusing to restore ${targetPath}: a restore target must be inside the home directory.`,
313
+ };
314
+ }
315
+ const existing = this.jobs.get(targetPath);
316
+ if (existing && existing.state === 'running') {
317
+ return { ok: true, outcome: 'joined', job: snapshot(existing) };
318
+ }
319
+ if (request.kind === 'clone' && !isAllowedCloneUrl(request.url)) {
320
+ return {
321
+ ok: false,
322
+ reason: 'invalid-url',
323
+ message: `Refusing to clone ${JSON.stringify(request.url)}: not a recognised SSH repository URL (git@host:owner/repo.git or ssh://host/path).`,
324
+ };
325
+ }
326
+ let targetExists = false;
327
+ try {
328
+ const stat = fs.statSync(targetPath);
329
+ if (!stat.isDirectory()) {
330
+ return { ok: false, reason: 'target-not-empty', message: `${targetPath} exists and is not a directory.` };
331
+ }
332
+ if (fs.readdirSync(targetPath).length > 0) {
333
+ return { ok: false, reason: 'target-not-empty', message: `${targetPath} already exists and is not empty.` };
334
+ }
335
+ targetExists = true;
336
+ }
337
+ catch (err) {
338
+ if (err?.code !== 'ENOENT') {
339
+ return { ok: false, reason: 'invalid-target', message: `Cannot inspect ${targetPath}: ${err?.message || err}` };
340
+ }
341
+ }
342
+ const job = this.createJob(request, targetPath, !targetExists);
343
+ this.jobs.set(targetPath, job);
344
+ if (request.kind === 'clone')
345
+ this.runClone(job);
346
+ else
347
+ this.runCreate(job);
348
+ return { ok: true, outcome: 'started', job: snapshot(job) };
349
+ }
350
+ /** The job at `targetPath`, running or briefly-retained terminal, if any. */
351
+ get(targetPath) {
352
+ const job = this.jobs.get(path.resolve(expandTilde(targetPath)));
353
+ return job ? snapshot(job) : undefined;
354
+ }
355
+ list() {
356
+ return [...this.jobs.values()].map(snapshot);
357
+ }
358
+ /**
359
+ * Observe a path: progress frames plus the terminal outcome.
360
+ *
361
+ * Subscription is keyed by PATH and independent of any particular job, so a
362
+ * consumer may attach before a job starts and stays attached across a retry.
363
+ * Returns the unsubscribe function.
364
+ */
365
+ subscribe(targetPath, observer) {
366
+ const key = path.resolve(expandTilde(targetPath));
367
+ let set = this.observers.get(key);
368
+ if (!set) {
369
+ set = new Set();
370
+ this.observers.set(key, set);
371
+ }
372
+ set.add(observer);
373
+ return () => {
374
+ const current = this.observers.get(key);
375
+ if (!current)
376
+ return;
377
+ current.delete(observer);
378
+ if (current.size === 0)
379
+ this.observers.delete(key);
380
+ };
381
+ }
382
+ /** Resolves with the terminal snapshot of the job at `targetPath`. */
383
+ settled(targetPath) {
384
+ const key = path.resolve(expandTilde(targetPath));
385
+ const job = this.jobs.get(key);
386
+ if (!job)
387
+ return Promise.reject(new Error(`No restore job for ${key}`));
388
+ return job.settled;
389
+ }
390
+ /**
391
+ * Cancel the job at `targetPath`. Returns false when there is nothing running.
392
+ *
393
+ * Cancellation is AUTHORITATIVE: the job settles as `cancelled` even if the
394
+ * child happened to finish in the same breath, because the user asked for the
395
+ * folder not to be there. A directory this job CREATED is removed; one that
396
+ * already existed is never touched.
397
+ */
398
+ cancel(targetPath) {
399
+ const key = path.resolve(expandTilde(targetPath));
400
+ const job = this.jobs.get(key);
401
+ if (!job || job.state !== 'running')
402
+ return false;
403
+ job.cancelRequested = true;
404
+ const child = job.child;
405
+ if (child && child.exitCode === null && child.signalCode === null) {
406
+ try {
407
+ child.kill('SIGTERM');
408
+ }
409
+ catch { }
410
+ job.killTimer = setTimeout(() => {
411
+ try {
412
+ child.kill('SIGKILL');
413
+ }
414
+ catch { }
415
+ }, KILL_GRACE_MS);
416
+ job.killTimer.unref?.();
417
+ }
418
+ else if (!child) {
419
+ // Nothing spawned yet (the create kind, or a clone still in its first
420
+ // tick): settle here, the runner checks `cancelRequested` before acting.
421
+ this.finish(job, 'cancelled');
422
+ }
423
+ return true;
424
+ }
425
+ /** Drop every timer and kill anything running. For shutdown and for tests. */
426
+ dispose() {
427
+ for (const job of this.jobs.values()) {
428
+ if (job.reapTimer)
429
+ clearTimeout(job.reapTimer);
430
+ if (job.killTimer)
431
+ clearTimeout(job.killTimer);
432
+ if (job.state === 'running' && job.child) {
433
+ try {
434
+ job.child.kill('SIGKILL');
435
+ }
436
+ catch { }
437
+ }
438
+ }
439
+ this.jobs.clear();
440
+ this.observers.clear();
441
+ }
442
+ // -- internals ----------------------------------------------------------
443
+ createJob(request, targetPath, createdTarget) {
444
+ let resolveSettled;
445
+ const settled = new Promise((resolve) => {
446
+ resolveSettled = resolve;
447
+ });
448
+ return {
449
+ id: this.nextId++,
450
+ kind: request.kind,
451
+ targetPath,
452
+ url: request.kind === 'clone' ? request.url : undefined,
453
+ gitInit: request.kind === 'create' ? request.gitInit === true : undefined,
454
+ state: 'running',
455
+ progress: null,
456
+ startedAt: Date.now(),
457
+ createdTarget,
458
+ cancelRequested: false,
459
+ stderr: '',
460
+ lastEmitAt: 0,
461
+ settled,
462
+ resolveSettled,
463
+ };
464
+ }
465
+ runClone(job) {
466
+ const parser = new GitProgressParser(job.targetPath);
467
+ let child;
468
+ try {
469
+ fs.mkdirSync(path.dirname(job.targetPath), { recursive: true });
470
+ child = this.spawnFn('git', buildCloneArgs(job.url, job.targetPath), {
471
+ cwd: path.dirname(job.targetPath),
472
+ stdio: ['ignore', 'ignore', 'pipe'],
473
+ env: buildCloneEnv(process.env),
474
+ });
475
+ }
476
+ catch (err) {
477
+ job.failure = mapCloneFailure(String(err?.message || err), job.url);
478
+ this.finish(job, 'failed');
479
+ return;
480
+ }
481
+ job.child = child;
482
+ if (job.cancelRequested) {
483
+ try {
484
+ child.kill('SIGTERM');
485
+ }
486
+ catch { }
487
+ }
488
+ child.stderr?.setEncoding('utf8');
489
+ child.stderr?.on('data', (chunk) => {
490
+ if (job.stderr.length < MAX_STDERR_CHARS)
491
+ job.stderr += chunk;
492
+ for (const frame of parser.push(chunk))
493
+ this.record(job, frame);
494
+ });
495
+ child.on('error', (err) => {
496
+ job.failure = mapCloneFailure(job.stderr || err.message, job.url);
497
+ this.finish(job, 'failed');
498
+ });
499
+ child.on('close', (code) => {
500
+ if (job.state !== 'running')
501
+ return;
502
+ if (job.cancelRequested) {
503
+ this.cleanupCancelled(job);
504
+ this.finish(job, 'cancelled');
505
+ return;
506
+ }
507
+ if (code === 0) {
508
+ setupUpstreamTracking(job.targetPath);
509
+ this.finish(job, 'done');
510
+ return;
511
+ }
512
+ job.failure = mapCloneFailure(job.stderr, job.url);
513
+ this.finish(job, 'failed');
514
+ });
515
+ }
516
+ runCreate(job) {
517
+ // Deliberately asynchronous even though mkdir is cheap: callers drive ONE
518
+ // state machine for both kinds, so `create` must never settle before the
519
+ // requester has had a chance to subscribe.
520
+ setImmediate(() => {
521
+ if (job.state !== 'running')
522
+ return;
523
+ if (job.cancelRequested) {
524
+ this.cleanupCancelled(job);
525
+ this.finish(job, 'cancelled');
526
+ return;
527
+ }
528
+ try {
529
+ this.record(job, {
530
+ phase: 'creating',
531
+ scope: REPOSITORY_SCOPE,
532
+ percent: null,
533
+ indeterminate: true,
534
+ text: `Creating ${job.targetPath}`,
535
+ at: Date.now(),
536
+ });
537
+ fs.mkdirSync(job.targetPath, { recursive: true });
538
+ }
539
+ catch (err) {
540
+ job.failure = { cause: 'unknown', message: `Could not create ${job.targetPath}: ${err?.message || err}`, stderr: '' };
541
+ this.finish(job, 'failed');
542
+ return;
543
+ }
544
+ if (!job.gitInit) {
545
+ this.finish(job, 'done');
546
+ return;
547
+ }
548
+ this.record(job, {
549
+ phase: 'initialising',
550
+ scope: REPOSITORY_SCOPE,
551
+ percent: null,
552
+ indeterminate: true,
553
+ text: `Initialising a git repository in ${job.targetPath}`,
554
+ at: Date.now(),
555
+ });
556
+ // The path travels as `cwd`, never as an argument, so nothing about it can
557
+ // be read as an option.
558
+ const child = this.spawnFn('git', ['init'], {
559
+ cwd: job.targetPath,
560
+ stdio: ['ignore', 'ignore', 'pipe'],
561
+ env: process.env,
562
+ });
563
+ job.child = child;
564
+ child.stderr?.setEncoding('utf8');
565
+ child.stderr?.on('data', (chunk) => {
566
+ if (job.stderr.length < MAX_STDERR_CHARS)
567
+ job.stderr += chunk;
568
+ });
569
+ child.on('error', (err) => {
570
+ job.failure = { cause: 'unknown', message: `git init failed: ${err.message}`, stderr: job.stderr };
571
+ this.finish(job, 'failed');
572
+ });
573
+ child.on('close', (code) => {
574
+ if (job.state !== 'running')
575
+ return;
576
+ if (job.cancelRequested) {
577
+ this.cleanupCancelled(job);
578
+ this.finish(job, 'cancelled');
579
+ return;
580
+ }
581
+ if (code === 0) {
582
+ this.finish(job, 'done');
583
+ return;
584
+ }
585
+ job.failure = {
586
+ cause: 'unknown',
587
+ message: lastMeaningfulLine(job.stderr) || `git init exited with code ${code}`,
588
+ stderr: job.stderr,
589
+ };
590
+ this.finish(job, 'failed');
591
+ });
592
+ });
593
+ }
594
+ /** Store the latest frame always; publish it at a few frames per second. */
595
+ record(job, frame) {
596
+ const previous = job.progress;
597
+ job.progress = frame;
598
+ const changedScope = !previous || previous.scope !== frame.scope || previous.phase !== frame.phase;
599
+ const now = Date.now();
600
+ if (!changedScope && frame.percent !== 100 && now - job.lastEmitAt < this.progressIntervalMs)
601
+ return;
602
+ job.lastEmitAt = now;
603
+ const view = snapshot(job);
604
+ for (const observer of this.observersFor(job.targetPath)) {
605
+ try {
606
+ observer.onProgress?.(frame, view);
607
+ }
608
+ catch (err) {
609
+ console.error('Restore progress observer threw:', err);
610
+ }
611
+ }
612
+ }
613
+ cleanupCancelled(job) {
614
+ if (!job.createdTarget)
615
+ return;
616
+ try {
617
+ fs.rmSync(job.targetPath, { recursive: true, force: true });
618
+ }
619
+ catch (err) {
620
+ console.error(`Failed to remove cancelled restore target ${job.targetPath}:`, err);
621
+ }
622
+ }
623
+ finish(job, state) {
624
+ if (job.state !== 'running')
625
+ return;
626
+ job.state = state;
627
+ job.endedAt = Date.now();
628
+ if (job.killTimer) {
629
+ clearTimeout(job.killTimer);
630
+ job.killTimer = undefined;
631
+ }
632
+ const view = snapshot(job);
633
+ for (const observer of this.observersFor(job.targetPath)) {
634
+ try {
635
+ observer.onSettled?.(view);
636
+ }
637
+ catch (err) {
638
+ console.error('Restore settle observer threw:', err);
639
+ }
640
+ }
641
+ job.resolveSettled(view);
642
+ job.reapTimer = setTimeout(() => {
643
+ if (this.jobs.get(job.targetPath) === job)
644
+ this.jobs.delete(job.targetPath);
645
+ }, this.retainMs);
646
+ job.reapTimer.unref?.();
647
+ }
648
+ observersFor(targetPath) {
649
+ const set = this.observers.get(targetPath);
650
+ return set ? [...set] : [];
651
+ }
652
+ }
653
+ function snapshot(job) {
654
+ return {
655
+ id: job.id,
656
+ kind: job.kind,
657
+ targetPath: job.targetPath,
658
+ ...(job.url !== undefined ? { url: job.url } : {}),
659
+ ...(job.gitInit !== undefined ? { gitInit: job.gitInit } : {}),
660
+ state: job.state,
661
+ progress: job.progress,
662
+ ...(job.failure ? { failure: job.failure } : {}),
663
+ startedAt: job.startedAt,
664
+ ...(job.endedAt !== undefined ? { endedAt: job.endedAt } : {}),
665
+ };
666
+ }
667
+ function expandTilde(p) {
668
+ if (p === '~')
669
+ return os.homedir();
670
+ if (p.startsWith('~/'))
671
+ return path.join(os.homedir(), p.slice(2));
672
+ return p;
673
+ }
674
+ /**
675
+ * Pre-configure upstream tracking for the cloned default branch.
676
+ *
677
+ * This preserves the behaviour of `cloneRemoteRepo()`/`setupUpstreamTracking()`
678
+ * in `session-pool.ts`, which this module is to replace. It is re-implemented
679
+ * here rather than imported because `session-pool.ts` pulls in the whole
680
+ * pi-coding-agent runtime, and this module (and its tests) must stay standalone.
681
+ * The later re-point task deletes the session-pool copies.
682
+ *
683
+ * Best effort by design: a clone that succeeded is a restored folder, and a
684
+ * tracking config that did not take is not worth failing it over.
685
+ */
686
+ function setupUpstreamTracking(resolvedCwd) {
687
+ // Synchronous is fine here: these are local config reads and writes on a repo
688
+ // that was just written to disk, and the job is already at its end.
689
+ try {
690
+ let defaultBranch = '';
691
+ try {
692
+ defaultBranch = execFileSync('git', ['symbolic-ref', '--short', 'HEAD'], { cwd: resolvedCwd })
693
+ .toString()
694
+ .trim();
695
+ }
696
+ catch {
697
+ try {
698
+ defaultBranch = execFileSync('git', ['config', '--get', 'init.defaultBranch'], { cwd: resolvedCwd })
699
+ .toString()
700
+ .trim();
701
+ }
702
+ catch { }
703
+ }
704
+ if (!defaultBranch)
705
+ defaultBranch = 'main';
706
+ execFileSync('git', ['config', `branch.${defaultBranch}.remote`, 'origin'], { cwd: resolvedCwd, stdio: 'ignore' });
707
+ execFileSync('git', ['config', `branch.${defaultBranch}.merge`, `refs/heads/${defaultBranch}`], {
708
+ cwd: resolvedCwd,
709
+ stdio: 'ignore',
710
+ });
711
+ }
712
+ catch (err) {
713
+ console.error('Failed to pre-configure upstream tracking branch:', err);
714
+ }
715
+ }
716
+ //# sourceMappingURL=restore-jobs.js.map