castle-web-cli 0.4.227 → 0.4.229

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 (42) hide show
  1. package/dist/agent-prompts.d.ts +9 -3
  2. package/dist/agent-prompts.js +140 -48
  3. package/dist/agent.js +127 -14
  4. package/dist/api.d.ts +37 -0
  5. package/dist/api.js +29 -0
  6. package/dist/castle-host/host.d.ts +6 -0
  7. package/dist/castle-host/host.js +42 -3
  8. package/dist/castleJson.d.ts +15 -0
  9. package/dist/castleJson.js +136 -3
  10. package/dist/cloudGit.d.ts +27 -1
  11. package/dist/cloudGit.js +359 -24
  12. package/dist/cloudGitServe.js +9 -5
  13. package/dist/gitCollaborators.d.ts +16 -0
  14. package/dist/gitCollaborators.js +42 -0
  15. package/dist/gitIncoming.d.ts +17 -0
  16. package/dist/gitIncoming.js +113 -0
  17. package/dist/gitRemote.js +2 -2
  18. package/dist/imports.js +4 -2
  19. package/dist/index.js +5 -0
  20. package/dist/init.js +1 -1
  21. package/dist/native/playtest-browser.js +13 -1
  22. package/dist/platformDoc.js +1 -1
  23. package/dist/save-deck.js +3 -0
  24. package/dist/serve.js +17 -0
  25. package/dist/shell/assets/index-Cf61cNfT.css +1 -0
  26. package/dist/shell/assets/{index-D006JHww.js → index-D2tWM896.js} +71 -71
  27. package/dist/shell/index.html +2 -2
  28. package/dist/sourceLineage.d.ts +42 -0
  29. package/dist/sourceLineage.js +380 -0
  30. package/dist/webSourceSync.d.ts +9 -0
  31. package/dist/webSourceSync.js +24 -9
  32. package/kits/base/castle.json +1 -1
  33. package/kits/base/sdk/README.md +81 -0
  34. package/kits/base/sdk/castle.d.ts +1 -1
  35. package/kits/base/sdk/commands.d.ts +6 -0
  36. package/kits/base/sdk/multiplayer.d.ts +44 -6
  37. package/kits/base/sdk/multiplayer.js +62 -1
  38. package/kits/base/sdk/server/platformHandle.d.ts +9 -1
  39. package/kits/base/sdk/server/wrapper.d.ts +111 -4
  40. package/kits/base/sdk/server/wrapper.js +650 -24
  41. package/package.json +10 -2
  42. package/dist/shell/assets/index-BxDYy_-C.css +0 -1
@@ -10,8 +10,8 @@
10
10
  <link rel="icon" type="image/png" sizes="32x32" href="/__castle/ide/favicon-32x32.png" />
11
11
  <link rel="icon" type="image/png" sizes="16x16" href="/__castle/ide/favicon-16x16.png" />
12
12
  <link rel="icon" href="/__castle/ide/favicon.ico" sizes="any" />
13
- <script type="module" crossorigin src="/__castle/ide/assets/index-D006JHww.js"></script>
14
- <link rel="stylesheet" crossorigin href="/__castle/ide/assets/index-BxDYy_-C.css">
13
+ <script type="module" crossorigin src="/__castle/ide/assets/index-D2tWM896.js"></script>
14
+ <link rel="stylesheet" crossorigin href="/__castle/ide/assets/index-Cf61cNfT.css">
15
15
  </head>
16
16
  <body>
17
17
  <div id="root"></div>
