castle-web-cli 0.4.212 → 0.4.214

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 (56) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +28 -6
  3. package/dist/agent.js +33 -2
  4. package/dist/cloudGit.d.ts +254 -0
  5. package/dist/cloudGit.js +1687 -0
  6. package/dist/cloudGitServe.d.ts +41 -0
  7. package/dist/cloudGitServe.js +318 -0
  8. package/dist/cover-bridge/play-cover-bridge.js +2 -0
  9. package/dist/externalSourcemaps.js +2 -1
  10. package/dist/gitRemote.d.ts +4 -1
  11. package/dist/gitRemote.js +4 -2
  12. package/dist/ide.js +52 -7
  13. package/dist/index.js +149 -2
  14. package/dist/playCover/bridge.d.ts +6 -0
  15. package/dist/playCover/bridge.js +159 -0
  16. package/dist/playCover/builtins.d.ts +29 -0
  17. package/dist/playCover/builtins.js +189 -0
  18. package/dist/playCover/capture.d.ts +53 -0
  19. package/dist/playCover/capture.js +419 -0
  20. package/dist/playCover/clone.d.ts +40 -0
  21. package/dist/playCover/clone.js +317 -0
  22. package/dist/playCover/engine.d.ts +37 -0
  23. package/dist/playCover/engine.js +76 -0
  24. package/dist/playCover/errors.d.ts +6 -0
  25. package/dist/playCover/errors.js +18 -0
  26. package/dist/playCover/images.d.ts +21 -0
  27. package/dist/playCover/images.js +180 -0
  28. package/dist/playCover/instrument.d.ts +49 -0
  29. package/dist/playCover/instrument.js +334 -0
  30. package/dist/playCover/protocol.d.ts +14 -0
  31. package/dist/playCover/protocol.js +139 -0
  32. package/dist/playCover/rasterize.d.ts +21 -0
  33. package/dist/playCover/rasterize.js +408 -0
  34. package/dist/playCover/resources.d.ts +31 -0
  35. package/dist/playCover/resources.js +823 -0
  36. package/dist/playCover/scratchCanvas.d.ts +4 -0
  37. package/dist/playCover/scratchCanvas.js +16 -0
  38. package/dist/playCover/textSamples.d.ts +36 -0
  39. package/dist/playCover/textSamples.js +412 -0
  40. package/dist/playCover/validate.d.ts +79 -0
  41. package/dist/playCover/validate.js +883 -0
  42. package/dist/playCover/verify.d.ts +56 -0
  43. package/dist/playCover/verify.js +578 -0
  44. package/dist/playCover/verifyRecord.d.ts +71 -0
  45. package/dist/playCover/verifyRecord.js +243 -0
  46. package/dist/playCoverGate.d.ts +4 -0
  47. package/dist/playCoverGate.js +57 -0
  48. package/dist/playCoverPlacement.d.ts +11 -0
  49. package/dist/playCoverPlacement.js +110 -0
  50. package/dist/serve.d.ts +1 -0
  51. package/dist/serve.js +35 -17
  52. package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
  53. package/dist/shell/assets/{index-DzLbNBc7.js → index-BcslKMfS.js} +94 -92
  54. package/dist/shell/index.html +2 -2
  55. package/package.json +2 -2
  56. package/dist/shell/assets/index-BCrgYh76.css +0 -1
