castle-web-cli 0.4.242 → 0.4.243

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.
@@ -118,7 +118,7 @@ ${runningTaskRules}
118
118
  - Never claim the board is cleared without actually emitting the fence.
119
119
  - Tasks are one-and-done -- when the user gives feedback on a finished task, spawn a new fix task (and \`castle-done\` the old row) rather than reopening it -- unless their words ask to go back to an earlier state, which is the version-history rule below.
120
120
  - Task agents are capable coding agents working in this same deck directory, but they know nothing about this conversation beyond your prompt.
121
- - The deck keeps its own version history, and you may READ it: \`castle-web list-versions\` shows the versions newest first, and \`castle-web show-version <id>\` shows what one changed, as diffs of just those files. Use them to answer "what changed" or to ground a claim about recent work. You NEVER run \`save-version\` -- you did not make the changes, so a version of yours would not correspond to a unit of work -- and you run \`restore-version\` only when the user's own words ask to put the whole deck back to an earlier state ("go back", "revert it", "undo all that"): that decision is theirs, and they have made it. Never restore on your own judgment, because a fix looks wrong, or on "that looks worse" alone; bringing back or undoing one thing inside newer work ("put the leaderboard back", "undo that color") is a targeted fix, as a task, since a restore would take out the rest. While any task is running, do not restore: its edits would land on top of the old version, so say it has to wait until they finish, or offer to stop them first. To restore, read \`list-versions\` (and \`show-version\` where it helps) for the version that matches what they described; when more than one could match, ask which, naming each as a choice, instead of guessing. Then run \`castle-web restore-version <id>\` yourself -- never with \`--force\`, never through a task -- and say which version you restored and which later changes it took out of the deck (they stay in the version history, so the restore can itself be undone). If it refuses or restores nothing (unsaved changes, tasks still running, already at that version), tell them what it said rather than forcing it. No task you spawn may ever revert, replace, or re-scaffold the deck's scenes, scripts, or behaviors back to kit or starter content -- a fix is always a targeted edit, and every task prompt you write has to be readable that way.
121
+ - The deck keeps its own version history, and you may READ it: \`castle-web list-versions\` shows the versions newest first, and \`castle-web show-version <id>\` shows what one changed, as diffs of just those files. Use them to answer "what changed" or to ground a claim about recent work. You NEVER run \`save-version\` -- you did not make the changes, so a version of yours would not correspond to a unit of work -- and you run \`restore-version\` only when the user's own words ask to put the whole deck back to an earlier state ("go back", "revert it", "undo all that"): that decision is theirs, and they have made it. Never restore on your own judgment, because a fix looks wrong, or on "that looks worse" alone; bringing back or undoing one thing inside newer work ("put the leaderboard back", "undo that color") is a targeted fix, as a task, since a restore would take out the rest. While any task is running, do not restore: its edits would land on top of the old version, so say it has to wait until they finish, or offer to stop them first. To restore, read \`list-versions\` (and \`show-version\` where it helps) for the version that matches what they described; when more than one could match, ask which, naming each as a choice, instead of guessing. Then run \`castle-web restore-version <id>\` yourself -- never with \`--force\`, never through a task -- and say which version you restored and which later changes it took out of the deck (they stay in the version history, so the restore can itself be undone). If it refuses or restores nothing (unsaved changes, tasks still running, already at that version), tell them what it said rather than forcing it. Never edit or delete anything under \`.castle/versions/\` yourself, and never ask a task to: removing versions or their blobs by hand corrupts the history and the cloud stops saving the deck. When the user asks to remove old versions, or the deck is too large to save and old versions are what is big, run \`castle-web prune-versions --keep <n> --dry-run\` yourself, tell them how many versions and how much space it would free, and once they agree run it without \`--dry-run\` (never through a task); if it refuses, tell them what it said. No task you spawn may ever revert, replace, or re-scaffold the deck's scenes, scripts, or behaviors back to kit or starter content -- a fix is always a targeted edit, and every task prompt you write has to be readable that way.
122
122
 
123
123
  Asking with options (the \`\`\`ask block). When you need the user to settle a few choices at once, emit ONE fenced block tagged \`ask\` containing JSON -- it renders inline in the chat as grouped options they tap and submit together (far better than stacking questions they can only half-answer). Reach for it to pin a direction when their ask is vague ("make me a game" -> ask what kind), NOT to interrogate.
124
124
 
@@ -1274,7 +1274,7 @@ phase: wiring the paddle to touch
1274
1274
  }
1275
1275
  // How a task agent records its work: a version in the deck's own store, or a
1276
1276
  // commit when the deck is on git. The version wording is the prompt's original
1277
- // text, unchanged.
1277
+ // text, plus the rule that only prune-versions shrinks the store.
1278
1278
  function taskSaveWording(git) {
1279
1279
  if (!git) {
1280
1280
  return {
@@ -1282,7 +1282,7 @@ function taskSaveWording(git) {
1282
1282
  rule: '- SAVE A VERSION when your change is done, so the user can see and undo it: `castle-web save-version -m "<short description of what you changed>" <each path you touched>`. Name those paths explicitly -- a bare `save-version` with no paths records the WHOLE deck, including files a sibling agent is still working on. One version for the whole task, at the end; not one per file.',
1283
1283
  listing: '`save-version -m "<message>" <paths...>` -- as above: your own paths, named explicitly, once at the end.',
1284
1284
  before: '- Before any change that overwrites or deletes MORE THAN ONE existing file of theirs, save a version first so they can restore: `castle-web save-version -m "<what is about to change>" <those paths>`. That is on top of the end-of-task version below, not instead of it.',
1285
- store: "(The version store lives there too, but you never edit it by hand -- `castle-web save-version` writes it for you.)",
1285
+ store: "(The version store lives there too, but you never edit or delete it by hand, not even to save space -- `castle-web save-version` writes it for you, and only `castle-web prune-versions` may shrink it.)",
1286
1286
  };
1287
1287
  }
1288
1288
  return {
@@ -1290,7 +1290,7 @@ function taskSaveWording(git) {
1290
1290
  rule: '- COMMIT when your change is done, so the user can see and undo it: `castle-web commit --reason task -m "<short description of what you changed>" <each path you touched>`. Name those paths explicitly -- a bare `commit` with no paths records the WHOLE deck, including files a sibling agent is still working on. One commit for the whole task, at the end; not one per file. It is pushed to the deck\'s git remote for you: never run `git commit`, `git push`, `git reset`, `git rebase` or `git checkout` yourself.',
1291
1291
  listing: '`commit --reason task -m "<message>" <paths...>` -- as above: your own paths, named explicitly, once at the end.',
1292
1292
  before: '- Before any change that overwrites or deletes MORE THAN ONE existing file of theirs, commit them first so they can restore: `castle-web commit --reason task -m "<what is about to change>" <those paths>`. That is on top of the end-of-task commit below, not instead of it.',
1293
- store: "(The deck's history is git, in .git -- you never edit it by hand; `castle-web commit` writes it for you.)",
1293
+ store: "(The deck's history is git, in .git -- you never edit it by hand; `castle-web commit` writes it for you. The older version store in .castle/versions is never edited or deleted by hand either; only `castle-web prune-versions` may shrink it.)",
1294
1294
  };
1295
1295
  }
1296
1296
  // Appended to claude task agents' system prompt (portable replacement for the
package/dist/index.js CHANGED
@@ -209,6 +209,7 @@ function usage() {
209
209
  castle-web list-versions [version] [--dir DIR] (defaults to the latest version)
210
210
  castle-web show-version <version> [--dir DIR] (diffs of the files that version changed)
211
211
  castle-web restore-version <version> [--force] [--dir DIR]
212
+ castle-web prune-versions --keep N [--dry-run] [--dir DIR] (keeps the newest N versions, drops the rest and their stored files, after checking the result against the cloud save's version-history rules; never hand-edit .castle/versions)
212
213
  castle-web git init [dir] [--dir DIR] [--staging] (connects the deck to its Castle git remote: git push castle <branch>)
213
214
  castle-web git clone <deckId|url> [dir] [--staging] (clones a deck's Castle repo; the remote is "castle")
214
215
  castle-web git setup [--force|--remove] (lets plain git use your Castle login for git.castle.xyz; login does this)
@@ -689,6 +690,15 @@ async function main() {
689
690
  restoreVersion(getFlagValue('--dir') ?? '.', target, { force: hasFlag('--force') });
690
691
  break;
691
692
  }
693
+ case 'prune-versions': {
694
+ const keep = Number(getFlagValue('--keep'));
695
+ if (!getFlagValue('--keep') || !Number.isInteger(keep) || keep < 1) {
696
+ console.error('Usage: castle-web prune-versions --keep N [--dry-run] (N is at least 1)');
697
+ process.exit(1);
698
+ }
699
+ (await import('./versionPrune.js')).pruneVersions(getFlagValue('--dir') ?? '.', { keep, dryRun: hasFlag('--dry-run') });
700
+ break;
701
+ }
692
702
  case 'restart': {
693
703
  const dir = findPositionalDir();
694
704
  const servePort = getServeSocketPort(dir);
@@ -59,6 +59,7 @@ export function everyDeckBullets(deckDir) {
59
59
  "- Do not reload the deck after an edit. Nothing auto-reloads: the person applies your changes when they are ready, from the Play panel's restart button or a panel's own reload control. `npm run restart` reloads every open panel at once and breaks their flow — only when asked.",
60
60
  '- If the browser console shows `[vite] failed to connect to websocket` (or a "Direct websocket connection fallback" line), ignore it. Vite HMR is deliberately off on this serve, so the line is expected and harmless: it is never why a scene is blank, a game is not running, or multiplayer is not connecting. Do not investigate or "fix" it.',
61
61
  "- Never revert, replace, or re-scaffold the deck's scenes, scripts, or behaviors back to kit, starter, or imported content, and never delete or rewrite a whole scene to diagnose a problem -- those files are the person's own work. Fix forward with targeted edits, and treat a request to diagnose or explain as read-only unless they asked for a fix.",
62
+ "- **Never hand-edit, move or delete anything under `.castle/versions/`**, the deck's saved version history -- not to save space, not to fix `list-versions`. Each version is stored as a change against the one before it, so removing versions or blobs by hand corrupts the history and the cloud stops saving the deck. To shrink it, run `castle-web prune-versions --keep <n> --dry-run` to see what would go, then the same without `--dry-run`: it keeps the newest n versions, rewrites the oldest kept one so it stands on its own, and checks the result against the cloud save's version-history rules before it changes anything. Removing old versions is the person's call, so ask first.",
62
63
  "- The deck can define its own editors: declare a file type in `castle.json` (`editor.fileTypes`: ext, label, icon, and an `editors/` module) and the Files panel opens that type in it — whole recipe under `## Editors` in the deck's guide (its kit's `CLAUDE.md` under `imports/`). Editors under `imports/` are read-only; add or fork, don't edit.",
63
64
  '- An editor is for content FILES the creator keeps coming back to (catalogs, dialogue, level tables) that nothing already opens. One-off or generated data stays code.',
64
65
  "- **Put the values someone would tune while playtesting in a `PARAMS` object**: `export const PARAMS = { jumpHeight: 4.2, coyoteTime: 0.08 };` near the top of the file that uses them. The Parameters panel lists every file in the deck that has one and renders their values as fields -- a number scrubs, a boolean toggles, a `'#rrggbb'` string opens a color picker -- and writes the edit back into the file. It edits every file's params in one place, so nobody has to remember which file a setting lives in, and a file that has params says so above its code with a way in. That is how a creator tunes a game on a phone without putting a cursor inside an expression. Nested one level deep (`player: { speed: 5 }`) renders as a group. **Write each value as a plain number, not as arithmetic** (`0.333`, not `1 / 3`): the panel folds arithmetic over plain numbers into a field and replaces it with the tuned literal on the first edit, so the expression you wrote does not survive the first tune. A value that NAMES something (`speed: BASE * 2`) shows read-only, as a link onto its own line in the code.",
@@ -0,0 +1,62 @@
1
+ import * as store from './versionStore.js';
2
+ export declare class InvalidVersionStore extends Error {
3
+ }
4
+ /** The shape checks deck-persistence's validateVersion applies to one version object. */
5
+ export declare function checkVersionShape(value: unknown, id: string): store.Version;
6
+ /**
7
+ * The history rules deck-persistence's validateVersions applies, over an in-memory store:
8
+ * head names a version, every parent exists, there are no loops, every hash a version
9
+ * names has a blob, and every version's `changes` equal the diff of its manifest against
10
+ * its parent's (an empty manifest for a root).
11
+ */
12
+ export declare function validateHistory(versions: ReadonlyMap<string, store.Version>, head: string | null, hasBlob: (hash: string) => boolean): void;
13
+ /** Every hash a set of versions needs a blob for. */
14
+ export declare function referencedHashes(versions: Iterable<store.Version>): Set<string>;
15
+ /** A version rewritten as a root: no parent, and its whole manifest as added. */
16
+ export declare function asRoot(version: store.Version): store.Version;
17
+ /**
18
+ * The line list-versions shows, newest first: head's later descendants (the chain a
19
+ * restore-version back in time left ahead of head), head, then head's ancestors. Stops at
20
+ * a missing parent rather than failing, so a store that already lost versions can be pruned
21
+ * back into shape.
22
+ */
23
+ export declare function versionLine(versions: ReadonlyMap<string, store.Version>, head: string): store.Version[];
24
+ export interface PrunePlan {
25
+ head: string;
26
+ /** Kept versions as they will be on disk, keyed by id. */
27
+ kept: Map<string, store.Version>;
28
+ /** Kept versions whose file is rewritten as a root. */
29
+ reRooted: string[];
30
+ /** Versions whose file is deleted, children before parents. */
31
+ removed: string[];
32
+ /** Blob hashes deleted: nothing kept references them. */
33
+ removedBlobs: string[];
34
+ }
35
+ /**
36
+ * Plans a prune over an in-memory store and validates the result. Pure: the caller
37
+ * decides whether to apply it. Throws InvalidVersionStore when the result would not be a
38
+ * store the cloud save accepts.
39
+ */
40
+ export declare function planPrune(versions: ReadonlyMap<string, store.Version>, head: string | null, blobs: ReadonlySet<string>, keep: number): PrunePlan;
41
+ /**
42
+ * Validates the store on disk with the cloud save's rules, blob bytes included. Throws
43
+ * InvalidVersionStore naming the first problem.
44
+ */
45
+ export declare function validateVersionStore(projectDir: string): void;
46
+ export interface PruneOptions {
47
+ keep: number;
48
+ dryRun?: boolean;
49
+ }
50
+ export interface PruneOutcome {
51
+ plan: PrunePlan;
52
+ bytesFreed: number;
53
+ applied: boolean;
54
+ }
55
+ /** Plans, validates and (unless dryRun) applies a prune. Writes nothing when it throws. */
56
+ /** A prune that applied and then found the store invalid: something raced it. */
57
+ export declare class PrunedButInvalid extends Error {
58
+ }
59
+ /** Plans, validates and (unless dryRun) applies a prune. Writes nothing when it throws
60
+ * InvalidVersionStore. Holds the store's lock throughout, so no save or restore interleaves. */
61
+ export declare function pruneVersionStore(projectDir: string, opts: PruneOptions): PruneOutcome;
62
+ export declare function pruneVersions(dir: string, opts: PruneOptions): void;
@@ -0,0 +1,513 @@
1
+ // prune-versions: the one supported way to shrink `.castle/versions/`.
2
+ //
3
+ // The store looks like it can be trimmed by hand -- delete old `.version` files and
4
+ // their blobs -- but it cannot. A version's `changes` are a delta against its parent,
5
+ // and Castle's cloud save (castle-sandboxes deck-persistence, validateVersions) checks
6
+ // every version's `changes` against its manifest diff: a ROOT (parentId null) must list
7
+ // its whole manifest as added. Dropping a version's parent and nulling its `parentId`
8
+ // leaves a delta against nothing, the save rejects the store, and the deck stops saving.
9
+ //
10
+ // So prune keeps the newest N versions of the line list-versions shows, rewrites the
11
+ // oldest kept one as a true root (its changes become its full manifest diffed against
12
+ // empty), drops every other version and every blob nothing kept references, and checks
13
+ // the result with the same rules the cloud save applies BEFORE it writes anything.
14
+ //
15
+ // Writes go in an order where every intermediate state is itself a valid store:
16
+ // re-roots first (atomic replace), then version files children-before-parents, then
17
+ // blobs. A crash midway leaves extra versions or blobs, never a dangling reference.
18
+ import * as fs from 'fs';
19
+ import * as path from 'path';
20
+ import * as zlib from 'zlib';
21
+ import { atomicWriteFileSync } from './atomicFile.js';
22
+ import * as store from './versionStore.js';
23
+ // Mirrors castle-sandboxes deck-persistence (workspaceState.ts, codec.ts, contracts.ts).
24
+ // Keep these in step with it: a store this file calls valid must be one the save accepts.
25
+ const HASH = /^[0-9a-f]{64}$/;
26
+ const VERSION_ID = /^[A-Za-z0-9]{12}$/;
27
+ const IGNORED_SEGMENTS = new Set(['node_modules', '.castle', '.git', 'dist', 'imports']);
28
+ const MAX_FILE_BYTES = 32 * 1024 * 1024;
29
+ const MAX_PATH_BYTES = 4096;
30
+ const MAX_SEGMENT_BYTES = 255;
31
+ const SOURCE_PRIVATE_ROOTS = new Set([
32
+ '.aws',
33
+ '.azure',
34
+ '.cache',
35
+ '.castle-home',
36
+ '.claude',
37
+ '.codex',
38
+ '.config',
39
+ '.docker',
40
+ '.gcloud',
41
+ '.git',
42
+ '.gnupg',
43
+ '.kube',
44
+ '.local',
45
+ '.netrc',
46
+ '.npmrc',
47
+ '.ssh',
48
+ ]);
49
+ const MAX_FILES = 10000;
50
+ const MAX_MANIFEST_BYTES = 4 * 1024 * 1024;
51
+ // The cloud validates each version's manifest as a source snapshot of empty files
52
+ // (validateSnapshotFiles), whose manifest JSON must fit MAX_MANIFEST_BYTES. Each empty file
53
+ // is one gzip-pack entry with a 64-hex object id and the empty-content sha256; its JSON size
54
+ // depends only on the path. Mirrors codec.ts planSnapshot + validateManifest.
55
+ const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
56
+ const MANIFEST_ENTRY_BYTES = Buffer.byteLength(JSON.stringify({ path: '', objectId: '0'.repeat(64), encoding: 'gzip-pack', sha256: EMPTY_SHA256, size: 0, mode: 0o644 }));
57
+ const MANIFEST_WRAPPER_BYTES = Buffer.byteLength(JSON.stringify({ version: 1, kind: 'source', files: [] }));
58
+ function sourceManifestBytes(paths) {
59
+ let bytes = MANIFEST_WRAPPER_BYTES + Math.max(0, paths.length - 1);
60
+ for (const p of paths)
61
+ bytes += MANIFEST_ENTRY_BYTES + Buffer.byteLength(JSON.stringify(p)) - 2;
62
+ return bytes;
63
+ }
64
+ const VERSION_KEYS = ['changes', 'createdAt', 'files', 'id', 'message', 'parentId'];
65
+ export class InvalidVersionStore extends Error {
66
+ }
67
+ function fail(message) {
68
+ throw new InvalidVersionStore(message);
69
+ }
70
+ function isRecord(value) {
71
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
72
+ }
73
+ function checkSourcePath(sourcePath, where) {
74
+ const segments = sourcePath.split('/');
75
+ if (sourcePath.length === 0 ||
76
+ Buffer.byteLength(sourcePath) > MAX_PATH_BYTES ||
77
+ [...sourcePath].some((c) => c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f) ||
78
+ sourcePath.includes('\\') ||
79
+ path.posix.isAbsolute(sourcePath) ||
80
+ path.posix.normalize(sourcePath) !== sourcePath ||
81
+ Buffer.from(sourcePath, 'utf8').toString('utf8') !== sourcePath ||
82
+ segments.some((s) => s.length === 0 || s === '.' || s === '..' || Buffer.byteLength(s) > MAX_SEGMENT_BYTES))
83
+ fail(`${where} has an unsafe path ${JSON.stringify(sourcePath)}`);
84
+ if (SOURCE_PRIVATE_ROOTS.has(segments[0]))
85
+ fail(`${where} tracks private state ${sourcePath}`);
86
+ if (segments.some((s) => IGNORED_SEGMENTS.has(s)))
87
+ fail(`${where} tracks an ignored path ${sourcePath}`);
88
+ }
89
+ function checkHash(value, where) {
90
+ if (typeof value !== 'string' || !HASH.test(value))
91
+ fail(`${where} has an invalid hash`);
92
+ }
93
+ /** The shape checks deck-persistence's validateVersion applies to one version object. */
94
+ export function checkVersionShape(value, id) {
95
+ const where = `version ${id}`;
96
+ if (!VERSION_ID.test(id))
97
+ fail(`${where} has an invalid id`);
98
+ if (!isRecord(value))
99
+ fail(`${where} is not an object`);
100
+ const keys = Object.keys(value).sort();
101
+ if (keys.length !== VERSION_KEYS.length || keys.some((k, i) => k !== VERSION_KEYS[i]))
102
+ fail(`${where} has unknown or missing fields`);
103
+ if (value.id !== id)
104
+ fail(`${where} id does not match its file name`);
105
+ if (value.parentId !== null && (typeof value.parentId !== 'string' || !VERSION_ID.test(value.parentId)))
106
+ fail(`${where} has an invalid parent id`);
107
+ if (typeof value.createdAt !== 'string' || value.createdAt.length === 0)
108
+ fail(`${where} has an invalid timestamp`);
109
+ if (typeof value.message !== 'string')
110
+ fail(`${where} has an invalid message`);
111
+ if (!isRecord(value.files) || !isRecord(value.changes))
112
+ fail(`${where} has invalid manifests`);
113
+ const filePaths = Object.keys(value.files);
114
+ // validateSnapshotFiles over the manifest: its file count and no path that is both a
115
+ // file and a directory.
116
+ if (filePaths.length > MAX_FILES)
117
+ fail(`${where} tracks more than ${MAX_FILES} files`);
118
+ if (sourceManifestBytes(filePaths) > MAX_MANIFEST_BYTES)
119
+ fail(`${where} manifest is too large`);
120
+ for (const [p, hash] of Object.entries(value.files)) {
121
+ checkSourcePath(p, where);
122
+ checkHash(hash, where);
123
+ }
124
+ const seen = new Set();
125
+ for (const p of [...filePaths].sort()) {
126
+ for (let slash = p.indexOf('/'); slash !== -1; slash = p.indexOf('/', slash + 1))
127
+ if (seen.has(p.slice(0, slash)))
128
+ fail(`${where} has a file/directory collision at ${p}`);
129
+ seen.add(p);
130
+ }
131
+ for (const [p, change] of Object.entries(value.changes)) {
132
+ checkSourcePath(p, where);
133
+ if (!isRecord(change))
134
+ fail(`${where} has an invalid change`);
135
+ const changeKeys = Object.keys(change).sort();
136
+ if (changeKeys.length !== 2 || changeKeys[0] !== 'after' || changeKeys[1] !== 'before')
137
+ fail(`${where} has an invalid change`);
138
+ if (change.before !== null)
139
+ checkHash(change.before, where);
140
+ if (change.after !== null)
141
+ checkHash(change.after, where);
142
+ }
143
+ return value;
144
+ }
145
+ /**
146
+ * The history rules deck-persistence's validateVersions applies, over an in-memory store:
147
+ * head names a version, every parent exists, there are no loops, every hash a version
148
+ * names has a blob, and every version's `changes` equal the diff of its manifest against
149
+ * its parent's (an empty manifest for a root).
150
+ */
151
+ export function validateHistory(versions, head, hasBlob) {
152
+ if (versions.size === 0) {
153
+ if (head !== null)
154
+ fail('version head does not reference a version');
155
+ return;
156
+ }
157
+ if (head === null)
158
+ fail('version history has no head');
159
+ if (!VERSION_ID.test(head) || !versions.has(head))
160
+ fail('version head does not reference a version');
161
+ for (const version of versions.values()) {
162
+ checkVersionShape(version, version.id);
163
+ if (version.parentId !== null && !versions.has(version.parentId))
164
+ fail(`version ${version.id} has a missing parent`);
165
+ const parentFiles = version.parentId === null ? {} : versions.get(version.parentId).files;
166
+ const expected = store.diffManifests(parentFiles, version.files);
167
+ const actualPaths = Object.keys(version.changes);
168
+ if (actualPaths.length !== Object.keys(expected).length ||
169
+ actualPaths.some((p) => {
170
+ const want = expected[p];
171
+ const got = version.changes[p];
172
+ return !want || got.before !== want.before || got.after !== want.after;
173
+ }))
174
+ fail(`version ${version.id} changes do not equal its manifest diff`);
175
+ for (const hash of Object.values(version.files))
176
+ if (!hasBlob(hash))
177
+ fail(`version ${version.id} references a missing blob`);
178
+ for (const change of Object.values(version.changes))
179
+ for (const hash of [change.before, change.after])
180
+ if (hash !== null && !hasBlob(hash))
181
+ fail(`version ${version.id} references a missing change blob`);
182
+ const seen = new Set();
183
+ let cursor = version;
184
+ while (cursor) {
185
+ if (seen.has(cursor.id))
186
+ fail(`version history loops at ${cursor.id}`);
187
+ seen.add(cursor.id);
188
+ cursor = cursor.parentId === null ? undefined : versions.get(cursor.parentId);
189
+ }
190
+ }
191
+ }
192
+ /** Every hash a set of versions needs a blob for. */
193
+ export function referencedHashes(versions) {
194
+ const out = new Set();
195
+ for (const version of versions) {
196
+ for (const hash of Object.values(version.files))
197
+ out.add(hash);
198
+ for (const change of Object.values(version.changes)) {
199
+ if (change.before !== null)
200
+ out.add(change.before);
201
+ if (change.after !== null)
202
+ out.add(change.after);
203
+ }
204
+ }
205
+ return out;
206
+ }
207
+ /** A version rewritten as a root: no parent, and its whole manifest as added. */
208
+ export function asRoot(version) {
209
+ return { ...version, parentId: null, changes: store.diffManifests({}, version.files) };
210
+ }
211
+ /**
212
+ * The line list-versions shows, newest first: head's later descendants (the chain a
213
+ * restore-version back in time left ahead of head), head, then head's ancestors. Stops at
214
+ * a missing parent rather than failing, so a store that already lost versions can be pruned
215
+ * back into shape.
216
+ */
217
+ export function versionLine(versions, head) {
218
+ const childrenOf = new Map();
219
+ for (const version of versions.values()) {
220
+ if (version.parentId === null)
221
+ continue;
222
+ const siblings = childrenOf.get(version.parentId);
223
+ if (siblings)
224
+ siblings.push(version);
225
+ else
226
+ childrenOf.set(version.parentId, [version]);
227
+ }
228
+ const seen = new Set([head]);
229
+ const later = [];
230
+ for (let cursor = head;;) {
231
+ const children = childrenOf.get(cursor);
232
+ if (!children || children.length === 0)
233
+ break;
234
+ // The same pick as versionStore.forwardChain: newest child, id breaking a tie.
235
+ const next = [...children].sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id))[0];
236
+ if (seen.has(next.id))
237
+ break;
238
+ seen.add(next.id);
239
+ later.push(next);
240
+ cursor = next.id;
241
+ }
242
+ const back = [];
243
+ const backSeen = new Set();
244
+ for (let cursor = head; cursor !== null;) {
245
+ const version = versions.get(cursor);
246
+ if (!version || backSeen.has(cursor))
247
+ break;
248
+ backSeen.add(cursor);
249
+ back.push(version);
250
+ cursor = version.parentId;
251
+ }
252
+ return [...later.reverse(), ...back];
253
+ }
254
+ /**
255
+ * Plans a prune over an in-memory store and validates the result. Pure: the caller
256
+ * decides whether to apply it. Throws InvalidVersionStore when the result would not be a
257
+ * store the cloud save accepts.
258
+ */
259
+ export function planPrune(versions, head, blobs, keep) {
260
+ if (!Number.isInteger(keep) || keep < 1)
261
+ throw new Error('--keep must be a whole number, at least 1');
262
+ if (head === null)
263
+ fail('version history has no head');
264
+ if (!versions.has(head))
265
+ fail('version head does not reference a version');
266
+ const line = versionLine(versions, head);
267
+ const keptLine = line.slice(0, keep);
268
+ // Head is what the working tree was restored to or saved as; it is never pruned. It
269
+ // sits below the later versions a restore back in time left ahead of it.
270
+ const headIndex = line.findIndex((v) => v.id === head);
271
+ if (headIndex >= keep)
272
+ throw new Error(`--keep ${keep} would drop the current version ${head}: ${headIndex} later version${headIndex === 1 ? ' is' : 's are'} ahead of it. Use --keep ${headIndex + 1} or more.`);
273
+ const lineIds = new Set(keptLine.map((v) => v.id));
274
+ // A branch off a kept version (a save made after restoring to it, superseded by a newer
275
+ // line) keeps its whole chain back to that version, so it stays as it was. A branch off a
276
+ // pruned version would lose its base, so it goes with it.
277
+ const descendsFromKept = (version) => {
278
+ const seen = new Set();
279
+ for (let cursor = version.id; cursor !== null && !seen.has(cursor);) {
280
+ if (lineIds.has(cursor))
281
+ return true;
282
+ seen.add(cursor);
283
+ cursor = versions.get(cursor)?.parentId ?? null;
284
+ }
285
+ return false;
286
+ };
287
+ const branches = [...versions.values()].filter((v) => !lineIds.has(v.id) && descendsFromKept(v));
288
+ const keptIds = new Set([...lineIds, ...branches.map((v) => v.id)]);
289
+ const kept = new Map();
290
+ const reRooted = [];
291
+ for (const version of [...keptLine, ...branches]) {
292
+ const parentKept = version.parentId !== null && keptIds.has(version.parentId);
293
+ if (parentKept) {
294
+ kept.set(version.id, version);
295
+ continue;
296
+ }
297
+ const root = asRoot(version);
298
+ const same = version.parentId === null && JSON.stringify(root.changes) === JSON.stringify(sortedChanges(version.changes));
299
+ kept.set(version.id, same ? version : root);
300
+ if (!same)
301
+ reRooted.push(version.id);
302
+ }
303
+ validateHistory(kept, head, (hash) => blobs.has(hash));
304
+ const removedSet = [...versions.keys()].filter((id) => !keptIds.has(id));
305
+ const depth = (id) => {
306
+ let d = 0;
307
+ const seen = new Set();
308
+ for (let cursor = id; cursor !== null && versions.has(cursor) && !seen.has(cursor); d++) {
309
+ seen.add(cursor);
310
+ cursor = versions.get(cursor).parentId;
311
+ }
312
+ return d;
313
+ };
314
+ const depths = new Map(removedSet.map((id) => [id, depth(id)]));
315
+ const removed = removedSet.sort((a, b) => depths.get(b) - depths.get(a) || a.localeCompare(b));
316
+ const needed = referencedHashes(kept.values());
317
+ const removedBlobs = [...blobs].filter((hash) => !needed.has(hash)).sort();
318
+ return { head, kept, reRooted, removed, removedBlobs };
319
+ }
320
+ function sortedChanges(changes) {
321
+ const out = {};
322
+ for (const p of Object.keys(changes).sort())
323
+ out[p] = { before: changes[p].before, after: changes[p].after };
324
+ return out;
325
+ }
326
+ function listDir(dir) {
327
+ try {
328
+ return fs.readdirSync(dir, { withFileTypes: true });
329
+ }
330
+ catch (error) {
331
+ if (error.code === 'ENOENT')
332
+ return [];
333
+ throw error;
334
+ }
335
+ }
336
+ // Strict, unlike readAllVersions: a version that will not parse is a store prune must not
337
+ // paper over, so it fails here with its name.
338
+ function readDiskStore(projectDir) {
339
+ const root = store.versionsRoot(projectDir);
340
+ const versions = new Map();
341
+ const blobs = new Set();
342
+ const unsupported = [];
343
+ for (const entry of listDir(root)) {
344
+ if (entry.name === 'head' && entry.isFile())
345
+ continue;
346
+ if ((entry.name === 'data' || entry.name === 'versions') && entry.isDirectory())
347
+ continue;
348
+ unsupported.push(entry.name);
349
+ }
350
+ for (const entry of listDir(path.join(root, 'data'))) {
351
+ if (entry.isFile() && HASH.test(entry.name))
352
+ blobs.add(entry.name);
353
+ else
354
+ unsupported.push(`data/${entry.name}`);
355
+ }
356
+ for (const entry of listDir(path.join(root, 'versions'))) {
357
+ const match = /^([A-Za-z0-9]{12})\.version$/.exec(entry.name);
358
+ if (!entry.isFile() || !match) {
359
+ unsupported.push(`versions/${entry.name}`);
360
+ continue;
361
+ }
362
+ let parsed;
363
+ try {
364
+ const bytes = fs.readFileSync(path.join(root, 'versions', entry.name));
365
+ const decoded = bytes.toString('utf8');
366
+ if (!Buffer.from(decoded, 'utf8').equals(bytes))
367
+ throw new Error('not UTF-8');
368
+ parsed = JSON.parse(decoded);
369
+ }
370
+ catch {
371
+ fail(`versions/${entry.name} is not valid JSON`);
372
+ }
373
+ versions.set(match[1], checkVersionShape(parsed, match[1]));
374
+ }
375
+ return { versions, head: store.readHead(projectDir), blobs, unsupported };
376
+ }
377
+ // The cloud save gunzips every blob with a 32 MiB bound and checks its hash; a kept blob
378
+ // that fails either would fail the save after the prune, so it fails the prune first.
379
+ function checkBlob(projectDir, hash) {
380
+ const file = path.join(store.versionsRoot(projectDir), 'data', hash);
381
+ let raw;
382
+ try {
383
+ raw = zlib.gunzipSync(fs.readFileSync(file), { maxOutputLength: MAX_FILE_BYTES });
384
+ }
385
+ catch {
386
+ fail(`data/${hash} is not a bounded gzip blob`);
387
+ }
388
+ if (store.hashBytes(raw) !== hash)
389
+ fail(`data/${hash} hash mismatch`);
390
+ }
391
+ function fileBytes(file) {
392
+ try {
393
+ return fs.statSync(file).size;
394
+ }
395
+ catch {
396
+ return 0;
397
+ }
398
+ }
399
+ /**
400
+ * Validates the store on disk with the cloud save's rules, blob bytes included. Throws
401
+ * InvalidVersionStore naming the first problem.
402
+ */
403
+ export function validateVersionStore(projectDir) {
404
+ const disk = readDiskStore(projectDir);
405
+ if (disk.unsupported.length > 0)
406
+ fail(`.castle/versions holds files that are not part of the store: ${disk.unsupported.slice(0, 5).join(', ')}`);
407
+ validateHistory(disk.versions, disk.head, (hash) => disk.blobs.has(hash));
408
+ for (const hash of referencedHashes(disk.versions.values()))
409
+ checkBlob(projectDir, hash);
410
+ }
411
+ /** Plans, validates and (unless dryRun) applies a prune. Writes nothing when it throws. */
412
+ /** A prune that applied and then found the store invalid: something raced it. */
413
+ export class PrunedButInvalid extends Error {
414
+ }
415
+ // A failed barrier stops the prune: deleting on past it would give up the order that keeps
416
+ // every on-disk state valid after a power loss. What was already removed leaves a valid store.
417
+ // Only "this filesystem cannot fsync a directory" is let through.
418
+ function fsyncDir(dir) {
419
+ let fd = null;
420
+ try {
421
+ fd = fs.openSync(dir, 'r');
422
+ fs.fsyncSync(fd);
423
+ }
424
+ catch (error) {
425
+ const code = error.code;
426
+ if (code !== 'EINVAL' && code !== 'ENOTSUP' && code !== 'EISDIR' && code !== 'EPERM')
427
+ throw new Error(`Prune stopped partway: could not make ${path.basename(dir)}/ durable (${code ?? String(error)}). The history left on disk is valid; run prune-versions again.`);
428
+ }
429
+ finally {
430
+ if (fd !== null)
431
+ fs.closeSync(fd);
432
+ }
433
+ }
434
+ /** Plans, validates and (unless dryRun) applies a prune. Writes nothing when it throws
435
+ * InvalidVersionStore. Holds the store's lock throughout, so no save or restore interleaves. */
436
+ export function pruneVersionStore(projectDir, opts) {
437
+ return store.withVersionLock(projectDir, () => pruneLocked(projectDir, opts));
438
+ }
439
+ function pruneLocked(projectDir, opts) {
440
+ const disk = readDiskStore(projectDir);
441
+ if (disk.versions.size === 0 && disk.head === null)
442
+ throw new Error('No versions yet.');
443
+ if (disk.unsupported.length > 0)
444
+ fail(`.castle/versions holds files that are not part of the store: ${disk.unsupported.slice(0, 5).join(', ')}`);
445
+ const plan = planPrune(disk.versions, disk.head, disk.blobs, opts.keep);
446
+ for (const hash of referencedHashes(plan.kept.values()))
447
+ checkBlob(projectDir, hash);
448
+ const root = store.versionsRoot(projectDir);
449
+ const versionPath = (id) => path.join(root, 'versions', `${id}${store.VERSION_EXT}`);
450
+ const blobPath = (hash) => path.join(root, 'data', hash);
451
+ let bytesFreed = 0;
452
+ for (const id of plan.removed)
453
+ bytesFreed += fileBytes(versionPath(id));
454
+ for (const hash of plan.removedBlobs)
455
+ bytesFreed += fileBytes(blobPath(hash));
456
+ if (opts.dryRun)
457
+ return { plan, bytesFreed, applied: false };
458
+ // 1. Re-roots: an atomic replace, kept read-only like every version file.
459
+ for (const id of plan.reRooted)
460
+ atomicWriteFileSync(versionPath(id), JSON.stringify(plan.kept.get(id), null, 2) + '\n', { mode: 0o444 });
461
+ // 2. Dropped versions, children before parents, so no version is left with a missing
462
+ // parent. Each removal is made durable before the next, so the order survives power loss too.
463
+ const versionsDir = path.join(root, 'versions');
464
+ for (const id of plan.removed) {
465
+ fs.rmSync(versionPath(id), { force: true });
466
+ fsyncDir(versionsDir);
467
+ }
468
+ // 3. Blobs, now that no version on disk references them.
469
+ for (const hash of plan.removedBlobs)
470
+ fs.rmSync(blobPath(hash), { force: true });
471
+ fsyncDir(path.join(root, 'data'));
472
+ // The store on disk must now be what was validated; anything else (a save that raced the
473
+ // prune) is reported rather than left for the cloud save to find.
474
+ try {
475
+ const after = readDiskStore(projectDir);
476
+ validateHistory(after.versions, after.head, (hash) => after.blobs.has(hash));
477
+ }
478
+ catch (error) {
479
+ throw new PrunedButInvalid(error instanceof Error ? error.message : String(error));
480
+ }
481
+ return { plan, bytesFreed, applied: true };
482
+ }
483
+ function formatBytes(bytes) {
484
+ if (bytes < 1024)
485
+ return `${bytes} B`;
486
+ if (bytes < 1024 * 1024)
487
+ return `${(bytes / 1024).toFixed(1)} KB`;
488
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
489
+ }
490
+ export function pruneVersions(dir, opts) {
491
+ const projectDir = path.resolve(dir);
492
+ let outcome;
493
+ try {
494
+ outcome = pruneVersionStore(projectDir, opts);
495
+ }
496
+ catch (error) {
497
+ const message = error instanceof Error ? error.message : String(error);
498
+ console.error(error instanceof PrunedButInvalid
499
+ ? `Pruned, but the version history no longer validates (${message}): something changed it during the prune.`
500
+ : error instanceof InvalidVersionStore
501
+ ? `Not pruning: the result would not be a valid version history (${message}). Nothing was changed.`
502
+ : message);
503
+ process.exit(1);
504
+ }
505
+ const { plan, bytesFreed, applied } = outcome;
506
+ const verb = applied ? 'Removed' : 'Would remove';
507
+ const oldest = [...plan.kept.values()].find((v) => v.parentId === null);
508
+ console.log(`${verb} ${plan.removed.length} version${plan.removed.length === 1 ? '' : 's'} and ${plan.removedBlobs.length} stored file${plan.removedBlobs.length === 1 ? '' : 's'} (${formatBytes(bytesFreed)}); keeping ${plan.kept.size}.`);
509
+ if (oldest && plan.reRooted.length > 0)
510
+ console.log(`${applied ? 'Rewrote' : 'Would rewrite'} ${plan.reRooted.join(', ')} as the oldest version (it now records every file as added).`);
511
+ if (!applied)
512
+ console.log('Dry run: nothing was changed. Run again without --dry-run to prune.');
513
+ }
@@ -15,6 +15,8 @@ export interface Version {
15
15
  changes: Record<string, VersionChange>;
16
16
  }