@@ -0,0 +1,42 @@
1
+ import * as api from './api.js';
2
+ import type { ServerSourceVersion } from './webSourceSync.js';
3
+ export declare const LINEAGE_BUDGET_MS = 9000;
4
+ /** path (posix, relative) -> sha256 hex */
5
+ export type SourceManifest = Map<string, string>;
6
+ /** Whether a source path counts toward a match: skips noise, dotfiles at the top, `._*`. */
7
+ export declare function countsTowardMatch(rel: string): boolean;
8
+ /**
9
+ * The folder's regular files as the archive would carry them, hashed in chunks; null past the
10
+ * size caps or once `expired` says the time is up.
11
+ */
12
+ export declare function folderManifest(dir: string, expired?: () => boolean): SourceManifest | null;
13
+ /**
14
+ * The regular files of a gzipped tar, hashed as they stream (ustar, pax `path`, GNU long
15
+ * names). Links and everything else are skipped; nothing is written to disk.
16
+ */
17
+ export declare function archiveManifest(gz: Buffer, expired?: () => boolean): Promise<SourceManifest>;
18
+ /** How many files the two copies hold identically. */
19
+ export declare function matchScore(folder: SourceManifest, saved: SourceManifest): number;
20
+ export type LineageOutcome = 'current' | 'older' | 'skipped';
21
+ export interface Lineage {
22
+ outcome: LineageOutcome;
23
+ /** The version to record: the current one unless an older one matches strictly better. */
24
+ version: ServerSourceVersion;
25
+ /** Saved versions compared (the current one included). */
26
+ examined: number;
27
+ /** Why the history was not compared, or why the comparison stopped early. */
28
+ reason?: string;
29
+ }
30
+ export interface LineageDeps {
31
+ listVersions?: (deckId: string, timeoutMs: number) => Promise<api.SavedSourceVersion[]>;
32
+ fetchArchive?: (url: string, timeoutMs: number) => Promise<Buffer>;
33
+ nowMs?: () => number;
34
+ /** When the comparison must be settled by (epoch ms); defaults to now + LINEAGE_BUDGET_MS. */
35
+ deadlineMs?: number;
36
+ }
37
+ /**
38
+ * The saved version this folder descends from. Never throws: any failure (an older Ghost,
39
+ * a fetch error, the budget) settles on the current version, which is what adopt recorded
40
+ * before this existed.
41
+ */
42
+ export declare function findLineage(dir: string, deckId: string, server: ServerSourceVersion, deps?: LineageDeps): Promise<Lineage>;
@@ -0,0 +1,380 @@
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as zlib from 'zlib';
5
+ import * as api from './api.js';
6
+ // Which saved version a folder with no sync record came from. Without this, `source-status
7
+ // --adopt` records the deck's current saved version, which is right for a folder that was
8
+ // fetched from it and wrong for one copied from an older save (the Sep 13-14 legacy-home
9
+ // import left a few dozen such folders behind a save made elsewhere): adopting the current
10
+ // key would let the folder's next save overwrite the newer copy without a word.
11
+ //
12
+ // Every save is kept under its own key, so the folder is compared with the deck's saved
13
+ // versions by identical path + sha256. An older version is adopted only when it matches
14
+ // strictly more files than the current one; a folder that grew, shrank or was reworked since
15
+ // the current save still matches the current save best. Bounded by time and bytes: whatever
16
+ // is not settled within the budget falls back to the current version, as before.
17
+ /** Files that differ between any two copies of the same work: tooling rewrites and metadata. */
18
+ const NOISE_FILES = new Set([
19
+ 'castle.json',
20
+ 'package.json',
21
+ 'package-lock.json',
22
+ 'pnpm-lock.yaml',
23
+ 'pnpm-workspace.yaml',
24
+ 'CLAUDE.md',
25
+ 'AGENTS.md',
26
+ 'fonts.generated.js',
27
+ 'preview.png',
28
+ ]);
29
+ /** Top-level entries the archive leaves out (save-deck SOURCE_ARCHIVE_EXCLUDES). */
30
+ const ARCHIVE_EXCLUDES = new Set(['node_modules', 'dist', '.castle', '.git', 'imports']);
31
+ // Measured from when source-status starts, so its own source query counts too: castle-www's
32
+ // open gives the --adopt and --notify calls 15 s between them.
33
+ export const LINEAGE_BUDGET_MS = 9_000;
34
+ const MAX_VERSIONS_EXAMINED = 20;
35
+ const MAX_ARCHIVE_BYTES_TOTAL = 200 * 1024 * 1024;
36
+ const MAX_UNPACKED_BYTES = 512 * 1024 * 1024;
37
+ const MAX_FOLDER_FILES = 20_000;
38
+ const MAX_FOLDER_BYTES = 512 * 1024 * 1024;
39
+ /** Whether a source path counts toward a match: skips noise, dotfiles at the top, `._*`. */
40
+ export function countsTowardMatch(rel) {
41
+ const parts = rel.split('/');
42
+ if (parts.some((part) => part === '' || part === '.' || part === '..'))
43
+ return false;
44
+ if (parts[0].startsWith('.') || ARCHIVE_EXCLUDES.has(parts[0]))
45
+ return false;
46
+ if (parts.includes('node_modules'))
47
+ return false;
48
+ const base = parts[parts.length - 1];
49
+ if (base.startsWith('._'))
50
+ return false;
51
+ if (parts.length === 1 && NOISE_FILES.has(base))
52
+ return false;
53
+ return true;
54
+ }
55
+ class LineageLimit extends Error {
56
+ }
57
+ const HASH_CHUNK_BYTES = 1024 * 1024;
58
+ function hashFile(file, expired) {
59
+ const hash = crypto.createHash('sha256');
60
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
61
+ try {
62
+ const chunk = Buffer.allocUnsafe(HASH_CHUNK_BYTES);
63
+ for (;;) {
64
+ if (expired())
65
+ throw new LineageLimit('budget');
66
+ const read = fs.readSync(fd, chunk, 0, chunk.length, null);
67
+ if (read === 0)
68
+ break;
69
+ hash.update(chunk.subarray(0, read));
70
+ }
71
+ }
72
+ finally {
73
+ fs.closeSync(fd);
74
+ }
75
+ return hash.digest('hex');
76
+ }
77
+ /**
78
+ * The folder's regular files as the archive would carry them, hashed in chunks; null past the
79
+ * size caps or once `expired` says the time is up.
80
+ */
81
+ export function folderManifest(dir, expired = () => false) {
82
+ const out = new Map();
83
+ let bytes = 0;
84
+ const walk = (rel) => {
85
+ for (const entry of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
86
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
87
+ if (entry.isDirectory()) {
88
+ if (!rel && (ARCHIVE_EXCLUDES.has(entry.name) || entry.name.startsWith('.')))
89
+ continue;
90
+ if (entry.name === 'node_modules')
91
+ continue;
92
+ walk(child);
93
+ }
94
+ else if (entry.isFile() && countsTowardMatch(child)) {
95
+ // Sized before anything is read, so one huge asset cannot run memory or time out.
96
+ bytes += fs.lstatSync(path.join(dir, child)).size;
97
+ if (out.size >= MAX_FOLDER_FILES || bytes > MAX_FOLDER_BYTES)
98
+ throw new LineageLimit('folder');
99
+ out.set(child, hashFile(path.join(dir, child), expired));
100
+ }
101
+ }
102
+ };
103
+ try {
104
+ walk('');
105
+ }
106
+ catch (error) {
107
+ if (error instanceof LineageLimit)
108
+ return null;
109
+ throw error;
110
+ }
111
+ return out;
112
+ }
113
+ function readString(block, start, length) {
114
+ const slice = block.subarray(start, start + length);
115
+ const end = slice.indexOf(0);
116
+ return slice.subarray(0, end === -1 ? slice.length : end).toString('utf-8');
117
+ }
118
+ function readSize(block) {
119
+ const field = block.subarray(124, 136);
120
+ if (field[0] & 0x80) {
121
+ // base-256: a size too big for octal. Nothing a deck saves gets there; refuse it.
122
+ throw new LineageLimit('archive');
123
+ }
124
+ const text = readString(block, 124, 12).trim();
125
+ return text ? parseInt(text, 8) : 0;
126
+ }
127
+ function paxPath(body) {
128
+ let offset = 0;
129
+ let found;
130
+ while (offset < body.length) {
131
+ const space = body.indexOf(0x20, offset);
132
+ if (space === -1)
133
+ break;
134
+ const length = parseInt(body.subarray(offset, space).toString('utf-8'), 10);
135
+ if (!Number.isFinite(length) || length <= 0)
136
+ break;
137
+ const record = body.subarray(space + 1, offset + length - 1).toString('utf-8');
138
+ const eq = record.indexOf('=');
139
+ if (eq !== -1 && record.slice(0, eq) === 'path')
140
+ found = record.slice(eq + 1);
141
+ offset += length;
142
+ }
143
+ return found;
144
+ }
145
+ function normalizeArchivePath(name) {
146
+ let rel = name;
147
+ while (rel.startsWith('./'))
148
+ rel = rel.slice(2);
149
+ return rel.replace(/\/+$/, '');
150
+ }
151
+ /**
152
+ * The regular files of a gzipped tar, hashed as they stream (ustar, pax `path`, GNU long
153
+ * names). Links and everything else are skipped; nothing is written to disk.
154
+ */
155
+ export function archiveManifest(gz, expired = () => false) {
156
+ return new Promise((resolve, reject) => {
157
+ const out = new Map();
158
+ const gunzip = zlib.createGunzip();
159
+ let pending = Buffer.alloc(0);
160
+ let unpacked = 0;
161
+ let done = false;
162
+ // The tar's end blocks were read: the rest is only drained, so gunzip still checks its footer.
163
+ let ended = false;
164
+ // The entry being read: its remaining body bytes, padding, and what to do with them.
165
+ let body = null;
166
+ let nextName;
167
+ const finish = (error) => {
168
+ if (done)
169
+ return;
170
+ done = true;
171
+ if (error) {
172
+ gunzip.destroy();
173
+ reject(error);
174
+ }
175
+ else
176
+ resolve(out);
177
+ };
178
+ const endEntry = () => {
179
+ const entry = body;
180
+ body = null;
181
+ if (entry.kind === 'file' && entry.hash) {
182
+ const rel = normalizeArchivePath(entry.name);
183
+ if (countsTowardMatch(rel))
184
+ out.set(rel, entry.hash.digest('hex'));
185
+ }
186
+ else if (entry.kind === 'pax') {
187
+ nextName = paxPath(Buffer.concat(entry.collect)) ?? nextName;
188
+ }
189
+ else if (entry.kind === 'longname') {
190
+ nextName = readString(Buffer.concat(entry.collect), 0, Number.MAX_SAFE_INTEGER);
191
+ }
192
+ };
193
+ const consume = () => {
194
+ for (;;) {
195
+ if (body) {
196
+ if (body.remaining > 0) {
197
+ if (pending.length === 0)
198
+ return;
199
+ const take = Math.min(body.remaining, pending.length);
200
+ const chunk = pending.subarray(0, take);
201
+ body.hash?.update(chunk);
202
+ body.collect?.push(Buffer.from(chunk));
203
+ body.remaining -= take;
204
+ pending = pending.subarray(take);
205
+ continue;
206
+ }
207
+ if (pending.length < body.padding)
208
+ return;
209
+ pending = pending.subarray(body.padding);
210
+ endEntry();
211
+ continue;
212
+ }
213
+ if (pending.length < 512)
214
+ return;
215
+ const block = pending.subarray(0, 512);
216
+ pending = pending.subarray(512);
217
+ if (block.every((byte) => byte === 0)) {
218
+ ended = true;
219
+ pending = Buffer.alloc(0);
220
+ return;
221
+ }
222
+ const size = readSize(block);
223
+ const type = String.fromCharCode(block[156] || 0x30);
224
+ let name = readString(block, 0, 100);
225
+ if (readString(block, 257, 5) === 'ustar') {
226
+ const prefix = readString(block, 345, 155);
227
+ if (prefix)
228
+ name = `${prefix}/${name}`;
229
+ }
230
+ if (nextName !== undefined && type !== 'x' && type !== 'L') {
231
+ name = nextName;
232
+ nextName = undefined;
233
+ }
234
+ const kind = type === '0' || type === '7' ? 'file' : type === 'x' ? 'pax' : type === 'L' ? 'longname' : 'skip';
235
+ if ((kind === 'pax' || kind === 'longname') && size > 1024 * 1024)
236
+ throw new LineageLimit('archive');
237
+ body = {
238
+ remaining: size,
239
+ padding: (512 - (size % 512)) % 512,
240
+ hash: kind === 'file' ? crypto.createHash('sha256') : null,
241
+ collect: kind === 'pax' || kind === 'longname' ? [] : null,
242
+ kind,
243
+ name,
244
+ };
245
+ }
246
+ };
247
+ gunzip.on('data', (chunk) => {
248
+ if (done)
249
+ return;
250
+ unpacked += chunk.length;
251
+ if (unpacked > MAX_UNPACKED_BYTES) {
252
+ finish(new LineageLimit('archive'));
253
+ return;
254
+ }
255
+ if (expired()) {
256
+ finish(new LineageLimit('budget'));
257
+ return;
258
+ }
259
+ if (ended)
260
+ return;
261
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
262
+ try {
263
+ consume();
264
+ }
265
+ catch (error) {
266
+ finish(error instanceof Error ? error : new Error('unreadable archive'));
267
+ }
268
+ });
269
+ // Complete only with the tar's end blocks and gunzip's verified footer (gunzip errors
270
+ // without it): a cut-off current archive would otherwise lose the comparison unfairly.
271
+ gunzip.on('end', () => finish(ended ? undefined : new Error('truncated archive')));
272
+ gunzip.on('error', (error) => finish(error));
273
+ gunzip.end(gz);
274
+ });
275
+ }
276
+ /** How many files the two copies hold identically. */
277
+ export function matchScore(folder, saved) {
278
+ let score = 0;
279
+ for (const [rel, sha] of saved)
280
+ if (folder.get(rel) === sha)
281
+ score += 1;
282
+ return score;
283
+ }
284
+ async function fetchArchiveBytes(url, timeoutMs) {
285
+ const res = await fetch(url, { signal: AbortSignal.timeout(Math.max(1, timeoutMs)) });
286
+ if (!res.ok)
287
+ throw new Error(`archive fetch failed: HTTP ${res.status}`);
288
+ return Buffer.from(await res.arrayBuffer());
289
+ }
290
+ /**
291
+ * The saved version this folder descends from. Never throws: any failure (an older Ghost,
292
+ * a fetch error, the budget) settles on the current version, which is what adopt recorded
293
+ * before this existed.
294
+ */
295
+ export async function findLineage(dir, deckId, server, deps = {}) {
296
+ const nowMs = deps.nowMs ?? Date.now;
297
+ const deadline = deps.deadlineMs ?? nowMs() + LINEAGE_BUDGET_MS;
298
+ const expired = () => nowMs() >= deadline;
299
+ const fetchArchive = deps.fetchArchive ?? fetchArchiveBytes;
300
+ const current = (reason, examined = 0) => ({ outcome: 'skipped', version: server, examined, reason });
301
+ if (expired())
302
+ return current('budget');
303
+ let versions;
304
+ try {
305
+ versions = await (deps.listVersions ?? api.savedSourceHistory)(deckId, deadline - nowMs());
306
+ }
307
+ catch {
308
+ return current(expired() ? 'budget' : 'history_unavailable');
309
+ }
310
+ const head = versions.find((v) => v.s3Key === server.s3Key);
311
+ if (!head)
312
+ return current('current_not_listed');
313
+ const serverMs = Date.parse(server.updatedAt);
314
+ // Older saves only: a refused save leaves its object behind too, and one newer than the
315
+ // current row was never the saved copy.
316
+ const older = versions
317
+ .filter((v) => v.s3Key !== server.s3Key && Date.parse(v.savedAt) < serverMs)
318
+ .sort((a, b) => Date.parse(b.savedAt) - Date.parse(a.savedAt))
319
+ .slice(0, MAX_VERSIONS_EXAMINED - 1);
320
+ if (older.length === 0)
321
+ return { outcome: 'current', version: server, examined: 0 };
322
+ let folder;
323
+ try {
324
+ folder = folderManifest(dir, expired);
325
+ }
326
+ catch {
327
+ return current('folder_unreadable');
328
+ }
329
+ if (!folder)
330
+ return current(expired() ? 'budget' : 'folder_too_large');
331
+ let bytes = 0;
332
+ const read = async (version) => {
333
+ const remaining = deadline - nowMs();
334
+ bytes += version.bytes;
335
+ if (remaining <= 0 || bytes > MAX_ARCHIVE_BYTES_TOTAL)
336
+ return null;
337
+ try {
338
+ return await archiveManifest(await fetchArchive(version.archiveUrl, remaining), expired);
339
+ }
340
+ catch {
341
+ return null;
342
+ }
343
+ };
344
+ const score = async (version) => {
345
+ const manifest = await read(version);
346
+ return manifest && matchScore(folder, manifest);
347
+ };
348
+ const headManifest = await read(head);
349
+ if (headManifest === null)
350
+ return current(expired() ? 'budget' : 'current_unreadable', 1);
351
+ const headScore = matchScore(folder, headManifest);
352
+ // Everything the current save holds is here unchanged: whatever else the folder has, it
353
+ // is not missing that save's work.
354
+ if (headScore === headManifest.size)
355
+ return { outcome: 'current', version: server, examined: 1 };
356
+ let examined = 1;
357
+ let best = null;
358
+ let reason;
359
+ for (const version of older) {
360
+ const s = await score(version);
361
+ if (s === null) {
362
+ reason = nowMs() >= deadline ? 'budget' : bytes > MAX_ARCHIVE_BYTES_TOTAL ? 'bytes' : 'archive_unreadable';
363
+ if (reason !== 'archive_unreadable')
364
+ break;
365
+ continue;
366
+ }
367
+ examined += 1;
368
+ // Newest first, so a tie keeps the newer of two equally good older saves.
369
+ if (s > headScore && (!best || s > best.score))
370
+ best = { version, score: s };
371
+ }
372
+ if (!best)
373
+ return { outcome: 'current', version: server, examined, ...(reason ? { reason } : {}) };
374
+ return {
375
+ outcome: 'older',
376
+ version: { s3Key: best.version.s3Key, updatedAt: best.version.savedAt },
377
+ examined,
378
+ ...(reason ? { reason } : {}),
379
+ };
380
+ }
@@ -1,3 +1,4 @@
1
+ import type { Lineage, LineageDeps } from './sourceLineage.js';
1
2
  export declare const WEB_SOURCE_SYNC_FILE: string;