@@ -0,0 +1,1687 @@
1
+ import { execFile } from 'child_process';
2
+ import { randomUUID } from 'crypto';
3
+ import * as fs from 'fs';
4
+ import * as os from 'os';
5
+ import * as path from 'path';
6
+ import { GIT_HOSTS, GIT_REMOTE_NAME, isSandboxToken, runGit } from './gitRemote.js';
7
+ import { COVER_FILE } from './localPaths.js';
8
+ export const COMMIT_REASONS = ['turn', 'task', 'leave', 'manual', 'sync'];
9
+ // Commits the agent made are marked so the Versions panel (and a laptop's git log) can tell
10
+ // them from the user's own edits. The commit is still authored as the user.
11
+ const AGENT_REASONS = new Set(['turn', 'task']);
12
+ export const AGENT_TRAILER_KEY = 'Castle-Agent';
13
+ const AGENT_TRAILER = `${AGENT_TRAILER_KEY}: claude`;
14
+ // The serve's own commits (and the leave commit) happen whether or not anything changed, so
15
+ // with nothing committed and nothing to push they skip the network entirely.
16
+ const QUIET_REASONS = new Set(['turn', 'task', 'leave']);
17
+ const DEFAULT_MESSAGES = {
18
+ turn: 'Changes from the agent',
19
+ task: 'Changes from agent tasks',
20
+ leave: 'Edits saved on leaving the deck',
21
+ manual: 'Saved version',
22
+ sync: 'Edits saved before syncing',
23
+ };
24
+ // Exit codes every command here uses, so the sandbox agent and the serve can tell a
25
+ // skipped command from a failed one.
26
+ export const EXIT_OK = 0;
27
+ export const EXIT_ERROR = 1;
28
+ /** Not a sandbox, or a deck `git attach` never set up: nothing was done. */
29
+ export const EXIT_NOT_ENABLED = 2;
30
+ /** A merge with the remote is waiting on the agent; nothing was committed. */
31
+ export const EXIT_CONFLICT = 3;
32
+ export class CloudGitError extends Error {
33
+ exitCode;
34
+ constructor(message, exitCode = EXIT_ERROR) {
35
+ super(message);
36
+ this.name = 'CloudGitError';
37
+ this.exitCode = exitCode;
38
+ }
39
+ }
40
+ // Castle's excludes, in .git/info/exclude rather than a .gitignore, so they apply whatever
41
+ // the deck's own .gitignore says and never show up as a change to the deck.
42
+ export const CLOUD_EXCLUDES = ['node_modules/', 'dist/', '/imports/', '.castle/', '.vite/'];
43
+ // More loose objects than this and a commit packs the repo: loose objects count toward the
44
+ // checkpoint's file cap, and `.git` rides in every draft checkpoint.
45
+ export const LOOSE_OBJECT_LIMIT = 200;
46
+ const PACK_TIMEOUT_MS = 90_000;
47
+ // A command that has already run this long leaves packing to the next one, so a caller's
48
+ // time limit never lands in the middle of a repack.
49
+ const PACK_BUDGET_MS = 120_000;
50
+ // A `.git/*.lock` this old is left over from a process that died -- or from a checkpoint
51
+ // that paused the container mid-write and restored the file.
52
+ export const STALE_GIT_LOCK_MS = 60_000;
53
+ // Everything these commands write lives under .git/ or .castle/agent/: the sandbox's draft
54
+ // checkpoints file those as private editor state, and refuse -- failing the whole checkpoint --
55
+ // any other path under .castle/. A checkpoint pauses the container at an arbitrary moment, so
56
+ // that holds for every lock, temp and claim file too, not just the finished records.
57
+ // The lock that serializes our own commits and syncs. See acquireLockFile. Not named `*.lock`:
58
+ // clearStaleGitLocks removes old files of that name at the top of .git.
59
+ export const DECK_LOCK_FILE = path.join('.git', 'castle-deck-lock');
60
+ const DECK_LOCK_WAIT_MS = 120_000;
61
+ // A lock file that does not name its holder can only be judged by its age.
62
+ const UNREADABLE_LOCK_STALE_MS = 10 * 60_000;
63
+ // A takeover claim is held for two system calls; one this old belongs to a process that died.
64
+ const LOCK_CLAIM_STALE_MS = 60_000;
65
+ const NETWORK_TIMEOUT_MS = 120_000;
66
+ const PUSH_RETRIES = 2;
67
+ /** Written by `git sync` on a conflict; the serve turns it into an agent turn. */
68
+ export const CONFLICT_MARKER_FILE = path.join('.castle', 'agent', 'git-conflict.json');
69
+ /** Written by `git attach` when it took the remote's version over a differing cloud copy. */
70
+ export const ADOPTED_MARKER_FILE = path.join('.castle', 'agent', 'git-adopted.json');
71
+ /** Every marker the serve turns into an agent turn. */
72
+ export const AGENT_MARKER_FILES = [CONFLICT_MARKER_FILE, ADOPTED_MARKER_FILE];
73
+ /** The serve's note that task agents (or the router) are working in the deck; see deckBusy. */
74
+ export const BUSY_FILE = path.join('.castle', 'agent', 'git-busy.json');
75
+ /** The remote has (or may have) work that waits to be merged until the deck is idle. */
76
+ export const SYNC_PENDING_FILE = path.join('.castle', 'agent', 'git-sync-pending');
77
+ /** The conflicted merge in progress, in .git beside MERGE_HEAD. */
78
+ export const MERGE_STATE_FILE = 'castle-merge.json';
79
+ /**
80
+ * Where `git attach` saves the cloud copy's files before taking the remote's version: one
81
+ * directory per attach. Under .git so no name a deck file may have (`*.pem`, `credentials`) is
82
+ * refused as a credential by the checkpoint, and never part of the working tree.
83
+ */
84
+ export const ATTACH_BACKUPS_DIR = path.join('.git', 'castle-attach-backups');
85
+ /** Backups written by an attach whose agent notice has not been written yet. */
86
+ export const ADOPT_PENDING_FILE = path.join('.git', 'castle-adopt-pending.json');
87
+ /** A leave commit found a merge waiting: the edits on disk stay uncommitted until it concludes. */
88
+ export const LEAVE_PENDING_FILE = path.join('.git', 'castle-leave-pending.json');
89
+ // Backups past this age, or beyond this many newer ones, are removed -- once the agent has been
90
+ // told about them.
91
+ export const ATTACH_BACKUP_MAX_AGE_MS = 30 * 24 * 60 * 60_000;
92
+ export const ATTACH_BACKUP_KEEP = 10;
93
+ // A caller's time limit, as the epoch ms by which this command must have exited (runCastleWeb
94
+ // sets it to just short of its SIGKILL). Every git step's own timeout is capped by what is left,
95
+ // so no step is still running when the kill lands, and none starts without time to finish.
96
+ export const DEADLINE_ENV = 'CASTLE_GIT_DEADLINE';
97
+ const MIN_STEP_MS = 2_000;
98
+ const MAIN = 'main';
99
+ const REMOTE_MAIN = `refs/remotes/${GIT_REMOTE_NAME}/${MAIN}`;
100
+ function sleepSync(ms) {
101
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
102
+ }
103
+ function pidIsAlive(pid) {
104
+ try {
105
+ process.kill(pid, 0);
106
+ return true;
107
+ }
108
+ catch (e) {
109
+ return e.code === 'EPERM';
110
+ }
111
+ }
112
+ /** A process's start time (in clock ticks since boot, from /proc), which tells a reused pid apart. */
113
+ export function processStartTime(pid) {
114
+ try {
115
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf-8');
116
+ // Field 22; counted from after the command name, which may itself hold spaces.
117
+ return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19] ?? null;
118
+ }
119
+ catch {
120
+ return null;
121
+ }
122
+ }
123
+ // The same process as the one recorded: alive, and (where /proc says) started at the same time.
124
+ function sameLiveProcess(deps, pid, start) {
125
+ if (pid <= 0 || !deps.isAlive(pid))
126
+ return false;
127
+ if (typeof start !== 'string')
128
+ return true;
129
+ const now = processStartTime(pid);
130
+ return now === null || now === start;
131
+ }
132
+ // git with the environment these commands need: no prompts (a missing credential must fail,
133
+ // not hang a turn), and no inherited GIT_DIR/GIT_WORK_TREE pointing somewhere else. The
134
+ // GIT_CONFIG_* the container sets are kept -- they carry the remote rewrite and the helper.
135
+ function cloudGitEnv(baseEnv) {
136
+ const env = { ...baseEnv, GIT_TERMINAL_PROMPT: '0' };
137
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_COMMON_DIR']) {
138
+ delete env[key];
139
+ }
140
+ return env;
141
+ }
142
+ export function cloudGitRunner(baseEnv = process.env) {
143
+ const env = cloudGitEnv(baseEnv);
144
+ return (args, cwd, opts) => runGit(args, cwd, {
145
+ env: opts?.indexFile ? { ...env, GIT_INDEX_FILE: opts.indexFile } : env,
146
+ timeoutMs: opts?.timeoutMs,
147
+ });
148
+ }
149
+ // The async form, for the serve and the IDE server: their event loop must never wait on git.
150
+ function runGitAsync(args, cwd, baseEnv) {
151
+ return new Promise((resolve) => {
152
+ execFile('git', args, {
153
+ cwd,
154
+ env: { ...cloudGitEnv(baseEnv), LC_ALL: 'C', LANGUAGE: 'C' },
155
+ encoding: 'utf-8',
156
+ maxBuffer: 64 * 1024 * 1024,
157
+ timeout: 60_000,
158
+ }, (error, stdout, stderr) => {
159
+ const code = error?.code;
160
+ resolve({
161
+ status: error ? (typeof code === 'number' ? code : null) : 0,
162
+ stdout,
163
+ stderr,
164
+ error: error && typeof code !== 'number' ? error : undefined,
165
+ });
166
+ });
167
+ });
168
+ }
169
+ export function defaultCloudGitDeps(whoAmI) {
170
+ // A caller's time limit arrives as SIGTERM: the command stops at its next safe point (never
171
+ // inside a git command) instead of dying wherever it happens to be.
172
+ let stopping = false;
173
+ process.on('SIGTERM', () => {
174
+ stopping = true;
175
+ });
176
+ return {
177
+ git: cloudGitRunner(),
178
+ whoAmI,
179
+ env: process.env,
180
+ log: (message) => console.log(message),
181
+ warn: (message) => console.error(message),
182
+ now: () => Date.now(),
183
+ sleep: sleepSync,
184
+ pid: process.pid,
185
+ hostname: () => os.hostname(),
186
+ isAlive: pidIsAlive,
187
+ stopRequested: () => new Promise((resolve) => setImmediate(() => resolve(stopping))),
188
+ };
189
+ }
190
+ // A git step's timeout: its own, capped by the time left before the caller's deadline. A step
191
+ // with too little time left is not started at all -- stopping between steps is safe, being
192
+ // killed in the middle of one is not.
193
+ function stepTimeout(ctx, args, wanted) {
194
+ if (ctx.deadline === undefined)
195
+ return wanted;
196
+ const left = ctx.deadline - ctx.deps.now();
197
+ if (left < MIN_STEP_MS) {
198
+ throw new CloudGitError(`Out of time: stopped before \`git ${args.join(' ')}\` rather than be killed partway through it.`);
199
+ }
200
+ return wanted === undefined ? left : Math.min(wanted, left);
201
+ }
202
+ function errorCode(result) {
203
+ return result.error && 'code' in result.error ? result.error.code : undefined;
204
+ }
205
+ function describeFailure(args, result) {
206
+ const timedOut = errorCode(result) === 'ETIMEDOUT';
207
+ const why = timedOut ? 'timed out' : (result.stderr || result.stdout || result.error?.message || '').trim();
208
+ return `\`git ${args.join(' ')}\` failed${why ? `: ${why}` : ''}`;
209
+ }
210
+ function run(ctx, args, opts) {
211
+ const result = ctx.deps.git(args, ctx.dir, { ...opts, timeoutMs: stepTimeout(ctx, args, opts?.timeoutMs) });
212
+ if (errorCode(result) === 'ENOENT') {
213
+ throw new CloudGitError('git is not installed (or not on PATH).');
214
+ }
215
+ return result;
216
+ }
217
+ function must(ctx, args, opts) {
218
+ const result = run(ctx, args, opts);
219
+ if (result.status !== 0)
220
+ throw new CloudGitError(describeFailure(args, result));
221
+ return result.stdout;
222
+ }
223
+ function ok(ctx, args) {
224
+ return run(ctx, args).status === 0;
225
+ }
226
+ function revParse(ctx, ref) {
227
+ const result = run(ctx, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
228
+ return result.status === 0 ? result.stdout.trim() : null;
229
+ }
230
+ function localConfig(ctx, key) {
231
+ const result = run(ctx, ['config', '--local', '--get', key]);
232
+ return result.status === 0 ? result.stdout.trim() : null;
233
+ }
234
+ function gitDir(dir) {
235
+ return path.join(dir, '.git');
236
+ }
237
+ export function mergeInProgress(dir) {
238
+ return fs.existsSync(path.join(gitDir(dir), 'MERGE_HEAD'));
239
+ }
240
+ function lines(text) {
241
+ return text.split('\n').map((l) => l.trim()).filter(Boolean);
242
+ }
243
+ function literal(rel) {
244
+ return `:(literal)${rel.split(path.sep).join('/')}`;
245
+ }
246
+ function writeJsonAtomic(file, value) {
247
+ fs.mkdirSync(path.dirname(file), { recursive: true });
248
+ const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`;
249
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n');
250
+ fs.renameSync(tmp, file);
251
+ }
252
+ // --- who may run what -------------------------------------------------------
253
+ export function isSandboxEnv(env) {
254
+ return Boolean(env.CASTLE_SANDBOX_ID) || isSandboxToken(env.CASTLE_TOKEN);
255
+ }
256
+ /** Whether `git attach` set this deck up: its own `.git` directory, marked in its config. */
257
+ export function isAttached(dir, git = cloudGitRunner()) {
258
+ try {
259
+ if (!fs.statSync(gitDir(dir)).isDirectory())
260
+ return false;
261
+ }
262
+ catch {
263
+ return false;
264
+ }
265
+ const result = git(['config', '--local', '--get', 'castle.cloud'], dir);
266
+ return result.status === 0 && result.stdout.trim() === 'true';
267
+ }
268
+ /**
269
+ * The serve's switch: the gate env castle-www sets on the serve, AND a deck that attach
270
+ * actually set up. An attach that failed leaves the deck on the old version store.
271
+ */
272
+ export function cloudGitMode(dir, env = process.env) {
273
+ return env.CASTLE_GIT === 'on' && isAttached(dir, cloudGitRunner(env));
274
+ }
275
+ /** cloudGitMode without blocking the caller's event loop. */
276
+ export async function cloudGitModeAsync(dir, env = process.env) {
277
+ if (env.CASTLE_GIT !== 'on')
278
+ return false;
279
+ try {
280
+ if (!(await fs.promises.stat(gitDir(dir))).isDirectory())
281
+ return false;
282
+ }
283
+ catch {
284
+ return false;
285
+ }
286
+ const result = await runGitAsync(['config', '--local', '--get', 'castle.cloud'], dir, env);
287
+ return result.status === 0 && result.stdout.trim() === 'true';
288
+ }
289
+ // The gate env counts too: castle-www sets CASTLE_GIT=on on the attach it runs in the
290
+ // container, and the sandbox agent on its commit and sync.
291
+ function requireSandbox(deps, command) {
292
+ if (!isSandboxEnv(deps.env) && deps.env.CASTLE_GIT !== 'on') {
293
+ throw new CloudGitError(`castle-web ${command} only runs in a Castle cloud sandbox. On your own computer, use \`castle-web git init\` and plain git.`, EXIT_NOT_ENABLED);
294
+ }
295
+ }
296
+ function requireAttached(ctx, command) {
297
+ requireSandbox(ctx.deps, command);
298
+ if (!isAttached(ctx.dir, ctx.deps.git)) {
299
+ throw new CloudGitError(`${ctx.dir} is not attached to its Castle git remote, so there is nothing for \`castle-web ${command}\` to do.`, EXIT_NOT_ENABLED);
300
+ }
301
+ }
302
+ // --- busy and pending sync ----------------------------------------------------
303
+ // While a task agent (or the router) is working in the deck, nothing merges the remote into
304
+ // its files: commits land locally and push only when that is a fast-forward, and a laptop
305
+ // push waits (SYNC_PENDING_FILE) for the board-idle commit to merge it. The serve keeps this
306
+ // file current; one whose serve is gone (or was in another container) does not count.
307
+ export function deckBusy(ctx) {
308
+ try {
309
+ const held = JSON.parse(fs.readFileSync(path.join(ctx.dir, BUSY_FILE), 'utf-8'));
310
+ return (typeof held.pid === 'number' &&
311
+ held.host === ctx.deps.hostname() &&
312
+ sameLiveProcess(ctx.deps, held.pid, held.start));
313
+ }
314
+ catch {
315
+ return false;
316
+ }
317
+ }
318
+ /** The serve's side of deckBusy. */
319
+ export function setDeckBusy(dir, busy) {
320
+ const file = path.join(dir, BUSY_FILE);
321
+ if (busy) {
322
+ writeJsonAtomic(file, { pid: process.pid, host: os.hostname(), start: processStartTime(process.pid) });
323
+ return;
324
+ }
325
+ try {
326
+ const held = JSON.parse(fs.readFileSync(file, 'utf-8'));
327
+ if (held.pid === process.pid)
328
+ fs.rmSync(file, { force: true });
329
+ }
330
+ catch {
331
+ /* not there */
332
+ }
333
+ }
334
+ function syncPending(ctx) {
335
+ return fs.existsSync(path.join(ctx.dir, SYNC_PENDING_FILE));
336
+ }
337
+ function markSyncPending(ctx) {
338
+ const file = path.join(ctx.dir, SYNC_PENDING_FILE);
339
+ fs.mkdirSync(path.dirname(file), { recursive: true });
340
+ fs.writeFileSync(file, new Date(ctx.deps.now()).toISOString() + '\n');
341
+ }
342
+ function clearSyncPending(ctx) {
343
+ fs.rmSync(path.join(ctx.dir, SYNC_PENDING_FILE), { force: true });
344
+ }
345
+ function inspectLock(file) {
346
+ let fd;
347
+ try {
348
+ fd = fs.openSync(file, 'r');
349
+ }
350
+ catch (e) {
351
+ if (e.code === 'ENOENT')
352
+ return null;
353
+ throw e;
354
+ }
355
+ try {
356
+ const stat = fs.fstatSync(fd);
357
+ return { ino: stat.ino, text: fs.readFileSync(fd, 'utf-8'), mtimeMs: stat.mtimeMs };
358
+ }
359
+ finally {
360
+ fs.closeSync(fd);
361
+ }
362
+ }
363
+ // A holder is gone when the lock names a process of another container (a checkpoint carried
364
+ // the file into this one), or one of this container that is no longer running. A live holder
365
+ // is never expired by age: a slow push is still a push in progress.
366
+ function holderIsGone(deps, seen) {
367
+ let held = {};
368
+ try {
369
+ held = JSON.parse(seen.text);
370
+ }
371
+ catch {
372
+ held = {};
373
+ }
374
+ if (typeof held.pid !== 'number' || typeof held.host !== 'string') {
375
+ return deps.now() - seen.mtimeMs > UNREADABLE_LOCK_STALE_MS;
376
+ }
377
+ if (held.host !== deps.hostname())
378
+ return true;
379
+ return !sameLiveProcess(deps, held.pid, held.start);
380
+ }
381
+ // Removes the lock file only if it is still the very file inspected. Removal needs a claim: a
382
+ // file named for the inspected inode, created exclusively, so exactly one waiter holds it. The
383
+ // claimant checks the lock is still that inode with that content before removing it, and no
384
+ // one else removes a lock at all -- so a fresh lock someone took in the meantime (its random
385
+ // token differs, even on a reused inode) is never removed by a waiter that saw the stale one.
386
+ // True when the stale lock is gone.
387
+ //
388
+ // Neither the lock nor the claim is ever a hard link: a draft checkpoint refuses hard-linked
389
+ // files, and a process killed between a link() and its unlink would leave one for good.
390
+ function takeOverStaleLock(deps, file, seen) {
391
+ const claim = `${file}.takeover-${seen.ino}`;
392
+ try {
393
+ fs.writeFileSync(claim, String(deps.pid), { flag: 'wx' });
394
+ }
395
+ catch (e) {
396
+ if (e.code !== 'EEXIST')
397
+ throw e;
398
+ // Another waiter is mid-takeover, or died there (then its claim ages out).
399
+ try {
400
+ if (deps.now() - fs.lstatSync(claim).ctimeMs > LOCK_CLAIM_STALE_MS)
401
+ fs.rmSync(claim, { force: true });
402
+ }
403
+ catch {
404
+ /* gone already */
405
+ }
406
+ return false;
407
+ }
408
+ try {
409
+ const now = inspectLock(file);
410
+ if (!now)
411
+ return true;
412
+ if (now.ino === seen.ino && now.text === seen.text) {
413
+ fs.rmSync(file, { force: true });
414
+ return true;
415
+ }
416
+ return false;
417
+ }
418
+ finally {
419
+ fs.rmSync(claim, { force: true });
420
+ }
421
+ }
422
+ // Temp files an older build published its lock from.
423
+ function removeOldLockLeftovers(deps, file) {
424
+ const dir = path.dirname(file);
425
+ const prefix = `${path.basename(file)}.`;
426
+ try {
427
+ for (const name of fs.readdirSync(dir)) {
428
+ if (!name.startsWith(prefix) || !name.endsWith('.tmp'))
429
+ continue;
430
+ const full = path.join(dir, name);
431
+ if (deps.now() - fs.statSync(full).mtimeMs > UNREADABLE_LOCK_STALE_MS)
432
+ fs.rmSync(full, { force: true });
433
+ }
434
+ }
435
+ catch {
436
+ /* best effort */
437
+ }
438
+ }
439
+ /**
440
+ * An exclusive lock on `file`, returning its release. The lock is created exclusively (O_EXCL),
441
+ * names its holder (pid, container hostname, process start time) and a random token, and is
442
+ * released only by the holder whose token it still carries. A stale one is taken over through
443
+ * takeOverStaleLock. Until its content is written a lock reads as unreadable, which a waiter
444
+ * judges only by age -- a holder is not taken over in that instant.
445
+ */
446
+ export function acquireLockFile(file, deps, waitMs = DECK_LOCK_WAIT_MS) {
447
+ fs.mkdirSync(path.dirname(file), { recursive: true });
448
+ removeOldLockLeftovers(deps, file);
449
+ const token = randomUUID();
450
+ const text = JSON.stringify({
451
+ pid: deps.pid,
452
+ host: deps.hostname(),
453
+ start: processStartTime(deps.pid),
454
+ at: deps.now(),
455
+ token,
456
+ });
457
+ const deadline = deps.now() + waitMs;
458
+ for (;;) {
459
+ let fd = null;
460
+ try {
461
+ fd = fs.openSync(file, 'wx');
462
+ }
463
+ catch (e) {
464
+ if (e.code !== 'EEXIST')
465
+ throw e;
466
+ }
467
+ if (fd !== null) {
468
+ try {
469
+ fs.writeSync(fd, text);
470
+ }
471
+ catch (e) {
472
+ fs.closeSync(fd);
473
+ fs.rmSync(file, { force: true });
474
+ throw e;
475
+ }
476
+ fs.closeSync(fd);
477
+ if (inspectLock(file)?.text === text)
478
+ break;
479
+ continue;
480
+ }
481
+ const seen = inspectLock(file);
482
+ if (!seen)
483
+ continue;
484
+ if (holderIsGone(deps, seen) && takeOverStaleLock(deps, file, seen))
485
+ continue;
486
+ if (deps.now() > deadline) {
487
+ throw new CloudGitError('Another castle-web commit or sync is still running on this deck. Try again shortly.');
488
+ }
489
+ deps.sleep(200);
490
+ }
491
+ return () => {
492
+ try {
493
+ if (inspectLock(file)?.text === text)
494
+ fs.rmSync(file, { force: true });
495
+ }
496
+ catch {
497
+ /* already gone */
498
+ }
499
+ };
500
+ }
501
+ async function withDeckLock(ctx, fn) {
502
+ // Waiting for the lock counts against the deadline too, with time left over to work.
503
+ const waitMs = ctx.deadline === undefined ? DECK_LOCK_WAIT_MS : Math.max(0, Math.min(DECK_LOCK_WAIT_MS, ctx.deadline - ctx.deps.now() - 10_000));
504
+ const release = acquireLockFile(path.join(ctx.dir, DECK_LOCK_FILE), ctx.deps, waitMs);
505
+ try {
506
+ clearStaleGitLocks(ctx);
507
+ return await fn();
508
+ }
509
+ finally {
510
+ release();
511
+ }
512
+ }
513
+ // Lock files git leaves when its process dies: at the top of .git and beside refs. Only
514
+ // cleared while holding the deck lock, so none of them can belong to our own live commands.
515
+ export function clearStaleGitLocks(ctx) {
516
+ const root = gitDir(ctx.dir);
517
+ const cleared = [];
518
+ const visit = (dir, recurse) => {
519
+ let entries;
520
+ try {
521
+ entries = fs.readdirSync(dir, { withFileTypes: true });
522
+ }
523
+ catch {
524
+ return;
525
+ }
526
+ for (const entry of entries) {
527
+ const full = path.join(dir, entry.name);
528
+ if (entry.isDirectory()) {
529
+ if (recurse)
530
+ visit(full, true);
531
+ continue;
532
+ }
533
+ if (!entry.name.endsWith('.lock'))
534
+ continue;
535
+ try {
536
+ if (ctx.deps.now() - fs.statSync(full).mtimeMs <= STALE_GIT_LOCK_MS)
537
+ continue;
538
+ fs.rmSync(full, { force: true });
539
+ cleared.push(path.relative(ctx.dir, full));
540
+ }
541
+ catch {
542
+ /* raced with its owner */
543
+ }
544
+ }
545
+ };
546
+ visit(root, false);
547
+ visit(path.join(root, 'refs'), true);
548
+ if (cleared.length > 0)
549
+ ctx.deps.warn(`Removed stale git lock files: ${cleared.join(', ')}`);
550
+ return cleared;
551
+ }
552
+ // --- identity ---------------------------------------------------------------
553
+ export function noreplyEmail(userId, username) {
554
+ const safeName = username.replace(/[^A-Za-z0-9._-]/g, '') || 'user';
555
+ const safeId = userId.replace(/[^A-Za-z0-9_-]/g, '') || 'unknown';
556
+ return `${safeId}+${safeName}@users.noreply.castle.xyz`;
557
+ }
558
+ /** A username as a git author name: no control characters or angle brackets, never empty. */
559
+ export function safeAuthorName(username) {
560
+ // eslint-disable-next-line no-control-regex
561
+ return username.replace(/[\x00-\x1f\x7f<>]/g, '').trim().slice(0, 100) || 'Castle user';
562
+ }
563
+ // Commits are the user's: their username and a noreply address, set in the repo's own
564
+ // config so the lookup happens once. If `me` can't be reached, this commit still lands under
565
+ // a placeholder rather than failing, and the next one asks again. The value goes after the
566
+ // key, where git config takes it literally whatever it starts with.
567
+ async function identityArgs(ctx) {
568
+ if (localConfig(ctx, 'user.email') && localConfig(ctx, 'user.name'))
569
+ return [];
570
+ let user = null;
571
+ try {
572
+ user = await ctx.deps.whoAmI();
573
+ }
574
+ catch (e) {
575
+ ctx.deps.warn(`Could not look up your Castle username: ${e instanceof Error ? e.message : String(e)}`);
576
+ }
577
+ if (user?.username && user.userId) {
578
+ must(ctx, ['config', '--local', 'user.name', safeAuthorName(String(user.username))]);
579
+ must(ctx, ['config', '--local', 'user.email', noreplyEmail(String(user.userId), String(user.username))]);
580
+ return [];
581
+ }
582
+ const userId = ctx.deps.env.CASTLE_USER_ID || 'unknown';
583
+ return ['-c', 'user.name=Castle user', '-c', `user.email=${noreplyEmail(userId, 'user')}`];
584
+ }
585
+ function mergeStatePath(dir) {
586
+ return path.join(gitDir(dir), MERGE_STATE_FILE);
587
+ }
588
+ export function readMergeState(dir) {
589
+ try {
590
+ const state = JSON.parse(fs.readFileSync(mergeStatePath(dir), 'utf-8'));
591
+ return Array.isArray(state.files) && typeof state.instruction === 'string' ? state : null;
592
+ }
593
+ catch {
594
+ return null;
595
+ }
596
+ }
597
+ function unmergedStages(ctx) {
598
+ const out = new Map();
599
+ for (const record of must(ctx, ['ls-files', '--unmerged', '-z']).split('\0')) {
600
+ const tab = record.indexOf('\t');
601
+ if (tab < 0)
602
+ continue;
603
+ const [, sha, stage] = record.slice(0, tab).split(' ');
604
+ const file = record.slice(tab + 1);
605
+ const stages = out.get(file) ?? {};
606
+ if (stage === '1')
607
+ stages.base = sha;
608
+ else if (stage === '2')
609
+ stages.ours = sha;
610
+ else if (stage === '3')
611
+ stages.theirs = sha;
612
+ out.set(file, stages);
613
+ }
614
+ return out;
615
+ }
616
+ // The four lines git writes around a conflict (diff3 style): `<<<<<<< label`,
617
+ // `||||||| label`, `=======` and `>>>>>>> label`, each at the start of a line.
618
+ const MARKER_LINE_RE = /^(?:(?:<{7}|\|{7}|>{7})(?: .*)?|={7})$/;
619
+ function markerLines(text) {
620
+ const found = new Map();
621
+ for (const raw of text.split('\n')) {
622
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
623
+ if (MARKER_LINE_RE.test(line))
624
+ found.set(line, (found.get(line) ?? 0) + 1);
625
+ }
626
+ return found;
627
+ }
628
+ // Whether a conflicted file still carries conflict markers: more of some marker-shaped line
629
+ // than any one of the merged versions had (a Markdown file may have `=======` lines of its
630
+ // own -- but a conflict adds another, so counts are compared, not just which lines occur).
631
+ function stillHasMarkers(ctx, file) {
632
+ let text;
633
+ try {
634
+ text = fs.readFileSync(path.join(ctx.dir, file.path), 'utf-8');
635
+ }
636
+ catch {
637
+ return false;
638
+ }
639
+ const found = markerLines(text);
640
+ if (found.size === 0)
641
+ return false;
642
+ const allowed = new Map();
643
+ for (const sha of Object.values(file.stages)) {
644
+ const blob = sha ? run(ctx, ['cat-file', 'blob', sha]) : null;
645
+ if (blob?.status !== 0)
646
+ continue;
647
+ for (const [line, count] of markerLines(blob.stdout))
648
+ allowed.set(line, Math.max(allowed.get(line) ?? 0, count));
649
+ }
650
+ for (const [line, count] of found)
651
+ if (count > (allowed.get(line) ?? 0))
652
+ return true;
653
+ return false;
654
+ }
655
+ // A conflict git cannot mark up line by line (a binary file, or a file changed on one side
656
+ // and deleted on the other) takes the other computer's side at once. This sandbox's version
657
+ // stays in its own commit, which the instruction names.
658
+ function takeLaptopSide(ctx, file) {
659
+ // A task agent that started since the merge began may be working on this very file: leave
660
+ // it as it is, for the resolver to settle.
661
+ if (deckBusy(ctx))
662
+ return 'manual';
663
+ const spec = literal(file.path);
664
+ if (file.stages.theirs) {
665
+ return ok(ctx, ['checkout', '--theirs', '--', spec]) && ok(ctx, ['add', '--', spec]) ? 'took-laptop' : 'manual';
666
+ }
667
+ return ok(ctx, ['rm', '--quiet', '--force', '--', spec]) ? 'laptop-deleted' : 'manual';
668
+ }
669
+ // The conflicted paths a conclusion checks: those the merge left markers in (or could not
670
+ // resolve on its own), plus anything git still counts as unmerged.
671
+ function conflictsToCheck(ctx) {
672
+ const state = readMergeState(ctx.dir);
673
+ const out = new Map();
674
+ for (const file of state?.files ?? []) {
675
+ if (file.resolution === 'markers' || file.resolution === 'manual')
676
+ out.set(file.path, file);
677
+ }
678
+ for (const [file, stages] of unmergedStages(ctx))
679
+ if (!out.has(file))
680
+ out.set(file, { path: file, stages });
681
+ return [...out.values()];
682
+ }
683
+ function filesWithMarkers(ctx) {
684
+ return conflictsToCheck(ctx)
685
+ .filter((file) => stillHasMarkers(ctx, file))
686
+ .map((file) => file.path);
687
+ }
688
+ function mergeWaitingError(ctx) {
689
+ const files = filesWithMarkers(ctx);
690
+ const where = files.length ? ` (conflict markers remain in: ${files.join(', ')})` : '';
691
+ return new CloudGitError(`A merge with the Castle remote is waiting to be resolved${where}, so nothing was committed. ` +
692
+ 'Once no conflict markers remain, conclude it with `castle-web commit --resolve`.', EXIT_CONFLICT);
693
+ }
694
+ function commitSubjects(ctx, range) {
695
+ const result = run(ctx, ['log', '--format=%h %s', '-n', '20', range]);
696
+ return result.status === 0 ? lines(result.stdout) : [];
697
+ }
698
+ export function conflictInstruction(summary) {
699
+ const list = (items) => (items.length ? items.map((i) => ` - ${i}`).join('\n') : ' (none listed)');
700
+ const marked = summary.files.filter((f) => f.resolution === 'markers' || f.resolution === 'manual').map((f) => f.path);
701
+ const taken = summary.files.filter((f) => f.resolution === 'took-laptop' || f.resolution === 'laptop-deleted');
702
+ const head = summary.head.slice(0, 10);
703
+ const parts = [
704
+ "[Castle] Syncing this deck with its Castle git remote hit a merge conflict: someone pushed to main from another computer (most likely the user's laptop) while this sandbox had changes of its own. Git merged what it could.",
705
+ 'Files with conflict markers (<<<<<<< / ||||||| / ======= / >>>>>>>) to resolve:',
706
+ list(marked),
707
+ ];
708
+ if (taken.length > 0) {
709
+ parts.push(`Files git could not merge line by line (binary, or changed on one side and deleted on the other). The other computer's side was taken for these automatically; this sandbox's version of each is still in commit ${head} (\`git show ${head}:<path>\`):`, list(taken.map((f) => f.resolution === 'took-laptop' ? `${f.path} (took the other computer's version)` : `${f.path} (the other computer deleted it)`)));
710
+ }
711
+ parts.push('What the other computer pushed (castle/main):', list(summary.theirs), 'What was committed here since the two diverged:', list(summary.ours), "Resolve it now. Spawn one task agent to do it, told the following: open each file with conflict markers and remove every marker so the file is whole and working again. Prefer the other computer's side -- keep what was pushed, and redo this sandbox's own change on top of it where it still makes sense; dropping this sandbox's change is acceptable, breaking the pushed work is not. For a file whose other-computer version was taken automatically, bring this sandbox's change back on top only if it still matters. Revert a whole commit from either side only if that is the cleanest way to a working deck. Do not run git reset, rebase, checkout, merge or push, and never force-push. No other commit lands until this merge is concluded. When no markers remain, finish with `castle-web commit --resolve -m \"Merge changes from another computer\"`, which concludes the merge and pushes it; if it exits 3, it names the files that still have markers.", 'Then tell the user in chat, briefly and plainly, that their deck had changes from another computer, what conflicted, and what was kept from each side.');
712
+ return parts.join('\n');
713
+ }
714
+ // A conflicted merge: take the other computer's side where git left no markers, record the
715
+ // rest in .git/castle-merge.json, and write the marker the serve turns into an agent turn.
716
+ function recordConflict(ctx) {
717
+ const head = revParse(ctx, 'HEAD') ?? '';
718
+ const mergeHead = revParse(ctx, 'MERGE_HEAD') ?? '';
719
+ const files = [];
720
+ for (const [file, stages] of unmergedStages(ctx)) {
721
+ const entry = { path: file, stages };
722
+ const kind = !stages.ours || !stages.theirs ? 'modify-delete' : stillHasMarkers(ctx, entry) ? 'text' : 'binary';
723
+ files.push({ ...entry, kind, resolution: kind === 'text' ? 'markers' : takeLaptopSide(ctx, entry) });
724
+ }
725
+ const base = run(ctx, ['merge-base', 'HEAD', 'MERGE_HEAD']).stdout.trim();
726
+ const theirs = commitSubjects(ctx, base ? `${base}..MERGE_HEAD` : 'MERGE_HEAD');
727
+ const ours = commitSubjects(ctx, base ? `${base}..HEAD` : 'HEAD');
728
+ const at = new Date(ctx.deps.now()).toISOString();
729
+ const instruction = conflictInstruction({ files, theirs, ours, head });
730
+ const state = { at, head, mergeHead, files, instruction };
731
+ writeJsonAtomic(mergeStatePath(ctx.dir), state);
732
+ const report = { at, files: files.map((f) => f.path), theirs, ours, instruction };
733
+ writeJsonAtomic(path.join(ctx.dir, CONFLICT_MARKER_FILE), report);
734
+ return state;
735
+ }
736
+ // A path as a commit takes it: inside the deck, and something git can stage -- on disk now,
737
+ // or tracked (a deletion).
738
+ function commitPathspecs(ctx, given) {
739
+ const out = [];
740
+ for (const raw of given) {
741
+ const abs = path.resolve(ctx.dir, raw);
742
+ const rel = path.relative(ctx.dir, abs);
743
+ if (rel === '') {
744
+ out.push('.');
745
+ continue;
746
+ }
747
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
748
+ throw new CloudGitError(`Path is outside the deck: ${raw}`);
749
+ }
750
+ const spec = literal(rel);
751
+ if (fs.existsSync(abs) || ok(ctx, ['ls-files', '--error-unmatch', '--', spec])) {
752
+ out.push(spec);
753
+ }
754
+ else {
755
+ ctx.deps.warn(`Skipping ${raw}: no such file, and git does not track it.`);
756
+ }
757
+ }
758
+ return out;
759
+ }
760
+ function commitMessageArgs(opts, reason) {
761
+ const message = opts.message?.trim() || DEFAULT_MESSAGES[reason];
762
+ const args = ['-m', message];
763
+ if (AGENT_REASONS.has(reason))
764
+ args.push('--trailer', AGENT_TRAILER);
765
+ return args;
766
+ }
767
+ function looseObjectCount(ctx) {
768
+ const match = /^count: (\d+)$/m.exec(must(ctx, ['count-objects', '-v']));
769
+ return match ? Number(match[1]) : 0;
770
+ }
771
+ // Geometric repacking rolls the loose objects into a new pack and merges only small packs,
772
+ // so it stays cheap as history grows (unlike rewriting one big pack every time).
773
+ export function packIfNeeded(ctx) {
774
+ if (looseObjectCount(ctx) <= LOOSE_OBJECT_LIMIT)
775
+ return false;
776
+ const geometric = run(ctx, ['repack', '-d', '-q', '--geometric=2'], { timeoutMs: PACK_TIMEOUT_MS });
777
+ if (geometric.status !== 0)
778
+ must(ctx, ['repack', '-d', '-q'], { timeoutMs: PACK_TIMEOUT_MS });
779
+ must(ctx, ['prune-packed', '-q']);
780
+ return true;
781
+ }
782
+ // After the commit and its sync: only while the command has time left, never on the way out
783
+ // of a deck, and not once asked to stop.
784
+ async function packAfterCommit(ctx, reason) {
785
+ if (reason === 'leave' || ctx.deps.now() - ctx.startedAt > PACK_BUDGET_MS)
786
+ return;
787
+ if (await ctx.deps.stopRequested())
788
+ return;
789
+ try {
790
+ packIfNeeded(ctx);
791
+ }
792
+ catch (e) {
793
+ ctx.deps.warn(`Packing the repo failed (the commit is fine): ${e instanceof Error ? e.message : String(e)}`);
794
+ }
795
+ }
796
+ // Concludes the merge in progress as one whole commit -- only when no conflicted file still
797
+ // has markers. Git refuses a partial commit mid-merge, so named paths are not used.
798
+ function concludeMerge(ctx, opts, reason, identity) {
799
+ const remaining = filesWithMarkers(ctx);
800
+ if (remaining.length > 0) {
801
+ throw new CloudGitError(`Conflict markers remain in: ${remaining.join(', ')}. Remove every one, then run \`castle-web commit --resolve\` again.`, EXIT_CONFLICT);
802
+ }
803
+ if (opts.paths?.length)
804
+ ctx.deps.warn('Concluding a merge commits the whole deck; the paths given were not needed.');
805
+ // Anything a leave commit could not save mid-merge is on disk still, and goes in with it.
806
+ must(ctx, ['add', '-A']);
807
+ // No message of our own keeps git's "Merge changes from another computer" one.
808
+ const trailer = AGENT_REASONS.has(reason) ? ['--trailer', AGENT_TRAILER] : [];
809
+ must(ctx, [
810
+ ...identity,
811
+ 'commit',
812
+ '--quiet',
813
+ '--no-verify',
814
+ ...(opts.message?.trim() ? commitMessageArgs(opts, reason) : ['--no-edit', ...trailer]),
815
+ ]);
816
+ fs.rmSync(mergeStatePath(ctx.dir), { force: true });
817
+ fs.rmSync(path.join(ctx.dir, LEAVE_PENDING_FILE), { force: true });
818
+ }
819
+ export function readLeavePending(dir) {
820
+ try {
821
+ const value = JSON.parse(fs.readFileSync(path.join(dir, LEAVE_PENDING_FILE), 'utf-8'));
822
+ return typeof value.at === 'string' && Array.isArray(value.paths) ? value : null;
823
+ }
824
+ catch {
825
+ return null;
826
+ }
827
+ }
828
+ // A leave commit cannot land mid-merge. The edits stay on disk (and in the deck's checkpoint);
829
+ // this records that they are waiting, so the resolver is told the conclusion saves them too.
830
+ function recordLeavePending(ctx) {
831
+ try {
832
+ const status = run(ctx, ['-c', 'core.quotePath=false', 'status', '--porcelain=v1', '-z', '--untracked-files=all']);
833
+ const paths = status.status === 0 ? parseStatus(status.stdout).map((c) => c.path) : [];
834
+ writeJsonAtomic(path.join(ctx.dir, LEAVE_PENDING_FILE), {
835
+ at: new Date(ctx.deps.now()).toISOString(),
836
+ paths,
837
+ });
838
+ }
839
+ catch (e) {
840
+ ctx.deps.warn(`Could not note the uncommitted edits: ${e instanceof Error ? e.message : String(e)}`);
841
+ }
842
+ }
843
+ async function commitLocked(ctx, opts) {
844
+ const reason = opts.reason ?? 'manual';
845
+ if (mergeInProgress(ctx.dir)) {
846
+ // Nothing but an explicit --resolve lands mid-merge: a turn, task, leave or manual
847
+ // commit would otherwise conclude a merge nobody has checked.
848
+ if (!opts.resolve) {
849
+ if (reason === 'leave')
850
+ recordLeavePending(ctx);
851
+ throw mergeWaitingError(ctx);
852
+ }
853
+ concludeMerge(ctx, opts, reason, await identityArgs(ctx));
854
+ return { sha: revParse(ctx, 'HEAD') };
855
+ }
856
+ // Left behind by a merge concluded (or aborted) some other way.
857
+ fs.rmSync(mergeStatePath(ctx.dir), { force: true });
858
+ fs.rmSync(path.join(ctx.dir, LEAVE_PENDING_FILE), { force: true });
859
+ const identity = await identityArgs(ctx);
860
+ const commit = (extra) => must(ctx, [...identity, 'commit', '--quiet', '--no-verify', ...extra]);
861
+ if (opts.paths && opts.paths.length > 0) {
862
+ const specs = commitPathspecs(ctx, opts.paths);
863
+ if (specs.length === 0)
864
+ return { sha: null };
865
+ must(ctx, ['add', '-A', '--', ...specs]);
866
+ if (ok(ctx, ['diff', '--cached', '--quiet', '--', ...specs]))
867
+ return { sha: null };
868
+ commit([...commitMessageArgs(opts, reason), '--', ...specs]);
869
+ }
870
+ else {
871
+ must(ctx, ['add', '-A']);
872
+ if (ok(ctx, ['diff', '--cached', '--quiet']))
873
+ return { sha: null };
874
+ commit(commitMessageArgs(opts, reason));
875
+ }
876
+ return { sha: revParse(ctx, 'HEAD') };
877
+ }
878
+ function requireMainBranch(ctx) {
879
+ const branch = run(ctx, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
880
+ if (branch.status !== 0 || branch.stdout.trim() !== MAIN) {
881
+ throw new CloudGitError(`The deck's repo is not on branch ${MAIN} (${branch.stdout.trim() || 'detached HEAD'}), so it will not sync.`);
882
+ }
883
+ }
884
+ function fetchRemote(ctx) {
885
+ must(ctx, ['fetch', '--quiet', '--prune', '--no-tags', GIT_REMOTE_NAME], { timeoutMs: NETWORK_TIMEOUT_MS });
886
+ return revParse(ctx, REMOTE_MAIN);
887
+ }
888
+ // Bring castle/main into local main. Local work is already committed by the caller.
889
+ // The mode was chosen when the sync started; a task agent may have started since. Asked again
890
+ // right before any step that writes the working tree, which then waits for the idle commit.
891
+ function deferIfBusy(ctx) {
892
+ if (!deckBusy(ctx))
893
+ return false;
894
+ markSyncPending(ctx);
895
+ ctx.deps.warn('Task agents started working in the deck; the remote\'s changes are merged once it is idle.');
896
+ return true;
897
+ }
898
+ async function integrate(ctx, remote) {
899
+ const head = revParse(ctx, 'HEAD');
900
+ if (!head) {
901
+ if (deferIfBusy(ctx))
902
+ return 'deferred';
903
+ adoptRemote(ctx);
904
+ surfaceAdoptedBackups(ctx);
905
+ return 'fast-forward';
906
+ }
907
+ if (head === remote || ok(ctx, ['merge-base', '--is-ancestor', remote, head]))
908
+ return 'none';
909
+ if (deferIfBusy(ctx))
910
+ return 'deferred';
911
+ if (ok(ctx, ['merge-base', '--is-ancestor', head, remote])) {
912
+ must(ctx, ['merge', '--ff-only', '--quiet', REMOTE_MAIN]);
913
+ return 'fast-forward';
914
+ }
915
+ const identity = await identityArgs(ctx);
916
+ const merge = run(ctx, [
917
+ ...identity,
918
+ 'merge',
919
+ '--no-edit',
920
+ '--no-ff',
921
+ '--quiet',
922
+ '-X',
923
+ 'diff-algorithm=histogram',
924
+ '-m',
925
+ `Merge changes from another computer`,
926
+ REMOTE_MAIN,
927
+ ]);
928
+ if (merge.status === 0)
929
+ return 'merged';
930
+ if (mergeInProgress(ctx.dir) && unmergedStages(ctx).size > 0) {
931
+ const state = recordConflict(ctx);
932
+ ctx.deps.warn(`Merge conflict with the Castle remote in: ${state.files.map((f) => f.path).join(', ')}. Left it for the agent to resolve.`);
933
+ return 'conflict';
934
+ }
935
+ // Refused before it started (an untracked file in the way, say) or failed outright.
936
+ if (mergeInProgress(ctx.dir))
937
+ run(ctx, ['merge', '--abort']);
938
+ throw new CloudGitError(describeFailure(['merge', REMOTE_MAIN], merge));
939
+ }
940
+ function isRejectedPush(result) {
941
+ return /\[rejected\]|non-fast-forward|fetch first|failed to update ref|incorrect old value|cannot lock ref|stale info/i.test(result.stderr);
942
+ }
943
+ const PUSH_ARGS = ['push', '--quiet', GIT_REMOTE_NAME, `${MAIN}:refs/heads/${MAIN}`];
944
+ // Main only, never forced. On success castle/main is moved without another fetch, so the next
945
+ // sync's comparisons hold.
946
+ function pushMain(ctx, local) {
947
+ const push = run(ctx, PUSH_ARGS, { timeoutMs: NETWORK_TIMEOUT_MS });
948
+ if (push.status === 0)
949
+ run(ctx, ['update-ref', REMOTE_MAIN, local]);
950
+ return push;
951
+ }
952
+ function pushOnly(ctx) {
953
+ const local = revParse(ctx, 'HEAD');
954
+ if (!local || local === revParse(ctx, REMOTE_MAIN))
955
+ return { merge: 'none', pushed: false };
956
+ const push = pushMain(ctx, local);
957
+ if (push.status === 0)
958
+ return { merge: 'none', pushed: true };
959
+ if (!isRejectedPush(push))
960
+ throw new CloudGitError(describeFailure(PUSH_ARGS, push));
961
+ markSyncPending(ctx);
962
+ ctx.deps.warn('The Castle remote has changes this sandbox does not have yet; they are merged once the deck is idle.');
963
+ return { merge: 'deferred', pushed: false };
964
+ }
965
+ async function syncLocked(ctx, opts) {
966
+ requireMainBranch(ctx);
967
+ if (opts.commitFirst)
968
+ await commitLocked(ctx, { reason: 'sync' });
969
+ if (mergeInProgress(ctx.dir))
970
+ throw mergeWaitingError(ctx);
971
+ if (opts.mode === 'push-only')
972
+ return pushOnly(ctx);
973
+ let merge = 'none';
974
+ for (let attempt = 0;; attempt++) {
975
+ const remote = fetchRemote(ctx);
976
+ clearSyncPending(ctx);
977
+ const head = revParse(ctx, 'HEAD');
978
+ if (remote) {
979
+ const step = await integrate(ctx, remote);
980
+ if (step === 'conflict' || step === 'deferred')
981
+ return { merge: step, pushed: false };
982
+ if (merge === 'none' || step !== 'none')
983
+ merge = step;
984
+ }
985
+ else if (!head) {
986
+ // An empty remote and nothing committed here: nothing to push yet.
987
+ return { merge, pushed: false };
988
+ }
989
+ else {
990
+ merge = 'seeded';
991
+ }
992
+ const local = revParse(ctx, 'HEAD');
993
+ if (!local || local === revParse(ctx, REMOTE_MAIN))
994
+ return { merge, pushed: false };
995
+ const push = pushMain(ctx, local);
996
+ if (push.status === 0)
997
+ return { merge, pushed: true };
998
+ if (!isRejectedPush(push) || attempt >= PUSH_RETRIES) {
999
+ throw new CloudGitError(describeFailure(PUSH_ARGS, push));
1000
+ }
1001
+ ctx.deps.warn('The Castle remote moved while pushing; fetching and merging again.');
1002
+ }
1003
+ }
1004
+ // Where the files on disk (the restored draft) differ from castle/main, worked out in a
1005
+ // scratch index so the repo's own index and HEAD are untouched until the draft is saved.
1006
+ function draftDifferences(ctx) {
1007
+ const indexFile = path.join(gitDir(ctx.dir), `castle-attach-index-${ctx.deps.pid}`);
1008
+ try {
1009
+ must(ctx, ['read-tree', REMOTE_MAIN], { indexFile });
1010
+ must(ctx, ['add', '-A'], { indexFile });
1011
+ const tokens = must(ctx, ['diff', '--cached', '--name-status', '--no-renames', '-z', REMOTE_MAIN], { indexFile }).split('\0');
1012
+ const out = [];
1013
+ for (let i = 0; i + 1 < tokens.length; i += 2) {
1014
+ const status = tokens[i];
1015
+ const file = tokens[i + 1];
1016
+ if (!status || !file)
1017
+ continue;
1018
+ out.push({ path: file, change: status === 'A' ? 'added' : status === 'D' ? 'deleted' : 'modified' });
1019
+ }
1020
+ return out;
1021
+ }
1022
+ finally {
1023
+ fs.rmSync(indexFile, { force: true });
1024
+ fs.rmSync(`${indexFile}.lock`, { force: true });
1025
+ }
1026
+ }
1027
+ // A byte-for-byte copy of a file (checked after it is written), or of a directory git records
1028
+ // as one entry (a nested repo), file by file. Links are not recreated: a checkpoint leaves
1029
+ // links under .git out, so each is kept as a text record in the manifest instead.
1030
+ function copyVerified(src, dst, rel, links) {
1031
+ const stat = fs.lstatSync(src);
1032
+ if (stat.isSymbolicLink()) {
1033
+ links.push({ path: rel, target: fs.readlinkSync(src) });
1034
+ return;
1035
+ }
1036
+ if (stat.isDirectory()) {
1037
+ fs.mkdirSync(dst, { recursive: true });
1038
+ for (const name of fs.readdirSync(src))
1039
+ copyVerified(path.join(src, name), path.join(dst, name), `${rel}/${name}`, links);
1040
+ return;
1041
+ }
1042
+ if (!stat.isFile())
1043
+ throw new Error(`${rel} is not a regular file`);
1044
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
1045
+ fs.copyFileSync(src, dst);
1046
+ if (!fs.readFileSync(src).equals(fs.readFileSync(dst)))
1047
+ throw new Error(`the copy of ${rel} differs`);
1048
+ }
1049
+ function relSlash(rel) {
1050
+ return rel.split(path.sep).join('/');
1051
+ }
1052
+ // Copies every file of the cloud copy that taking castle/main would replace or remove into
1053
+ // .git/castle-attach-backups/<time>/files/ (never committed), with manifest.json beside it --
1054
+ // outside files/, so a deck file of that name cannot overwrite it. Throws before anything is
1055
+ // touched if any copy fails.
1056
+ function backUpDraft(ctx, diffs, remoteSha) {
1057
+ const stamp = new Date(ctx.deps.now()).toISOString().replace(/[:.]/g, '-');
1058
+ let name = stamp;
1059
+ for (let n = 2; fs.existsSync(path.join(ctx.dir, ATTACH_BACKUPS_DIR, name)); n++)
1060
+ name = `${stamp}-${n}`;
1061
+ const rel = relSlash(path.join(ATTACH_BACKUPS_DIR, name));
1062
+ const root = path.join(ctx.dir, rel);
1063
+ const files = [];
1064
+ const symlinks = [];
1065
+ try {
1066
+ fs.mkdirSync(path.join(root, 'files'), { recursive: true });
1067
+ for (const diff of diffs) {
1068
+ if (diff.change === 'deleted') {
1069
+ files.push({ ...diff, saved: false });
1070
+ continue;
1071
+ }
1072
+ copyVerified(path.join(ctx.dir, diff.path), path.join(root, 'files', diff.path), diff.path, symlinks);
1073
+ files.push({ ...diff, saved: true });
1074
+ }
1075
+ writeJsonAtomic(path.join(root, 'manifest.json'), {
1076
+ createdAt: new Date(ctx.deps.now()).toISOString(),
1077
+ about: "The cloud copy of this deck, as it differed from the Castle git remote's main when the sandbox took the remote's version. `modified` and `added` files are the cloud copy's own, under files/ at the same paths; `deleted` files are ones the cloud copy did not have. Symbolic links are not copied: each is listed under `symlinks` with the target it pointed to.",
1078
+ remoteCommit: remoteSha,
1079
+ files,
1080
+ symlinks,
1081
+ });
1082
+ }
1083
+ catch (e) {
1084
+ fs.rmSync(root, { recursive: true, force: true });
1085
+ throw new CloudGitError(`Could not save the cloud copy's files before taking the remote's version, so nothing was changed: ${e instanceof Error ? e.message : String(e)}`);
1086
+ }
1087
+ return { dir: rel, files };
1088
+ }
1089
+ // A file the draft added (and the backup now holds) goes, and so do the directories it
1090
+ // leaves empty -- a file of the remote's may need that name as a directory, or the reverse.
1091
+ function removeDraftFile(ctx, rel) {
1092
+ const abs = path.join(ctx.dir, rel);
1093
+ try {
1094
+ if (fs.lstatSync(abs).isDirectory())
1095
+ return;
1096
+ fs.rmSync(abs, { force: true });
1097
+ }
1098
+ catch {
1099
+ return;
1100
+ }
1101
+ for (let dir = path.dirname(abs); dir.startsWith(ctx.dir + path.sep); dir = path.dirname(dir)) {
1102
+ try {
1103
+ fs.rmdirSync(dir);
1104
+ }
1105
+ catch {
1106
+ break;
1107
+ }
1108
+ }
1109
+ }
1110
+ function stringList(value) {
1111
+ return Array.isArray(value) ? value.filter((v) => typeof v === 'string' && v.length > 0) : [];
1112
+ }
1113
+ function readAdoptPending(dir) {
1114
+ try {
1115
+ return stringList(JSON.parse(fs.readFileSync(path.join(dir, ADOPT_PENDING_FILE), 'utf-8')).backups);
1116
+ }
1117
+ catch {
1118
+ return [];
1119
+ }
1120
+ }
1121
+ // The backups a notice the serve has not picked up yet already names.
1122
+ function readAdoptedMarkerBackups(dir) {
1123
+ try {
1124
+ return stringList(JSON.parse(fs.readFileSync(path.join(dir, ADOPTED_MARKER_FILE), 'utf-8')).backups);
1125
+ }
1126
+ catch {
1127
+ return [];
1128
+ }
1129
+ }
1130
+ // Old backups go once the agent has been told about them: past ATTACH_BACKUP_MAX_AGE_MS, or
1131
+ // beyond the ATTACH_BACKUP_KEEP newest. One still waiting to be surfaced is never removed.
1132
+ function pruneAttachBackups(ctx) {
1133
+ const root = path.join(ctx.dir, ATTACH_BACKUPS_DIR);
1134
+ let names;
1135
+ try {
1136
+ names = fs.readdirSync(root).sort().reverse();
1137
+ }
1138
+ catch {
1139
+ return;
1140
+ }
1141
+ const keep = new Set([...readAdoptPending(ctx.dir), ...readAdoptedMarkerBackups(ctx.dir)].map((d) => path.posix.basename(d)));
1142
+ names.forEach((name, rank) => {
1143
+ if (keep.has(name))
1144
+ return;
1145
+ const full = path.join(root, name);
1146
+ let created = Number.NaN;
1147
+ try {
1148
+ created = Date.parse(JSON.parse(fs.readFileSync(path.join(full, 'manifest.json'), 'utf-8')).createdAt ?? '');
1149
+ }
1150
+ catch {
1151
+ /* judged by the directory below */
1152
+ }
1153
+ try {
1154
+ if (!Number.isFinite(created))
1155
+ created = fs.statSync(full).mtimeMs;
1156
+ if (rank >= ATTACH_BACKUP_KEEP || ctx.deps.now() - created > ATTACH_BACKUP_MAX_AGE_MS) {
1157
+ fs.rmSync(full, { recursive: true, force: true });
1158
+ }
1159
+ }
1160
+ catch {
1161
+ /* best effort */
1162
+ }
1163
+ });
1164
+ }
1165
+ export function adoptedInstruction(backupDirs) {
1166
+ const where = backupDirs.length === 1
1167
+ ? `was copied to \`${backupDirs[0]}/files/\`, and \`${backupDirs[0]}/manifest.json\` lists`
1168
+ : `was copied, over ${backupDirs.length} attempts, to ${backupDirs.map((d) => `\`${d}/files/\``).join(', ')}; each one's \`manifest.json\` beside files/ lists`;
1169
+ return [
1170
+ `[Castle] When this deck opened in the cloud, its Castle git remote had newer history (most likely pushed from the user's laptop) than the copy saved in the cloud, so the deck now matches the remote's main exactly. Nothing from the cloud copy was thrown away: every file where it differed ${where} each path as modified, added, or deleted (deleted: the cloud copy lacked a file the remote has), and any symbolic links under \`symlinks\`.`,
1171
+ "Usually the cloud copy is just older and there is nothing to do. Have one task agent compare those saved files with the deck's current ones (reading them is fine; never edit or delete the backup folder). Only if the cloud copy has work the current version lacks -- something made in the cloud that never reached the laptop -- carry that work over on top of the current files, never replacing the laptop's newer changes with the older copy, and commit it with `castle-web commit --reason task -m \"<what was carried over>\" <paths>`.",
1172
+ 'Then tell the user in one or two plain sentences that the deck now has the version pushed from their other computer, and whether anything from the cloud copy was carried over.',
1173
+ ].join('\n');
1174
+ }
1175
+ // Turns every backup an attach recorded (this one's, and any an interrupted attach left) into
1176
+ // the notice the serve hands the agent, then clears the record. Only once the deck is the
1177
+ // remote's version: the agent compares the backups against it.
1178
+ function surfaceAdoptedBackups(ctx) {
1179
+ const pending = readAdoptPending(ctx.dir);
1180
+ if (pending.length === 0)
1181
+ return;
1182
+ const backups = [...new Set([...readAdoptedMarkerBackups(ctx.dir), ...pending])].filter((dir) => fs.existsSync(path.join(ctx.dir, dir)));
1183
+ if (backups.length > 0) {
1184
+ writeJsonAtomic(path.join(ctx.dir, ADOPTED_MARKER_FILE), {
1185
+ at: new Date(ctx.deps.now()).toISOString(),
1186
+ backups,
1187
+ notice: `This deck took the newer version pushed from another computer. The cloud copy's differing files were saved in ${backups.join(', ')}; the agent is checking them.`,
1188
+ instruction: adoptedInstruction(backups),
1189
+ });
1190
+ }
1191
+ fs.rmSync(path.join(ctx.dir, ADOPT_PENDING_FILE), { force: true });
1192
+ }
1193
+ // An unborn local main takes castle/main -- history, index and files. The files on disk (the
1194
+ // restored draft) are older than a history someone pushed, so the remote's version wins; every
1195
+ // file of the draft that differs is saved first, and the agent is asked to carry over anything
1196
+ // the remote lacks (surfaceAdoptedBackups, once this has finished).
1197
+ function adoptRemote(ctx) {
1198
+ const remoteSha = revParse(ctx, REMOTE_MAIN);
1199
+ if (!remoteSha)
1200
+ throw new CloudGitError('The Castle remote has no main to take.');
1201
+ if (deckBusy(ctx)) {
1202
+ throw new CloudGitError("Task agents are working in this deck, so it did not take the remote's version yet. Attach again once they finish.");
1203
+ }
1204
+ const diffs = draftDifferences(ctx);
1205
+ pruneAttachBackups(ctx);
1206
+ const backup = diffs.length > 0 ? backUpDraft(ctx, diffs, remoteSha) : null;
1207
+ // The intent, before any file changes: an attach killed from here on leaves this backup
1208
+ // named, and the next attach surfaces it along with its own.
1209
+ if (backup)
1210
+ writeJsonAtomic(path.join(ctx.dir, ADOPT_PENDING_FILE), { backups: [...readAdoptPending(ctx.dir), backup.dir] });
1211
+ for (const diff of diffs)
1212
+ if (diff.change === 'added')
1213
+ removeDraftFile(ctx, diff.path);
1214
+ // The index first, so the hard reset only writes castle/main's own paths: an index left
1215
+ // with entries from an undone seed would otherwise have it delete files outside that list.
1216
+ must(ctx, ['read-tree', REMOTE_MAIN]);
1217
+ must(ctx, ['reset', '--hard', '--quiet', REMOTE_MAIN]);
1218
+ run(ctx, ['branch', '--quiet', `--set-upstream-to=${GIT_REMOTE_NAME}/${MAIN}`, MAIN]);
1219
+ if (backup) {
1220
+ ctx.deps.warn(`Took the Castle remote's version; the cloud copy's ${backup.files.length} differing file(s) are saved in ${backup.dir}.`);
1221
+ }
1222
+ return { backup: backup?.dir ?? null };
1223
+ }
1224
+ // --- the commands -----------------------------------------------------------
1225
+ function contextFor(dir, deps) {
1226
+ const deadline = Number(deps.env[DEADLINE_ENV]);
1227
+ return {
1228
+ dir: path.resolve(dir),
1229
+ deps,
1230
+ startedAt: deps.now(),
1231
+ ...(Number.isFinite(deadline) && deadline > 0 ? { deadline } : {}),
1232
+ };
1233
+ }
1234
+ function syncModeFor(ctx, namedPaths) {
1235
+ return namedPaths || deckBusy(ctx) ? 'push-only' : 'full';
1236
+ }
1237
+ // A sync that fails after a commit landed is a warning, not a failure: the commit is safe
1238
+ // locally and the next sync pushes it. A conflict still surfaces (exit 3).
1239
+ async function syncAfterCommit(ctx, mode) {
1240
+ if (await ctx.deps.stopRequested())
1241
+ return { sync: null, syncError: 'Stopped before syncing.' };
1242
+ try {
1243
+ return { sync: await syncLocked(ctx, { commitFirst: false, mode }) };
1244
+ }
1245
+ catch (e) {
1246
+ if (e instanceof CloudGitError && e.exitCode === EXIT_CONFLICT)
1247
+ throw e;
1248
+ return { sync: null, syncError: e instanceof Error ? e.message : String(e) };
1249
+ }
1250
+ }
1251
+ /**
1252
+ * `castle-web commit`: commit, then sync. With named paths, or while the deck is busy, the
1253
+ * sync only pushes (see SyncMode). The serve's commits skip the network when they committed
1254
+ * nothing and there is nothing to push and no laptop push waiting.
1255
+ */
1256
+ export async function cloudCommit(dir, opts, deps) {
1257
+ const ctx = contextFor(dir, deps);
1258
+ requireAttached(ctx, 'commit');
1259
+ return withDeckLock(ctx, async () => {
1260
+ const reason = opts.reason ?? 'manual';
1261
+ const outcome = await commitLocked(ctx, opts);
1262
+ if (reason === 'sync')
1263
+ return { ...outcome, sync: null };
1264
+ const quiet = QUIET_REASONS.has(reason) &&
1265
+ !opts.resolve &&
1266
+ !outcome.sha &&
1267
+ revParse(ctx, 'HEAD') === revParse(ctx, REMOTE_MAIN) &&
1268
+ !syncPending(ctx);
1269
+ if (quiet)
1270
+ return { ...outcome, sync: null };
1271
+ const after = await syncAfterCommit(ctx, syncModeFor(ctx, (opts.paths?.length ?? 0) > 0));
1272
+ await packAfterCommit(ctx, reason);
1273
+ return { ...outcome, ...after };
1274
+ });
1275
+ }
1276
+ /**
1277
+ * `castle-web git sync`: commit work in progress, bring in castle/main, push. While the deck
1278
+ * is busy it only notes that a sync is waiting: the board-idle commit does it.
1279
+ */
1280
+ export async function cloudSync(dir, deps) {
1281
+ const ctx = contextFor(dir, deps);
1282
+ requireAttached(ctx, 'git sync');
1283
+ return withDeckLock(ctx, async () => {
1284
+ if (deckBusy(ctx)) {
1285
+ markSyncPending(ctx);
1286
+ return { merge: 'deferred', pushed: false };
1287
+ }
1288
+ return syncLocked(ctx, { commitFirst: true, mode: 'full' });
1289
+ });
1290
+ }
1291
+ /**
1292
+ * Restore the deck to an earlier commit as a NEW commit on top: history is never rewritten,
1293
+ * so the restore can itself be restored away. Work in progress is committed first, so
1294
+ * nothing on disk is lost by restoring.
1295
+ */
1296
+ export async function cloudRestore(dir, target, deps) {
1297
+ const ctx = contextFor(dir, deps);
1298
+ requireAttached(ctx, 'restore-version');
1299
+ return withDeckLock(ctx, async () => {
1300
+ requireMainBranch(ctx);
1301
+ const sha = revParse(ctx, target);
1302
+ if (!sha || !ok(ctx, ['merge-base', '--is-ancestor', sha, 'HEAD'])) {
1303
+ throw new CloudGitError(`No such version in this deck's history: ${target}`);
1304
+ }
1305
+ // Rewriting the files under a task agent at work would mix its edits into the old version:
1306
+ // asked before anything is done, and again right before the files are rewritten.
1307
+ const refuseIfBusy = () => {
1308
+ if (deckBusy(ctx)) {
1309
+ throw new CloudGitError('Task agents are working in this deck, so it was not restored. Restore it once they finish.');
1310
+ }
1311
+ };
1312
+ refuseIfBusy();
1313
+ await commitLocked(ctx, { reason: 'manual', message: 'Work in progress before restoring a version' });
1314
+ const subject = must(ctx, ['log', '-1', '--format=%s', sha]).trim();
1315
+ refuseIfBusy();
1316
+ must(ctx, ['read-tree', '-u', '--reset', sha]);
1317
+ const outcome = await commitLocked(ctx, {
1318
+ reason: 'manual',
1319
+ message: `Restore version ${sha.slice(0, 7)}${subject ? `: ${subject}` : ''}`,
1320
+ });
1321
+ return { ...outcome, ...(await syncAfterCommit(ctx, syncModeFor(ctx, false))) };
1322
+ });
1323
+ }
1324
+ // --- attach -----------------------------------------------------------------
1325
+ const CASTLE_REMOTE_RE = /^https:\/\/([a-z0-9.-]+)\/([A-Za-z0-9_-]{1,64})\.git$/;
1326
+ function parseRemoteUrl(url) {
1327
+ const match = CASTLE_REMOTE_RE.exec(url);
1328
+ const hosts = new Set(Object.values(GIT_HOSTS));
1329
+ if (!match || !hosts.has(match[1])) {
1330
+ throw new CloudGitError(`Not a Castle git remote: ${url} (expected https://${GIT_HOSTS.production}/<deckId>.git or the staging host).`);
1331
+ }
1332
+ return { deckId: match[2] };
1333
+ }
1334
+ function readDeckId(dir) {
1335
+ try {
1336
+ const parsed = JSON.parse(fs.readFileSync(path.join(dir, 'castle.json'), 'utf-8'));
1337
+ return typeof parsed.deckId === 'string' && parsed.deckId ? parsed.deckId : null;
1338
+ }
1339
+ catch {
1340
+ return null;
1341
+ }
1342
+ }
1343
+ function sameRealPath(a, b) {
1344
+ try {
1345
+ return fs.realpathSync(a) === fs.realpathSync(b);
1346
+ }
1347
+ catch {
1348
+ return path.resolve(a) === path.resolve(b);
1349
+ }
1350
+ }
1351
+ // The deck dir must be its own repo, or no repo at all -- never a `.git` file pointing
1352
+ // elsewhere (a worktree or submodule) and never inside another repo, whose whole history
1353
+ // the castle remote would then receive.
1354
+ function ensureOwnRepo(ctx) {
1355
+ const dotGit = gitDir(ctx.dir);
1356
+ let stat = null;
1357
+ try {
1358
+ stat = fs.lstatSync(dotGit);
1359
+ }
1360
+ catch {
1361
+ stat = null;
1362
+ }
1363
+ if (stat && !stat.isDirectory()) {
1364
+ throw new CloudGitError(`${dotGit} is not a directory (a gitdir file or link); refusing to attach.`);
1365
+ }
1366
+ const top = run(ctx, ['rev-parse', '--show-toplevel']);
1367
+ if (stat) {
1368
+ if (top.status !== 0)
1369
+ throw new CloudGitError(`git cannot read the repo at ${ctx.dir}: ${top.stderr.trim()}`);
1370
+ if (!sameRealPath(top.stdout.trim(), ctx.dir)) {
1371
+ throw new CloudGitError(`${ctx.dir} is inside the git repo at ${top.stdout.trim()}; refusing to attach.`);
1372
+ }
1373
+ return 'existing';
1374
+ }
1375
+ if (top.status === 0) {
1376
+ throw new CloudGitError(`${ctx.dir} is inside the git repo at ${top.stdout.trim()}; refusing to attach.`);
1377
+ }
1378
+ if (!/not a git repository/i.test(top.stderr)) {
1379
+ throw new CloudGitError(`git cannot tell whether ${ctx.dir} is in a repo: ${top.stderr.trim()}`);
1380
+ }
1381
+ must(ctx, ['init', '--quiet', `--initial-branch=${MAIN}`]);
1382
+ return 'created';
1383
+ }
1384
+ // A copied deck brings the original's repo along, attached to the original's remote. Its
1385
+ // cloud config (remote, identity, attached mark) is the original's, so it is dropped and the
1386
+ // copy attaches afresh; the history itself stays.
1387
+ //
1388
+ // Known gap: that kept history is the original deck's, so the copy's first push (onto an empty
1389
+ // remote) publishes the original's whole history to the copy's remote. Both belong to the same
1390
+ // user today; starting the copy on a fresh history instead is left for a later change.
1391
+ function forgetOtherDecksRemote(ctx, deckId) {
1392
+ const current = configuredRemoteUrl(ctx);
1393
+ if (current === null)
1394
+ return null;
1395
+ const other = CASTLE_REMOTE_RE.exec(current)?.[2];
1396
+ if (!other || other === deckId)
1397
+ return null;
1398
+ must(ctx, ['remote', 'remove', GIT_REMOTE_NAME]);
1399
+ for (const key of ['castle.cloud', 'castle.seed', 'user.name', 'user.email']) {
1400
+ run(ctx, ['config', '--local', '--unset-all', key]);
1401
+ }
1402
+ fs.rmSync(mergeStatePath(ctx.dir), { force: true });
1403
+ return other;
1404
+ }
1405
+ // Local main, whatever the repo started on: an unborn HEAD is pointed at main; a born one on
1406
+ // another branch is renamed when main does not exist yet.
1407
+ function ensureMainBranch(ctx) {
1408
+ const branch = run(ctx, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
1409
+ const current = branch.status === 0 ? branch.stdout.trim() : '';
1410
+ if (current === MAIN)
1411
+ return;
1412
+ if (!revParse(ctx, 'HEAD')) {
1413
+ must(ctx, ['symbolic-ref', 'HEAD', `refs/heads/${MAIN}`]);
1414
+ return;
1415
+ }
1416
+ if (current && !revParse(ctx, `refs/heads/${MAIN}`)) {
1417
+ must(ctx, ['branch', '-m', current, MAIN]);
1418
+ return;
1419
+ }
1420
+ throw new CloudGitError(`The deck's repo is on ${current || 'a detached HEAD'}, not ${MAIN}; refusing to attach over it.`);
1421
+ }
1422
+ // The URL as configured: `git remote get-url` would apply the container's insteadOf rewrite.
1423
+ function configuredRemoteUrl(ctx) {
1424
+ return localConfig(ctx, `remote.${GIT_REMOTE_NAME}.url`);
1425
+ }
1426
+ function setCastleRemote(ctx, url) {
1427
+ const current = configuredRemoteUrl(ctx);
1428
+ if (current === null) {
1429
+ must(ctx, ['remote', 'add', GIT_REMOTE_NAME, url]);
1430
+ }
1431
+ else if (current !== url) {
1432
+ must(ctx, ['remote', 'set-url', GIT_REMOTE_NAME, url]);
1433
+ }
1434
+ // A pushurl would send pushes somewhere else.
1435
+ run(ctx, ['config', '--local', '--unset-all', `remote.${GIT_REMOTE_NAME}.pushurl`]);
1436
+ }
1437
+ // An empty `credential.<url>.helper` in the repo's config resets the helper list, which would
1438
+ // cancel the helper the container's env config installs. Only empty ones go.
1439
+ function stripEmptyCredentialHelpers(ctx) {
1440
+ const listed = run(ctx, ['config', '--local', '--null', '--get-regexp', '^credential\\..*helper$']);
1441
+ if (listed.status !== 0)
1442
+ return [];
1443
+ const empties = new Set();
1444
+ for (const entry of listed.stdout.split('\0')) {
1445
+ if (!entry)
1446
+ continue;
1447
+ const nl = entry.indexOf('\n');
1448
+ const key = nl >= 0 ? entry.slice(0, nl) : entry;
1449
+ const value = nl >= 0 ? entry.slice(nl + 1) : '';
1450
+ if (value === '')
1451
+ empties.add(key);
1452
+ }
1453
+ for (const key of empties)
1454
+ must(ctx, ['config', '--local', '--unset-all', key, '^$']);
1455
+ return [...empties];
1456
+ }
1457
+ export function writeCloudExcludes(dir) {
1458
+ const file = path.join(gitDir(dir), 'info', 'exclude');
1459
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1460
+ let existing = '';
1461
+ try {
1462
+ existing = fs.readFileSync(file, 'utf-8');
1463
+ }
1464
+ catch {
1465
+ existing = '';
1466
+ }
1467
+ const have = new Set(existing.split('\n').map((l) => l.trim()));
1468
+ const missing = CLOUD_EXCLUDES.filter((line) => !have.has(line));
1469
+ if (missing.length === 0)
1470
+ return;
1471
+ const prefix = existing && !existing.endsWith('\n') ? '\n' : '';
1472
+ fs.appendFileSync(file, `${prefix}# Castle cloud sandbox\n${missing.join('\n')}\n`);
1473
+ }
1474
+ /** `castle-web git attach <dir> --remote <url>`. */
1475
+ export async function cloudAttach(dir, remoteUrl, deps) {
1476
+ requireSandbox(deps, 'git attach');
1477
+ const ctx = contextFor(dir, deps);
1478
+ try {
1479
+ if (!fs.statSync(ctx.dir).isDirectory())
1480
+ throw new Error('not a directory');
1481
+ }
1482
+ catch {
1483
+ throw new CloudGitError(`${ctx.dir} does not exist.`);
1484
+ }
1485
+ if (!fs.existsSync(path.join(ctx.dir, 'castle.json'))) {
1486
+ throw new CloudGitError(`${ctx.dir} has no castle.json, so it isn't a Castle deck.`);
1487
+ }
1488
+ const { deckId } = parseRemoteUrl(remoteUrl);
1489
+ const ownDeckId = readDeckId(ctx.dir);
1490
+ if (ownDeckId && ownDeckId !== deckId) {
1491
+ throw new CloudGitError(`${remoteUrl} is deck ${deckId}'s remote, but this deck is ${ownDeckId}.`);
1492
+ }
1493
+ must(ctx, ['--version']);
1494
+ const repo = ensureOwnRepo(ctx);
1495
+ const original = forgetOtherDecksRemote(ctx, deckId);
1496
+ if (original)
1497
+ deps.warn(`This repo was attached to deck ${original}'s remote (a copied deck); attaching it to ${deckId}'s instead.`);
1498
+ ensureMainBranch(ctx);
1499
+ setCastleRemote(ctx, remoteUrl);
1500
+ const stripped = stripEmptyCredentialHelpers(ctx);
1501
+ if (stripped.length)
1502
+ deps.log(`Removed empty credential helpers: ${stripped.join(', ')}`);
1503
+ writeCloudExcludes(ctx.dir);
1504
+ must(ctx, ['config', '--local', 'gc.autoDetach', 'false']);
1505
+ // Git publishes a new object by hard-linking its temp file by default; a draft checkpoint
1506
+ // that pauses the container in between refuses the hard link. Renaming has no such moment.
1507
+ must(ctx, ['config', '--local', 'core.createObject', 'rename']);
1508
+ // The base in conflict markers is what lets the agent see what each side changed.
1509
+ must(ctx, ['config', '--local', 'merge.conflictStyle', 'diff3']);
1510
+ return withDeckLock(ctx, async () => {
1511
+ const outcome = await firstSync(ctx, repo);
1512
+ // Marked attached only once the repo shares history with the remote: a deck whose
1513
+ // first fetch failed must not start a local history of its own, which the next attach
1514
+ // could not merge. The next open retries the whole attach.
1515
+ must(ctx, ['config', '--local', 'castle.cloud', 'true']);
1516
+ return outcome;
1517
+ });
1518
+ }
1519
+ // The seed commit an attach made for an empty remote, until it is pushed. Should the push
1520
+ // fail (or the process die first), the commit is undone so the next attach starts from an
1521
+ // unborn main again: it then takes whatever the remote has by then, where keeping the seed
1522
+ // would leave two unrelated histories that no merge can join.
1523
+ const SEED_KEY = 'castle.seed';
1524
+ function undoUnpushedSeed(ctx) {
1525
+ const seed = localConfig(ctx, SEED_KEY);
1526
+ if (!seed)
1527
+ return;
1528
+ if (!localConfig(ctx, 'castle.cloud') && revParse(ctx, 'HEAD') === seed) {
1529
+ // Only this exact commit: update-ref refuses if main has moved on from it.
1530
+ if (ok(ctx, ['update-ref', '-d', `refs/heads/${MAIN}`, seed])) {
1531
+ ctx.deps.warn('Undid the first commit of an attach that never reached the remote; the files are unchanged.');
1532
+ }
1533
+ }
1534
+ run(ctx, ['config', '--local', '--unset-all', SEED_KEY]);
1535
+ }
1536
+ async function firstSync(ctx, repo) {
1537
+ undoUnpushedSeed(ctx);
1538
+ const remote = fetchRemote(ctx);
1539
+ const head = revParse(ctx, 'HEAD');
1540
+ if (!remote) {
1541
+ if (!head) {
1542
+ const seed = await commitLocked(ctx, { reason: 'sync', message: 'Start of history' });
1543
+ if (seed.sha)
1544
+ must(ctx, ['config', '--local', SEED_KEY, seed.sha]);
1545
+ }
1546
+ let sync;
1547
+ try {
1548
+ sync = await syncLocked(ctx, { commitFirst: true, mode: 'full' });
1549
+ }
1550
+ catch (e) {
1551
+ undoUnpushedSeed(ctx);
1552
+ throw e;
1553
+ }
1554
+ run(ctx, ['config', '--local', '--unset-all', SEED_KEY]);
1555
+ run(ctx, ['branch', '--quiet', `--set-upstream-to=${GIT_REMOTE_NAME}/${MAIN}`, MAIN]);
1556
+ surfaceAdoptedBackups(ctx);
1557
+ return { repo, outcome: 'seeded', sync };
1558
+ }
1559
+ if (!head) {
1560
+ const { backup } = adoptRemote(ctx);
1561
+ surfaceAdoptedBackups(ctx);
1562
+ const sync = await syncLocked(ctx, { commitFirst: false, mode: 'full' });
1563
+ return { repo, outcome: 'adopted', sync, ...(backup ? { backup } : {}) };
1564
+ }
1565
+ // An earlier attach took the remote's version but was stopped before telling the agent.
1566
+ surfaceAdoptedBackups(ctx);
1567
+ // Reopened while tasks are working: their half-done files are not committed or merged into.
1568
+ const mode = syncModeFor(ctx, false);
1569
+ return { repo, outcome: 'synced', sync: await syncLocked(ctx, { commitFirst: mode === 'full', mode }) };
1570
+ }
1571
+ const RECORD = '\x1e';
1572
+ const FIELD = '\x1f';
1573
+ function kindOf(status) {
1574
+ if (status.startsWith('A'))
1575
+ return 'added';
1576
+ if (status.startsWith('D'))
1577
+ return 'deleted';
1578
+ return 'changed';
1579
+ }
1580
+ export function parseGitLog(output) {
1581
+ const entries = [];
1582
+ for (const chunk of output.split(RECORD)) {
1583
+ if (!chunk.trim())
1584
+ continue;
1585
+ const [header, ...rest] = chunk.replace(/^\n+/, '').split('\n');
1586
+ const [id, parents, createdAt, author, subject, agent] = header.split(FIELD);
1587
+ if (!id)
1588
+ continue;
1589
+ const changes = [];
1590
+ for (const line of rest) {
1591
+ if (!line.trim())
1592
+ continue;
1593
+ const parts = line.split('\t');
1594
+ const status = parts[0];
1595
+ if (status.startsWith('R') && parts.length >= 3) {
1596
+ changes.push({ path: parts[1], kind: 'deleted' }, { path: parts[2], kind: 'added' });
1597
+ }
1598
+ else if (parts.length >= 2) {
1599
+ changes.push({ path: parts[parts.length - 1], kind: kindOf(status) });
1600
+ }
1601
+ }
1602
+ entries.push({
1603
+ id,
1604
+ parentId: parents?.split(' ')[0] || null,
1605
+ createdAt: createdAt ?? '',
1606
+ message: subject ?? '',
1607
+ author: author ?? '',
1608
+ agent: agent?.trim() ? agent.trim() : null,
1609
+ changes: changes.filter((c) => c.path !== COVER_FILE),
1610
+ later: false,
1611
+ });
1612
+ }
1613
+ return entries;
1614
+ }
1615
+ export function parseStatus(output) {
1616
+ const out = [];
1617
+ const records = output.split('\0');
1618
+ for (let i = 0; i < records.length; i++) {
1619
+ const record = records[i];
1620
+ if (record.length < 4)
1621
+ continue;
1622
+ const xy = record.slice(0, 2);
1623
+ const file = record.slice(3);
1624
+ // A rename's second record is its source path.
1625
+ if (xy[0] === 'R' || xy[0] === 'C')
1626
+ i++;
1627
+ if (file === COVER_FILE)
1628
+ continue;
1629
+ const kind = xy === '??' || xy.includes('A') ? 'added' : xy.includes('D') ? 'deleted' : 'changed';
1630
+ out.push({ path: file, kind });
1631
+ }
1632
+ return out;
1633
+ }
1634
+ const LOG_LIMIT = 200;
1635
+ function logArgs(from, limit) {
1636
+ return [
1637
+ '-c',
1638
+ 'core.quotePath=false',
1639
+ 'log',
1640
+ '-n',
1641
+ String(limit),
1642
+ '--diff-merges=first-parent',
1643
+ '--name-status',
1644
+ `--format=${RECORD}%H${FIELD}%P${FIELD}%aI${FIELD}%an${FIELD}%s${FIELD}%(trailers:key=${AGENT_TRAILER_KEY},valueonly,separator=%x2C)`,
1645
+ from,
1646
+ ];
1647
+ }
1648
+ function readGitLog(ctx, from, limit) {
1649
+ return parseGitLog(must(ctx, logArgs(from, limit)));
1650
+ }
1651
+ /**
1652
+ * The Versions panel's picture with git on: the log and `git status` as pending. Async, since
1653
+ * the IDE server's event loop must not wait on git, and without optional locks, so a panel
1654
+ * refresh never holds the index lock a commit needs.
1655
+ */
1656
+ export async function gitVersionHistory(dir, env = process.env) {
1657
+ const git = async (args) => {
1658
+ const result = await runGitAsync(['--no-optional-locks', ...args], dir, env);
1659
+ if (result.status !== 0)
1660
+ throw new CloudGitError(describeFailure(args, result));
1661
+ return result.stdout;
1662
+ };
1663
+ const head = await runGitAsync(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], dir, env);
1664
+ const versions = head.status === 0 ? parseGitLog(await git(logArgs('HEAD', LOG_LIMIT))) : [];
1665
+ const status = await git(['status', '--porcelain=v1', '-z', '--untracked-files=all']);
1666
+ return { versions, pending: parseStatus(status) };
1667
+ }
1668
+ // `list-versions` and `show-version` with git on: the same history the panel shows, for an
1669
+ // agent working out what recent work did.
1670
+ export function printGitLog(dir, from, git = cloudGitRunner()) {
1671
+ const ctx = { dir, deps: { git }, startedAt: 0 };
1672
+ if (!revParse(ctx, from ?? 'HEAD')) {
1673
+ console.log(from ? `No such version: ${from}` : 'No versions yet.');
1674
+ return;
1675
+ }
1676
+ for (const v of readGitLog(ctx, from ?? 'HEAD', 50)) {
1677
+ const count = v.changes.length;
1678
+ const by = v.agent ? `${v.author} (agent: ${v.agent})` : v.author;
1679
+ console.log(`${v.id.slice(0, 10)} ${v.createdAt} ${count} file${count === 1 ? '' : 's'} ${by} ${v.message}`);
1680
+ }
1681
+ }
1682
+ export function printGitShow(dir, target, git = cloudGitRunner()) {
1683
+ const ctx = { dir, deps: { git }, startedAt: 0 };
1684
+ if (!revParse(ctx, target))
1685
+ throw new CloudGitError(`No such version: ${target}`);
1686
+ process.stdout.write(must(ctx, ['-c', 'core.quotePath=false', 'show', '--stat', '--patch', '--diff-merges=first-parent', target]));
1687
+ }