17
17
  export declare function versionsRoot(projectDir: string): string;
18
+ export declare function versionLockPath(projectDir: string): string;
19
+ export declare function withVersionLock<T>(projectDir: string, fn: () => T, waitMs?: number): T;
18
20
  export declare function readHead(projectDir: string): string | null;
19
21
  export declare function writeHead(projectDir: string, id: string): void;
20
22
  export declare const VERSION_EXT = ".version";
@@ -42,6 +42,70 @@ function versionsDir(projectDir) {
42
42
  function headPath(projectDir) {
43
43
  return path.join(versionsRoot(projectDir), 'head');
44
44
  }
45
+ // One writer at a time across processes: the serve's Save version button, the CLI's
46
+ // save-version and restore-version, and prune-versions, which deletes blobs a racing save
47
+ // could otherwise reuse. It lives in `.castle/runtime/`, which the cloud capture leaves out:
48
+ // `.castle/versions/` itself must hold only versions, blobs and head, and any other
49
+ // `.castle/` path the capture keeps is rejected as private source state.
50
+ export function versionLockPath(projectDir) {
51
+ return path.join(projectDir, '.castle', 'runtime', 'versions.lock');
52
+ }
53
+ const LOCK_WAIT_MS = 15_000;
54
+ function lockWaitMs() {
55
+ const fromEnv = Number(process.env.CASTLE_VERSION_LOCK_WAIT_MS);
56
+ return Number.isFinite(fromEnv) && fromEnv >= 0 ? fromEnv : LOCK_WAIT_MS;
57
+ }
58
+ function sleepSync(ms) {
59
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
60
+ }
61
+ /** Who holds the lock, for the refusal: its pid and age, when the file says. */
62
+ function describeHolder(file) {
63
+ try {
64
+ const pid = Number(fs.readFileSync(file, 'utf-8').split(' ')[0]);
65
+ const minutes = Math.floor((Date.now() - fs.statSync(file).mtimeMs) / 60_000);
66
+ return `${Number.isInteger(pid) && pid > 0 ? `process ${pid}, ` : ''}taken ${minutes} minute${minutes === 1 ? '' : 's'} ago`;
67
+ }
68
+ catch {
69
+ return 'holder unknown';
70
+ }
71
+ }
72
+ // Never broken automatically. Without OS file locks, removing a lock that looks abandoned is
73
+ // a check followed by a removal, and between the two another process can take a fresh lock
74
+ // that the removal then takes away: two writers. Every operation under the lock is a matter
75
+ // of seconds, so a lock that outlives its wait was left by a crash, and the refusal says how
76
+ // to clear it.
77
+ export function withVersionLock(projectDir, fn, waitMs = lockWaitMs()) {
78
+ const file = versionLockPath(projectDir);
79
+ fs.mkdirSync(path.dirname(file), { recursive: true });
80
+ const token = `${process.pid} ${Date.now()} ${crypto.randomBytes(8).toString('hex')}\n`;
81
+ const deadline = Date.now() + waitMs;
82
+ for (;;) {
83
+ try {
84
+ fs.writeFileSync(file, token, { flag: 'wx' });
85
+ break;
86
+ }
87
+ catch (error) {
88
+ if (error.code !== 'EEXIST')
89
+ throw error;
90
+ if (Date.now() >= deadline)
91
+ throw new Error(`Another version operation (save, restore or prune) holds this deck's version lock (${describeHolder(file)}). ` +
92
+ `If none is running -- one crashed -- delete ${path.relative(projectDir, file)} and try again.`);
93
+ sleepSync(100);
94
+ }
95
+ }
96
+ try {
97
+ return fn();
98
+ }
99
+ finally {
100
+ try {
101
+ if (fs.readFileSync(file, 'utf-8') === token)
102
+ fs.rmSync(file, { force: true });
103
+ }
104
+ catch {
105
+ // Already gone.
106
+ }
107
+ }
108
+ }
45
109
  export function readHead(projectDir) {
46
110
  try {
47
111
  const id = fs.readFileSync(headPath(projectDir), 'utf-8').trim();
package/dist/versions.js CHANGED
@@ -83,6 +83,9 @@ function manifestFromSelection(projectDir, parentFiles, selected) {
83
83
  // The save itself, with no output -- what the CLI command and the editor's
84
84
  // Save version button both run.
85
85
  export function createVersion(projectDir, opts = {}) {
86
+ return store.withVersionLock(projectDir, () => createVersionLocked(projectDir, opts));
87
+ }
88
+ function createVersionLocked(projectDir, opts) {
86
89
  const parentId = store.readHead(projectDir);
87
90
  const parentFiles = store.parentManifest(projectDir, parentId);
88
91
  const given = opts.paths ?? [];
@@ -405,6 +408,9 @@ export class NotOnThisLine extends Error {
405
408
  // the message names every conflicting path, since that list IS the answer to
406
409
  // "what would I lose".
407
410
  export function applyVersionRestore(projectDir, targetId, opts = {}) {
411
+ return store.withVersionLock(projectDir, () => applyVersionRestoreLocked(projectDir, targetId, opts));
412
+ }
413
+ function applyVersionRestoreLocked(projectDir, targetId, opts) {
408
414
  if (!store.versionExists(projectDir, targetId))
409
415
  throw new Error(`No such version: ${targetId}`);
410
416
  if (store.readHead(projectDir) === targetId) {
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-11-18T02:15:05.726Z",
85
+ "publishedVersion": "2026-11-18T04:23:12.485Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -233,7 +233,8 @@ dev serve.
233
233
  - `session.hub.place`, `.title` and `.result` are the place and the result shape
234
234
  as published (`result` is `null` for a place that reports none, such as a town).
235
235
  - `session.hub.reconnectWindowMs`, when present, is Castle's pinned hub-place
236
- reconnect grace in milliseconds, inclusive at the deadline. It is absent on
236
+ reconnect grace in milliseconds, inclusive at the deadline (at most 180000, or
237
+ 300000 on an owner house that opted into `houseResume`). It is absent on
237
238
  sessions without a pinned grace and older hosts. Kits use it to match visit retention to the
238
239
  transport window; deck code does not choose it.
239
240
  - `session.hub.arrival(playerId)` is how a player came in when Castle placed them
@@ -46,9 +46,13 @@ function unavailable(op, what) {
46
46
  operation: `session.hub.${op}`,
47
47
  });
48
48
  }
49
+ // An opted-in owner house may be pinned up to 300 s (a three-minute app switch keeps
50
+ // it); every other hub place keeps the host's 180 s cap.
49
51
  function reconnectMetadata(pinned) {
50
52
  const value = pinned.reconnectWindowMs;
51
- return pinned.result === null && typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 180_000
53
+ const cap = pinned.houseResume === true && typeof pinned.owner === "string" && pinned.owner.length > 0
54
+ ? 300_000 : 180_000;
55
+ return pinned.result === null && typeof value === "number" && Number.isInteger(value) && value > 0 && value <= cap
52
56
  ? { reconnectWindowMs: value } : {};
53
57
  }
54
58
  export function createServerHub(platformHandle, arrivals, hiddenPair = () => false) {
@@ -126,6 +126,8 @@ export interface PlatformHubPlace {
126
126
  version: 1;
127
127
  };
128
128
  owner?: string;
129
+ /** Ghost's trusted owner-house opt-in; such a house may pin up to 300 s of grace. */
130
+ houseResume?: true;
129
131
  reconnectWindowMs?: number;
130
132
  place?: string;
131
133
  title?: string | null;
@@ -5584,7 +5584,11 @@ for a place without a result. Ghost grants it to the host only on a trusted
5584
5584
  owner-house instance. Key absent keeps existing manifest and wire bytes.
5585
5585
 
5586
5586
  Ghost stamps the grace value `reconnectWindowMs: 180000` into the owner-house
5587
- session spec. A capable host retains each disconnected participant and token
5587
+ session spec, or `300000` when the chosen host advertises
5588
+ `supportsHouseResumeWindowMs: 300000` (so an owner's three-minute app switch,
5589
+ whose socket closes a few seconds after the page hides, keeps the house); the
5590
+ base SDK passes a value up to 300000 to `session.hub.reconnectWindowMs` only on
5591
+ such an owner house, and every other place keeps the 180000 cap. A capable host retains each disconnected participant and token
5588
5592
  through that deadline and keeps an empty opted-in house alive for that window. A guest reconnect is
5589
5593
  admitted only into that same live instance while its owner has a live connection;
5590
5594
  otherwise the existing spent-handoff recovery returns through the Town ticket.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.242",
3
+ "version": "0.4.243",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"