2
3
  /** `get-deck --side` copies of the saved source, one folder per saved version. */
3
4
  export declare const SAVED_SOURCE_DIR: string;
@@ -66,6 +67,12 @@ export interface SourceStatusResult {
66
67
  marker: Omit<WebSourceSyncMarker, 'deckId'> | null;
67
68
  server: ServerSourceVersion | null;
68
69
  adopted?: true;
70
+ /** How --adopt chose the version it recorded (sourceLineage.ts). */
71
+ lineage?: {
72
+ outcome: Lineage['outcome'];
73
+ examined: number;
74
+ reason?: string;
75
+ };
69
76
  notified?: true;
70
77
  }
71
78
  export interface SourceStatusOptions {
@@ -73,6 +80,8 @@ export interface SourceStatusOptions {
73
80
  notify?: boolean;
74
81
  /** Injected by tests; defaults to the webDeckSource query. */
75
82
  fetchServer?: (deckId: string) => Promise<ServerSourceVersion | null>;
83
+ /** Injected by tests; defaults to sourceLineage's findLineage. */
84
+ findLineage?: (dir: string, deckId: string, server: ServerSourceVersion, deps: LineageDeps) => Promise<Lineage>;
76
85
  now?: () => Date;
77
86
  }
78
87
  export declare function sourceNewerNotice(dir: string, savedAt: string, syncedAt: string): {
@@ -12,6 +12,8 @@ import { WEB_SOURCE_NEWER_MARKER_FILE } from './cloudGit.js';
12
12
  // It lives in `.castle/agent/`: excluded from the source archive (so it never travels into a
13
13
  // save or a remix), and a durable editor namespace in deck persistence (so a cold resume keeps
14
14
  // it). A missing or malformed marker reads as absent: the folder is then adopted, never refused.
15
+ // `source-status --adopt` records the saved version the folder actually matches
16
+ // (sourceLineage.ts), so a folder copied from an older save is told the saved copy is newer.
15
17
  export const WEB_SOURCE_SYNC_FILE = path.join('.castle', 'agent', 'web-source-sync.json');
16
18
  /** `get-deck --side` copies of the saved source, one folder per saved version. */
17
19
  export const SAVED_SOURCE_DIR = path.join('.castle', 'agent', 'saved-source');
@@ -168,6 +170,7 @@ export async function sourceStatus(dir, opts = {}) {
168
170
  return result;
169
171
  }
170
172
  async function computeSourceStatus(dir, opts) {
173
+ const startedAtMs = Date.now();
171
174
  const projectDir = path.resolve(dir);
172
175
  // An unreadable or missing folder is a real error, unlike a folder that isn't a deck.
173
176
  if (!fs.statSync(projectDir).isDirectory())
@@ -191,18 +194,29 @@ async function computeSourceStatus(dir, opts) {
191
194
  return result;
192
195
  if (!marker) {
193
196
  result.status = 'no-marker';
194
- if (opts.adopt) {
195
- const written = writeSyncMarker(projectDir, deckId, server, 'adopt', opts.now?.());
196
- result.marker = { s3Key: written.s3Key, updatedAt: written.updatedAt, syncedAt: written.syncedAt, via: written.via };
197
- result.adopted = true;
198
- }
199
- return result;
197
+ if (!opts.adopt)
198
+ return result;
199
+ const { findLineage: defaultFindLineage, LINEAGE_BUDGET_MS } = await import('./sourceLineage.js');
200
+ const lineage = await (opts.findLineage ?? defaultFindLineage)(projectDir, deckId, server, {
201
+ deadlineMs: startedAtMs + LINEAGE_BUDGET_MS,
202
+ });
203
+ const written = writeSyncMarker(projectDir, deckId, lineage.version, 'adopt', opts.now?.());
204
+ result.marker = { s3Key: written.s3Key, updatedAt: written.updatedAt, syncedAt: written.syncedAt, via: written.via };
205
+ result.adopted = true;
206
+ result.lineage = {
207
+ outcome: lineage.outcome,
208
+ examined: lineage.examined,
209
+ ...(lineage.reason ? { reason: lineage.reason } : {}),
210
+ };
211
+ // Adopted at an older save: from here on it is an ordinary folder behind the saved copy.
212
+ if (lineage.outcome !== 'older')
213
+ return result;
200
214
  }
201
- result.status = compareSync(marker, server);
215
+ result.status = compareSync(result.marker, server);
202
216
  if (result.status === 'saved-newer' && opts.notify) {
203
217
  const file = path.join(projectDir, WEB_SOURCE_NEWER_MARKER_FILE);
204
218
  fs.mkdirSync(path.dirname(file), { recursive: true });
205
- atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, marker.updatedAt))}\n`);
219
+ atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, result.marker.updatedAt))}\n`);
206
220
  result.notified = true;
207
221
  }
208
222
  return result;
@@ -222,7 +236,8 @@ export function describeSourceStatus(result) {
222
236
  case 'lag':
223
237
  return `The server has not caught up with this folder's last save yet (${humanTime(result.marker.updatedAt)}).`;
224
238
  case 'saved-newer':
225
- return (`The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
239
+ return ((result.adopted ? `This folder matches an older save of deck ${result.deckId}. ` : '') +
240
+ `The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
226
241
  `this folder last synced ${humanTime(result.marker.updatedAt)}).` +
227
242
  (result.notified ? ' The agent has been told.' : ''));
228
243
  }
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-09-30T02:50:31.658Z",
85
+ "publishedVersion": "2026-10-01T02:24:47.884Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -151,6 +151,87 @@ Two differences follow from a session server not being a player:
151
151
  stop. An out-of-memory kill or a host failing sends no shutdown at all, so
152
152
  save as things change and treat `onShutdown` as the last chance, not the plan.
153
153
 
154
+ ### Persistent worlds
155
+
156
+ An opted-in persistent-world route has `session.world`; other sessions have
157
+ `session.world === null`. Alongside its checkpoint, the world keeps a journal
158
+ of its latest 512 entries and a last-seen row for each participant:
159
+
160
+ ```js
161
+ await session.world.journal.append({
162
+ operationId: "market-opened-day-12",
163
+ entries: [{
164
+ kind: "market.opened",
165
+ disclosure: "world",
166
+ data: { day: 12 },
167
+ }],
168
+ });
169
+
170
+ const page = await session.world.journal.read({
171
+ afterSeq: savedCursor,
172
+ participantId: player.participantId,
173
+ });
174
+ const { participants } = await session.world.participants.read({
175
+ participantIds: [player.participantId],
176
+ });
177
+ ```
178
+
179
+ `journal.append` accepts up to 16 entries per operation; each optional `data`
180
+ value must be JSON no larger than 2 KiB. Save `nextSeq` from `journal.read` as
181
+ the next cursor, and compare it with `oldestRetainedSeq` to detect a cursor that
182
+ fell behind retention. Entries disclosed to `participants` name participant
183
+ ids for the trusted deck server to project to those players; never broadcast
184
+ those entries to the whole session.
185
+
186
+ Every `MultiplayerServerPlayer` has a stable `participantId` for these calls
187
+ (`scopedUserId` when available, otherwise `userId`). The host records join,
188
+ leave, and shutdown presence automatically, and `participants.read` reflects
189
+ those host writes. The SDK never writes participant presence, and there is no
190
+ public touch method.
191
+
192
+ A world-notification template is published copy with named slots; push copy is
193
+ always authored by the deck and is never generated at runtime. Ghost owns
194
+ delivery, muting, expiry, and rate caps, including notifications scheduled for
195
+ later. `notifications.notify` and `notifications.cancel` return counts only, so
196
+ deck code cannot learn which participants were muted or unavailable.
197
+
198
+ ```js
199
+ await session.world.notifications.notify({
200
+ key: "lantern-overdue",
201
+ participantIds: [player.participantId],
202
+ templateId: "lantern_overdue",
203
+ slots: { npc: "Mara" },
204
+ at: "2026-10-01T18:00:00Z",
205
+ });
206
+
207
+ await session.world.notifications.cancel({
208
+ key: "lantern-overdue",
209
+ participantIds: [player.participantId],
210
+ });
211
+ ```
212
+
213
+ A destination can opt into real elapsed time with
214
+ `worldTime: { advance: "wallClock" }`. On boot, `catchUp` reads the latest
215
+ checkpoint, clamps the elapsed duration, and commits the full checkpoint
216
+ returned by `apply`; it retries one revision conflict and never advances an
217
+ authored game clock on its own.
218
+
219
+ The checkpoint marker prevents an elapsed interval from being counted twice
220
+ and never moves backwards if the host clock regresses. If a prior commit landed
221
+ without its acknowledgement being observed, the next boot counts only time
222
+ elapsed after that marker, so `apply` may run again for that new interval; it
223
+ returns `{ applied: false, elapsedMs: 0 }` without calling `apply` only when no
224
+ time has passed since the marker.
225
+
226
+ ```js
227
+ const result = await session.world.catchUp({
228
+ maxElapsedMs: 7 * 24 * 60 * 60 * 1000,
229
+ apply({ elapsedMs, checkpoint }) {
230
+ return advanceWorld(checkpoint, elapsedMs);
231
+ },
232
+ });
233
+ ```
234
+
154
235
  ## Store
155
236
 
156
237
  `Store` saves data one key at a time. It is the storage to use for
@@ -14,7 +14,7 @@ export type { LeaderboardData, LeaderboardEntry, LeaderboardOptions, Leaderboard
14
14
  export { Lifecycle } from "./lifecycle";
15
15
  export type { CastleLifecycleApi } from "./lifecycle";
16
16
  export { Multiplayer } from "./multiplayer";
17
- export type { CastleMultiplayerApi, MultiplayerConnection, MultiplayerConnectionState, MultiplayerDestinationJoinResult, MultiplayerDestinationOptions, MultiplayerJoinOptions, MultiplayerRoster, MultiplayerStateMetadata, } from "./multiplayer";
17
+ export type { CastleMultiplayerApi, MultiplayerConnection, MultiplayerConnectionState, MultiplayerCompleteScheduledBeatCommand, MultiplayerCompleteScheduledBeatResult, MultiplayerDestinationJoinResult, MultiplayerDestinationOptions, MultiplayerEvaluateBeatsCommand, MultiplayerEvaluateBeatsResult, MultiplayerJoinHint, MultiplayerJoinOptions, MultiplayerRoster, MultiplayerScheduledBeatReason, MultiplayerScheduledBeatSelection, MultiplayerStateMetadata, MultiplayerStoryOpportunity, MultiplayerWorldCharacterCommand, MultiplayerWorldCharacterCommandResult, MultiplayerWorldCharacterCommandResultValue, } from "./multiplayer";
18
18
  export type { MultiplayerVoice, VoiceJoinStatus, VoiceListener, VoiceMixEntry, VoiceSpatialOptions, VoiceState, VoiceVector, } from "./multiplayerVoice";
19
19
  export type { MultiplayerDestinationAudience, MultiplayerSoloReason } from "./commands";
20
20
  export { MAX_CLIENT_FRAME_BYTES, MAX_PLAYERS_CAP } from "./multiplayerProtocol";
@@ -114,6 +114,10 @@ export interface MultiplayerGetSessionResult {
114
114
  /** Internal local-serve scope for restoring this Play panel after a reload. */
115
115
  devReconnectScope?: string;
116
116
  }
117
+ export interface MultiplayerJoinHint {
118
+ routeId: string;
119
+ slot: string;
120
+ }
117
121
  export interface MultiplayerJoinDestinationParams {
118
122
  routeId: string;
119
123
  slot: string;
@@ -352,6 +356,7 @@ export interface CommandParams {
352
356
  style: HapticStyle;
353
357
  };
354
358
  "multiplayer.getSession": MultiplayerGetSessionParams;
359
+ "multiplayer.getJoinHint": Record<string, never>;
355
360
  "multiplayer.joinDestination": MultiplayerJoinDestinationParams;
356
361
  "voice.getState": {
357
362
  sessionId: string;
@@ -492,6 +497,7 @@ export interface CommandResult {
492
497
  "portal.info": PortalInfoResult;
493
498
  "haptics.play": HapticsResult;
494
499
  "multiplayer.getSession": MultiplayerGetSessionResult;
500
+ "multiplayer.getJoinHint": MultiplayerJoinHint | null;
495
501
  "multiplayer.joinDestination": MultiplayerJoinDestinationResult;
496
502
  "voice.getState": {
497
503
  state: VoiceState;