castle-web-cli 0.4.219 → 0.4.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.js CHANGED
@@ -47,7 +47,7 @@ import { createPlaywrightPlaytestExecutor } from './native/playtest-executor.js'
47
47
  import { createRemotePlaytestExecutor } from './native/playtest-remote.js';
48
48
  import { runPlaytest, } from './native/playtest.js';
49
49
  import { AGENT_ROLE_ENV, cloudGitMode } from './cloudGit.js';
50
- import { createServeGitHooks } from './cloudGitServe.js';
50
+ import { createServeGitHooks, createServeMarkerPoll } from './cloudGitServe.js';
51
51
  export const AGENT_WS_PATH = '/__castle/agent';
52
52
  const DEFAULT_SETTINGS = {
53
53
  // Both roles run the claude CLI routed through OpenRouter at the slug below.
@@ -4158,6 +4158,15 @@ export function createAgentServer(opts) {
4158
4158
  routerBusy: () => routerQueue.isRunning(),
4159
4159
  enqueueInstruction: (text) => routerQueue.handleUserMessage(text, undefined, undefined, undefined, true),
4160
4160
  });
4161
+ // Markers that need no git (the saved copy of the deck is newer than this folder) become
4162
+ // router turns with git off too; with git on, the hooks above consume them.
4163
+ const markerPoll = gitHooks
4164
+ ? null
4165
+ : createServeMarkerPoll({
4166
+ deckDir,
4167
+ addLog,
4168
+ enqueueInstruction: (text) => routerQueue.handleUserMessage(text, undefined, undefined, undefined, true),
4169
+ });
4161
4170
  const taskStore = createTaskStore({
4162
4171
  deckDir,
4163
4172
  deckLabel,
@@ -4378,6 +4387,7 @@ export function createAgentServer(opts) {
4378
4387
  }
4379
4388
  function shutdown() {
4380
4389
  gitHooks?.stop();
4390
+ markerPoll?.stop();
4381
4391
  taskStore.shutdown();
4382
4392
  for (const child of [...taskChildren, ...routerChildren]) {
4383
4393
  try {
package/dist/api.d.ts CHANGED
@@ -166,6 +166,8 @@ export declare function saveCauldronServerBundle(deckId: string, uploadId: strin
166
166
  export interface WebDeckSource {
167
167
  deckId: string;
168
168
  archiveUrl: string;
169
+ /** Unique per saved version: every save mints a new one (webSourceSync.ts compares it). */
170
+ s3Key: string;
169
171
  updatedAt: string;
170
172
  }
171
173
  export interface DeckMeta {
@@ -177,7 +179,7 @@ export interface DeckMeta {
177
179
  }
178
180
  export declare function deckMeta(deckId: string): Promise<DeckMeta | null>;
179
181
  export declare function webDeckSource(deckId: string): Promise<WebDeckSource | null>;
180
- export declare function saveWebDeckSource(deckId: string, uploadId: string): Promise<WebDeckSource>;
182
+ export declare function saveWebDeckSource(deckId: string, uploadId: string, expectedS3Key?: string | null): Promise<WebDeckSource>;
181
183
  export type CloudDeckKit = 'PHYSICS_2D' | 'PHYSICS_3D' | 'MULTIPLAYER_2D' | 'MULTIPLAYER_3D' | 'TURN_BASED' | 'NONE';
182
184
  export interface RegisteredCloudDeck {
183
185
  deckId: string;
package/dist/api.js CHANGED
@@ -286,18 +286,29 @@ export async function deckMeta(deckId) {
286
286
  export async function webDeckSource(deckId) {
287
287
  const data = await graphql(`query($deckId: ID!) {
288
288
  webDeckSource(deckId: $deckId) {
289
- deckId archiveUrl updatedAt
289
+ deckId archiveUrl s3Key updatedAt
290
290
  }
291
291
  }`, { deckId });
292
292
  handleAPIError(data);
293
293
  return pickData(data, 'webDeckSource');
294
294
  }
295
- export async function saveWebDeckSource(deckId, uploadId) {
296
- const data = await graphql(`mutation($deckId: ID!, $uploadId: ID!) {
295
+ // `expectedS3Key` is the save precondition: omitted (undefined) means no check, null means
296
+ // "there must be no saved source yet", and a key means "the saved source must still be this
297
+ // one" -- otherwise Ghost refuses with WEB_DECK_SOURCE_STALE. The argument is left out of the
298
+ // document entirely when omitted, so the request is exactly what older CLIs sent.
299
+ export async function saveWebDeckSource(deckId, uploadId, expectedS3Key) {
300
+ const checked = expectedS3Key !== undefined;
301
+ const data = await graphql(checked
302
+ ? `mutation($deckId: ID!, $uploadId: ID!, $expectedS3Key: String) {
303
+ saveWebDeckSource(deckId: $deckId, uploadId: $uploadId, expectedS3Key: $expectedS3Key) {
304
+ deckId archiveUrl s3Key updatedAt
305
+ }
306
+ }`
307
+ : `mutation($deckId: ID!, $uploadId: ID!) {
297
308
  saveWebDeckSource(deckId: $deckId, uploadId: $uploadId) {
298
- deckId archiveUrl updatedAt
309
+ deckId archiveUrl s3Key updatedAt
299
310
  }
300
- }`, { deckId, uploadId });
311
+ }`, checked ? { deckId, uploadId, expectedS3Key } : { deckId, uploadId });
301
312
  handleAPIError(data);
302
313
  return pickData(data, 'saveWebDeckSource');
303
314
  }
@@ -33,8 +33,15 @@ export declare const HISTORY_RECOVERED_FILE: string;
33
33
  export declare const RECOVERED_COMMIT_MESSAGE = "Edits restored after lost history";
34
34
  /** Written with it, once: the notice and instruction the serve turns into an agent turn. */
35
35
  export declare const HISTORY_LOST_MARKER_FILE: string;
36
+ /**
37
+ * Written by `source-status --notify` when the deck's saved copy is newer than this folder
38
+ * (webSourceSync.ts). Not a git marker: the serve consumes it with git off too.
39
+ */
40
+ export declare const WEB_SOURCE_NEWER_MARKER_FILE: string;
36
41
  /** Every marker the serve turns into an agent turn. */
37
42
  export declare const AGENT_MARKER_FILES: readonly string[];
43
+ /** The markers the serve consumes whether or not git is on (CASTLE_GIT). */
44
+ export declare const UNGATED_AGENT_MARKER_FILES: readonly string[];
38
45
  /** The serve's note that task agents (or the router) are working in the deck; see deckBusy. */
39
46
  export declare const BUSY_FILE: string;
40
47
  /** The remote has (or may have) work that waits to be merged until the deck is idle. */
package/dist/cloudGit.js CHANGED
@@ -82,8 +82,20 @@ export const HISTORY_RECOVERED_FILE = path.join('.castle', 'agent', 'git-history
82
82
  export const RECOVERED_COMMIT_MESSAGE = 'Edits restored after lost history';
83
83
  /** Written with it, once: the notice and instruction the serve turns into an agent turn. */
84
84
  export const HISTORY_LOST_MARKER_FILE = path.join('.castle', 'agent', 'git-history-lost.json');
85
+ /**
86
+ * Written by `source-status --notify` when the deck's saved copy is newer than this folder
87
+ * (webSourceSync.ts). Not a git marker: the serve consumes it with git off too.
88
+ */
89
+ export const WEB_SOURCE_NEWER_MARKER_FILE = path.join('.castle', 'agent', 'web-source-newer.json');
85
90
  /** Every marker the serve turns into an agent turn. */
86
- export const AGENT_MARKER_FILES = [CONFLICT_MARKER_FILE, ADOPTED_MARKER_FILE, HISTORY_LOST_MARKER_FILE];
91
+ export const AGENT_MARKER_FILES = [
92
+ CONFLICT_MARKER_FILE,
93
+ ADOPTED_MARKER_FILE,
94
+ HISTORY_LOST_MARKER_FILE,
95
+ WEB_SOURCE_NEWER_MARKER_FILE,
96
+ ];
97
+ /** The markers the serve consumes whether or not git is on (CASTLE_GIT). */
98
+ export const UNGATED_AGENT_MARKER_FILES = [WEB_SOURCE_NEWER_MARKER_FILE];
87
99
  /** The serve's note that task agents (or the router) are working in the deck; see deckBusy. */
88
100
  export const BUSY_FILE = path.join('.castle', 'agent', 'git-busy.json');
89
101
  /** The remote has (or may have) work that waits to be merged until the deck is idle. */
@@ -37,5 +37,30 @@ export declare function runCastleWeb(args: string[], cwd: string, env?: NodeJS.P
37
37
  code: number;
38
38
  output: string;
39
39
  }>;
40
+ type MarkerSink = Pick<ServeGitHooksOptions, 'addLog' | 'enqueueInstruction'>;
41
+ /**
42
+ * One `.castle/agent/*.json` marker `{ notice?, instruction }` becomes a chat line and a hidden
43
+ * router turn. The file is deleted before anything else, so a throw can never turn one marker
44
+ * into a loop of turns. True when a turn was queued.
45
+ */
46
+ export declare function consumeAgentMarker(deckDir: string, rel: string, sink: MarkerSink, beforeTurn?: () => void): boolean;
47
+ export interface ServeMarkerPoll {
48
+ /** Check for markers now (the poll does this on its own). */
49
+ check(): void;
50
+ stop(): void;
51
+ }
52
+ /**
53
+ * The marker poll for a serve without git (createServeGitHooks returns null): the markers that
54
+ * need no git (UNGATED_AGENT_MARKER_FILES, e.g. the saved-copy-is-newer notice) still become
55
+ * router turns. With git on, the git hooks' own poll consumes these along with the git ones, so
56
+ * exactly one poll runs either way. A file rather than an env var because a reused serve never
57
+ * sees new env, and the first check runs at start for a marker left while the serve was down.
58
+ */
59
+ export declare function createServeMarkerPoll(opts: MarkerSink & {
60
+ deckDir: string;
61
+ pollMs?: number;
62
+ files?: readonly string[];
63
+ }): ServeMarkerPoll;
40
64
  /** Null unless the serve runs with CASTLE_GIT=on. Whether the deck is attached is asked per commit. */
41
65
  export declare function createServeGitHooks(opts: ServeGitHooksOptions): ServeGitHooks | null;
66
+ export {};
@@ -2,7 +2,7 @@ import { spawn } from 'child_process';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
4
  import { fileURLToPath } from 'url';
5
- import { AGENT_MARKER_FILES, cloudGitModeAsync, CONFLICT_MARKER_FILE, DEADLINE_ENV, EXIT_CONFLICT, EXIT_NOT_ENABLED, mergeWaiting, readLeavePending, readMergeState, setDeckBusy, } from './cloudGit.js';
5
+ import { AGENT_MARKER_FILES, cloudGitModeAsync, CONFLICT_MARKER_FILE, DEADLINE_ENV, EXIT_CONFLICT, EXIT_NOT_ENABLED, mergeWaiting, readLeavePending, readMergeState, setDeckBusy, UNGATED_AGENT_MARKER_FILES, } from './cloudGit.js';
6
6
  // The serve's half of git in the cloud sandbox (castle-sandboxes docs/git-remotes-phase2.md):
7
7
  // - `commit --reason turn` when the router settles with the task board idle,
8
8
  // - `commit --reason task` when the task board goes idle,
@@ -110,6 +110,61 @@ function taskMessage(titles) {
110
110
  const more = titles.length > MAX_TITLES_IN_MESSAGE ? ` (+${titles.length - MAX_TITLES_IN_MESSAGE} more)` : '';
111
111
  return `${titles.length === 1 ? 'Task' : 'Tasks'}: ${shown}${more}`;
112
112
  }
113
+ /**
114
+ * One `.castle/agent/*.json` marker `{ notice?, instruction }` becomes a chat line and a hidden
115
+ * router turn. The file is deleted before anything else, so a throw can never turn one marker
116
+ * into a loop of turns. True when a turn was queued.
117
+ */
118
+ export function consumeAgentMarker(deckDir, rel, sink, beforeTurn) {
119
+ const file = path.join(deckDir, rel);
120
+ let report;
121
+ try {
122
+ report = JSON.parse(fs.readFileSync(file, 'utf-8'));
123
+ }
124
+ catch (e) {
125
+ if (e.code !== 'ENOENT')
126
+ fs.rmSync(file, { force: true });
127
+ return false;
128
+ }
129
+ fs.rmSync(file, { force: true });
130
+ if (typeof report.instruction !== 'string' || !report.instruction)
131
+ return false;
132
+ sink.addLog(typeof report.notice === 'string' && report.notice ? report.notice : CONFLICT_NOTICE);
133
+ beforeTurn?.();
134
+ sink.enqueueInstruction(report.instruction);
135
+ return true;
136
+ }
137
+ /**
138
+ * The marker poll for a serve without git (createServeGitHooks returns null): the markers that
139
+ * need no git (UNGATED_AGENT_MARKER_FILES, e.g. the saved-copy-is-newer notice) still become
140
+ * router turns. With git on, the git hooks' own poll consumes these along with the git ones, so
141
+ * exactly one poll runs either way. A file rather than an env var because a reused serve never
142
+ * sees new env, and the first check runs at start for a marker left while the serve was down.
143
+ */
144
+ export function createServeMarkerPoll(opts) {
145
+ const files = opts.files ?? UNGATED_AGENT_MARKER_FILES;
146
+ const check = () => {
147
+ for (const rel of files) {
148
+ try {
149
+ consumeAgentMarker(opts.deckDir, rel, opts);
150
+ }
151
+ catch (err) {
152
+ console.error(`[serve] could not read the agent marker ${rel}: ${String(err)}`);
153
+ }
154
+ }
155
+ };
156
+ const poll = setInterval(check, opts.pollMs ?? CONFLICT_POLL_MS);
157
+ poll.unref();
158
+ // Not synchronously: the caller wires the router queue up after creating this.
159
+ const first = setImmediate(check);
160
+ return {
161
+ check,
162
+ stop() {
163
+ clearInterval(poll);
164
+ clearImmediate(first);
165
+ },
166
+ };
167
+ }
113
168
  /** Null unless the serve runs with CASTLE_GIT=on. Whether the deck is attached is asked per commit. */
114
169
  export function createServeGitHooks(opts) {
115
170
  const env = opts.env ?? process.env;
@@ -190,26 +245,12 @@ export function createServeGitHooks(opts) {
190
245
  drain();
191
246
  }
192
247
  function consumeMarker(rel) {
193
- const file = path.join(opts.deckDir, rel);
194
- let report;
195
- try {
196
- report = JSON.parse(fs.readFileSync(file, 'utf-8'));
197
- }
198
- catch (e) {
199
- if (e.code !== 'ENOENT')
200
- fs.rmSync(file, { force: true });
201
- return;
202
- }
203
- // Consumed first, so a throw below can never turn one marker into a loop of turns.
204
- fs.rmSync(file, { force: true });
205
- if (typeof report.instruction !== 'string' || !report.instruction)
206
- return;
207
- opts.addLog(typeof report.notice === 'string' && report.notice ? report.notice : CONFLICT_NOTICE);
208
- if (rel === CONFLICT_MARKER_FILE) {
209
- resolverInFlight = true;
210
- lastRaisedAt = now();
211
- }
212
- opts.enqueueInstruction(report.instruction);
248
+ consumeAgentMarker(opts.deckDir, rel, opts, () => {
249
+ if (rel === CONFLICT_MARKER_FILE) {
250
+ resolverInFlight = true;
251
+ lastRaisedAt = now();
252
+ }
253
+ });
213
254
  }
214
255
  function checkConflict() {
215
256
  for (const rel of AGENT_MARKER_FILES)
@@ -1,4 +1,21 @@
1
1
  export declare function getDeck(dir: string, options?: {
2
2
  deckId?: string;
3
3
  force?: boolean;
4
+ side?: boolean;
5
+ json?: boolean;
4
6
  }): Promise<void>;
7
+ /** A save time as a folder name: `20260818-132107` (UTC), or null if unparseable. */
8
+ export declare function savedSourceStamp(updatedAt: string): string | null;
9
+ /**
10
+ * The saved-source root inside `deckDir`, created if needed, or an error naming why it is not
11
+ * safe to write into: `.castle`, `.castle/agent`, `.castle/agent/saved-source` and every stamped
12
+ * copy must be real directories (never symlinks), and the root must resolve inside the deck.
13
+ * The folder is written by whatever runs in the deck, so a link here could aim the replace and
14
+ * the prune at files outside it.
15
+ */
16
+ export declare function prepareSavedSourceRoot(deckDir: string): string;
17
+ /**
18
+ * Removes all but the `keep` newest stamped copies; returns what it removed. Only real
19
+ * directories named like a stamp are candidates: anything else there is left alone.
20
+ */
21
+ export declare function pruneSavedSources(root: string, keep?: number): string[];
package/dist/get-deck.js CHANGED
@@ -6,6 +6,7 @@ import * as api from './api.js';
6
6
  import { normalizeDeckPackageJson } from './normalize.js';
7
7
  import { archiveSource, downloadSourceArchive, runTar, SOURCE_ARCHIVE_EXCLUDES, } from './save-deck.js';
8
8
  import { readCastleJson } from './castleJson.js';
9
+ import { SAVED_SOURCE_DIR, SAVED_SOURCE_KEEP, writeSyncMarker } from './webSourceSync.js';
9
10
  // Refreshing a deck already in the target replaces its source, so a file deleted
10
11
  // upstream actually disappears here -- untarring over the old tree would leave it
11
12
  // behind. What survives is exactly what the source archive doesn't carry, and it
@@ -48,6 +49,10 @@ function newestSourceMtime(dir) {
48
49
  //
49
50
  // Deps are left to `castle-web install`, like a git pull leaves them to you.
50
51
  export async function getDeck(dir, options = {}) {
52
+ if (options.side) {
53
+ await getDeckSide(dir, options);
54
+ return;
55
+ }
51
56
  const targetDir = path.resolve(dir);
52
57
  const localDeckId = readCastleJson(targetDir)?.deckId;
53
58
  const deckId = options.deckId ?? localDeckId;
@@ -113,8 +118,152 @@ export async function getDeck(dir, options = {}) {
113
118
  }
114
119
  catch { /* nothing to clean */ }
115
120
  }
121
+ // The folder's lineage is now exactly this saved version (webSourceSync.ts).
122
+ writeSyncMarker(targetDir, deckId, source, 'get-deck');
116
123
  if (normalizeDeckPackageJson(targetDir)) {
117
124
  console.log(`Repointed package.json at this machine's sdk/cli`);
118
125
  }
119
126
  console.log(`${refreshing ? 'Updated' : 'Extracted to'} ${targetDir}`);
120
127
  }
128
+ /** A save time as a folder name: `20260818-132107` (UTC), or null if unparseable. */
129
+ export function savedSourceStamp(updatedAt) {
130
+ const ms = Date.parse(updatedAt);
131
+ if (!Number.isFinite(ms))
132
+ return null;
133
+ return new Date(ms).toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '-');
134
+ }
135
+ const STAMP_RE = /^\d{8}-\d{6}$/;
136
+ function lstatIfPresent(file) {
137
+ try {
138
+ return fs.lstatSync(file);
139
+ }
140
+ catch (e) {
141
+ if (e.code === 'ENOENT')
142
+ return null;
143
+ throw e;
144
+ }
145
+ }
146
+ /**
147
+ * The saved-source root inside `deckDir`, created if needed, or an error naming why it is not
148
+ * safe to write into: `.castle`, `.castle/agent`, `.castle/agent/saved-source` and every stamped
149
+ * copy must be real directories (never symlinks), and the root must resolve inside the deck.
150
+ * The folder is written by whatever runs in the deck, so a link here could aim the replace and
151
+ * the prune at files outside it.
152
+ */
153
+ export function prepareSavedSourceRoot(deckDir) {
154
+ let current = deckDir;
155
+ for (const part of SAVED_SOURCE_DIR.split(path.sep)) {
156
+ current = path.join(current, part);
157
+ const stat = lstatIfPresent(current);
158
+ if (!stat) {
159
+ fs.mkdirSync(current);
160
+ continue;
161
+ }
162
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
163
+ throw new Error(`Refusing to use ${current}: it is ${stat.isSymbolicLink() ? 'a symlink' : 'not a directory'}.`);
164
+ }
165
+ }
166
+ const realDeck = fs.realpathSync(deckDir);
167
+ const realRoot = fs.realpathSync(current);
168
+ if (path.relative(realDeck, realRoot).startsWith('..') || path.isAbsolute(path.relative(realDeck, realRoot))) {
169
+ throw new Error(`Refusing to use ${current}: it resolves outside the deck (${realRoot}).`);
170
+ }
171
+ for (const name of fs.readdirSync(current)) {
172
+ if (!STAMP_RE.test(name))
173
+ continue;
174
+ const stat = fs.lstatSync(path.join(current, name));
175
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
176
+ throw new Error(`Refusing to use ${path.join(current, name)}: it is ${stat.isSymbolicLink() ? 'a symlink' : 'not a directory'}.`);
177
+ }
178
+ }
179
+ return current;
180
+ }
181
+ /**
182
+ * Removes all but the `keep` newest stamped copies; returns what it removed. Only real
183
+ * directories named like a stamp are candidates: anything else there is left alone.
184
+ */
185
+ export function pruneSavedSources(root, keep = SAVED_SOURCE_KEEP) {
186
+ let names;
187
+ try {
188
+ names = fs.readdirSync(root).filter((name) => {
189
+ if (!STAMP_RE.test(name))
190
+ return false;
191
+ const stat = lstatIfPresent(path.join(root, name));
192
+ return stat !== null && stat.isDirectory() && !stat.isSymbolicLink();
193
+ });
194
+ }
195
+ catch {
196
+ return [];
197
+ }
198
+ const removed = names.sort().reverse().slice(keep);
199
+ for (const name of removed)
200
+ fs.rmSync(path.join(root, name), { recursive: true, force: true });
201
+ return removed;
202
+ }
203
+ // `get-deck <dir> --side`: the deck's current saved source, fetched beside the folder into
204
+ // `.castle/agent/saved-source/<stamp>/` for comparing -- not installed, not served, and nothing
205
+ // of the folder's own (its source files, its sync marker) is touched. Excluded from the source
206
+ // archive and kept by deck persistence, like the rest of `.castle/agent/`.
207
+ async function getDeckSide(dir, options) {
208
+ const targetDir = path.resolve(dir);
209
+ const localDeckId = readCastleJson(targetDir)?.deckId;
210
+ if (!fs.existsSync(targetDir) || !fs.statSync(targetDir).isDirectory()) {
211
+ console.error(`--side fetches the saved copy beside an existing deck folder; ${targetDir} does not exist.`);
212
+ process.exit(1);
213
+ }
214
+ const deckId = options.deckId ?? localDeckId;
215
+ if (!deckId) {
216
+ console.error(`No deckId. Either pass --deck-id <id> or run from a directory whose castle.json has one.`);
217
+ process.exit(1);
218
+ }
219
+ if (localDeckId && deckId !== localDeckId) {
220
+ console.error(`This directory holds deck ${localDeckId}, but --deck-id ${deckId} was passed.`);
221
+ process.exit(1);
222
+ }
223
+ const source = await api.webDeckSource(deckId);
224
+ if (!source) {
225
+ console.error(`No source archive on server for deck ${deckId}.`);
226
+ process.exit(1);
227
+ }
228
+ const stamp = savedSourceStamp(source.updatedAt);
229
+ if (!stamp) {
230
+ console.error(`Unreadable save time from the server (${source.updatedAt}).`);
231
+ process.exit(1);
232
+ }
233
+ // With --json, stdout is the one result line.
234
+ const log = options.json ? (line) => console.error(line) : (line) => console.log(line);
235
+ let root;
236
+ try {
237
+ root = prepareSavedSourceRoot(targetDir);
238
+ }
239
+ catch (e) {
240
+ console.error(e instanceof Error ? e.message : String(e));
241
+ process.exit(1);
242
+ }
243
+ const dest = path.join(root, stamp);
244
+ const tmpFile = await downloadSourceArchive(source, 'castle-side', log);
245
+ // Extracted beside the destination and renamed in, so a failed extract never leaves a
246
+ // half-written copy under a real stamp (and tmp may be another filesystem).
247
+ const staging = path.join(root, `.partial-${nanoid(8)}`);
248
+ try {
249
+ fs.mkdirSync(staging, { recursive: true });
250
+ await runTar(['-xzf', tmpFile, '-C', staging]);
251
+ fs.rmSync(dest, { recursive: true, force: true });
252
+ fs.renameSync(staging, dest);
253
+ }
254
+ finally {
255
+ fs.rmSync(staging, { recursive: true, force: true });
256
+ try {
257
+ fs.unlinkSync(tmpFile);
258
+ }
259
+ catch { /* nothing to clean */ }
260
+ }
261
+ for (const name of pruneSavedSources(root))
262
+ log(`Removed the older saved copy ${name}`);
263
+ if (options.json) {
264
+ console.log(JSON.stringify({ path: dest, s3Key: source.s3Key, updatedAt: source.updatedAt }));
265
+ }
266
+ else {
267
+ console.log(`Saved copy (saved ${source.updatedAt}) fetched to ${dest}`);
268
+ }
269
+ }
package/dist/index.js CHANGED
@@ -155,8 +155,10 @@ function usage() {
155
155
  castle-web serve [dir] [--port PORT] [--host HOST] [--open] [--detach]
156
156
  castle-web restart [--port PORT]
157
157
  castle-web screenshot [--out FILE] [--port PORT]
158
- castle-web save-deck [dir] [--title TITLE] [--caption TEXT] [--visibility unlisted|private]
158
+ castle-web save-deck [dir] [--title TITLE] [--caption TEXT] [--visibility unlisted|private] [--force] (--force: save over a newer saved copy)
159
159
  castle-web get-deck [dir] [--deck-id ID] [--force] (replaces the source if the deck is already there)
160
+ castle-web get-deck <dir> --side [--deck-id ID] [--json] (fetches the saved copy into <dir>/.castle/agent/saved-source/<stamp>/, touching nothing else)
161
+ castle-web source-status <dir> [--adopt] [--notify] [--json] (whether the deck's saved copy is newer than this folder)
160
162
  castle-web list-decks [dir] [--kind mine|saved|kits] (decks this one could import; ids are what add-import takes)
161
163
  castle-web add-import <deckId|url|kit> [dir] [--as ALIAS] (adds another deck, or a kit this CLI ships, as a read-only dependency in imports/)
162
164
  castle-web fork-import-file <imports/...> [dir] (this deck's own version of one imported file)
@@ -518,7 +520,7 @@ async function main() {
518
520
  const title = getFlagValue('--title');
519
521
  const caption = getFlagValue('--caption');
520
522
  const visibility = getFlagValue('--visibility');
521
- await saveDeck(dir, { title, caption, visibility });
523
+ await saveDeck(dir, { title, caption, visibility, force: hasFlag('--force') });
522
524
  break;
523
525
  }
524
526
  case 'get-deck': {
@@ -527,9 +529,20 @@ async function main() {
527
529
  await getDeck(findPositionalDir(), {
528
530
  deckId: getFlagValue('--deck-id'),
529
531
  force: hasFlag('--force'),
532
+ side: hasFlag('--side'),
533
+ json: hasFlag('--json'),
530
534
  });
531
535
  break;
532
536
  }
537
+ case 'source-status': {
538
+ const { sourceStatus, describeSourceStatus } = await import('./webSourceSync.js');
539
+ const result = await sourceStatus(findPositionalDir(), {
540
+ adopt: hasFlag('--adopt'),
541
+ notify: hasFlag('--notify'),
542
+ });
543
+ console.log(hasFlag('--json') ? JSON.stringify(result) : describeSourceStatus(result));
544
+ break;
545
+ }
533
546
  case 'list-decks': {
534
547
  await listDecks(findPositionalDir(), { kind: getFlagValue('--kind') });
535
548
  break;
package/dist/init.js CHANGED
@@ -54,7 +54,7 @@ if (!(await mountEditorRoute())) startGame(initCard());
54
54
  // Registry version of castle-web-sdk to inject when scaffolding from a
55
55
  // globally-installed castle-web (not from inside the workspace). Bumped
56
56
  // alongside cli/sdk version bumps.
57
- const PUBLISHED_SDK_VERSION = '0.4.39';
57
+ const PUBLISHED_SDK_VERSION = '0.4.40';
58
58
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
59
59
  // face can ship without a cli release, and a caret range means an existing
60
60
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -1,4 +1,5 @@
1
1
  import * as api from './api.js';
2
+ import { type SavePrecondition } from './webSourceSync.js';
2
3
  export declare const SOURCE_ARCHIVE_EXCLUDES: string[];
3
4
  export declare const SAVE_STAGE_TELEMETRY_PREFIX = "CASTLE_SAVE_TELEMETRY ";
4
5
  export declare const SAVE_COVER_SELECTION_TELEMETRY_PREFIX = "CASTLE_SAVE_COVER_SELECTION ";
@@ -7,11 +8,15 @@ export declare function runTar(args: string[], opts?: {
7
8
  capture?: boolean;
8
9
  }): Promise<string>;
9
10
  export declare function archiveSource(projectDir: string): Promise<Buffer>;
10
- export declare function downloadSourceArchive(source: api.WebDeckSource, namePrefix: string): Promise<string>;
11
+ export declare function downloadSourceArchive(source: api.WebDeckSource, namePrefix: string, log?: (line: string) => void): Promise<string>;
12
+ export declare function uploadSource(projectDir: string, deckId: string, expectedS3Key?: string | null): Promise<api.WebDeckSource>;
13
+ export declare function checkSavePrecondition(projectDir: string, deckId: string, force: boolean): Promise<SavePrecondition>;
11
14
  export type SaveVisibility = 'unlisted' | 'private';
12
15
  export interface SaveDeckOptions {
13
16
  title?: string;
14
17
  caption?: string;
15
18
  visibility?: SaveVisibility;
19
+ /** Save even when the deck's saved copy is newer than this folder. */
20
+ force?: boolean;
16
21
  }
17
22
  export declare function saveDeck(dir: string, opts?: SaveDeckOptions): Promise<void>;
package/dist/save-deck.js CHANGED
@@ -10,6 +10,7 @@ import { resolveServerConfig } from './castleJson.js';
10
10
  import { selectSaveCover } from './saveCover.js';
11
11
  import { COVER_FILE } from './localPaths.js';
12
12
  import { buildServerBundle } from './serverBundle.js';
13
+ import { decideSavePrecondition, EXIT_SAVED_DECK_NEWER, fetchServerSourceVersion, readSyncMarker, saveRefusedLine, saveRefusedMessage, WEB_DECK_SOURCE_STALE_CODE, writeSyncMarker, } from './webSourceSync.js';
13
14
  // `imports/` is derived state like node_modules: a dependency's files belong to
14
15
  // the deck that published them, and castle.json's import pins are enough to fetch
15
16
  // them again -- so they neither bloat this deck's archive nor get republished as
@@ -95,14 +96,14 @@ export async function archiveSource(projectDir) {
95
96
  // Written to tmp and read or untarred out of there, never moved out: in a sandbox
96
97
  // the deck is on a different filesystem from tmp, and a rename across that is EXDEV.
97
98
  // The caller owns the file it gets back.
98
- export async function downloadSourceArchive(source, namePrefix) {
99
- console.log(`Fetching ${source.archiveUrl}`);
99
+ export async function downloadSourceArchive(source, namePrefix, log = console.log) {
100
+ log(`Fetching ${source.archiveUrl}`);
100
101
  const res = await fetch(source.archiveUrl, { signal: AbortSignal.timeout(60000) });
101
102
  if (!res.ok) {
102
103
  throw new Error(`Archive fetch failed: HTTP ${res.status}`);
103
104
  }
104
105
  const buf = Buffer.from(await res.arrayBuffer());
105
- console.log(`Archive: ${(buf.length / 1024).toFixed(1)}KB (updated ${source.updatedAt})`);
106
+ log(`Archive: ${(buf.length / 1024).toFixed(1)}KB (updated ${source.updatedAt})`);
106
107
  const file = path.join(os.tmpdir(), `${namePrefix}-${nanoid(8)}.tar.gz`);
107
108
  fs.writeFileSync(file, buf);
108
109
  return file;
@@ -122,7 +123,9 @@ async function uploadPresignedFile(uploadConfig, file, contentType, timeoutMs, l
122
123
  if (response.status >= 300)
123
124
  throw new Error(`${label} failed: HTTP ${response.status}`);
124
125
  }
125
- async function uploadSource(projectDir, deckId) {
126
+ // `expectedS3Key` is the save precondition (api.saveWebDeckSource). Returns the saved source,
127
+ // whose key and time become this folder's sync marker.
128
+ export async function uploadSource(projectDir, deckId, expectedS3Key) {
126
129
  const archive = await traceSaveStage('source_archive', () => archiveSource(projectDir), (value) => ({ bytes: value.byteLength }));
127
130
  const sizeKB = archive.length / 1024;
128
131
  console.log(`Source archive: ${sizeKB.toFixed(1)}KB`);
@@ -131,7 +134,24 @@ async function uploadSource(projectDir, deckId) {
131
134
  const view = new Uint8Array(archive.byteLength);
132
135
  view.set(archive);
133
136
  await traceSaveStage('source_upload', () => uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', 60_000, 'Source upload'));
134
- await traceSaveStage('source_commit', () => api.saveWebDeckSource(deckId, uploadConfig.uploadId));
137
+ return traceSaveStage('source_commit', () => api.saveWebDeckSource(deckId, uploadConfig.uploadId, expectedS3Key));
138
+ }
139
+ // Refused: the saved copy is newer than this folder. One machine-readable stdout line (castle-www
140
+ // turns it into its "saved copy is newer" dialog), the human message on stderr, and a dedicated
141
+ // exit code -- set, not exited with, so a piped stdout is flushed before the process ends. The
142
+ // caller returns straight after.
143
+ function refuseSave(dir, refusal) {
144
+ console.log(saveRefusedLine(refusal));
145
+ console.error(saveRefusedMessage(dir, refusal));
146
+ process.exitCode = EXIT_SAVED_DECK_NEWER;
147
+ }
148
+ // Before anything is uploaded or published: the deck goes live at updateCardAndDeckV2, so a
149
+ // refusal any later would leave it half-published. Only a deck that already has an id is
150
+ // checked; a new deck has no saved copy to overwrite.
151
+ export async function checkSavePrecondition(projectDir, deckId, force) {
152
+ const marker = readSyncMarker(projectDir, deckId);
153
+ const server = await fetchServerSourceVersion(deckId);
154
+ return decideSavePrecondition(marker, server, force);
135
155
  }
136
156
  const SERVER_BUNDLE_STATE = path.join('.castle', 'published-server-bundle.json');
137
157
  function readPublishedServerBundleState(projectDir) {
@@ -254,6 +274,23 @@ export async function saveDeck(dir, opts = {}) {
254
274
  process.exit(1);
255
275
  }
256
276
  const castleJson = readCastleJson(projectDir);
277
+ const existingDeckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : null;
278
+ // A deck without an id is new: the source commit sends no precondition, as before.
279
+ let expectedS3Key;
280
+ let markerVia = 'save-deck';
281
+ if (existingDeckId) {
282
+ const precondition = await checkSavePrecondition(projectDir, existingDeckId, opts.force === true);
283
+ if (precondition.kind === 'refuse') {
284
+ refuseSave(dir, precondition);
285
+ return;
286
+ }
287
+ expectedS3Key = precondition.expectedS3Key;
288
+ markerVia = precondition.via;
289
+ if (precondition.adopt) {
290
+ console.error('Note: this folder has no record of which saved copy it came from; adopting it as the ' +
291
+ "deck's saved copy. Later saves are refused if someone else saves this deck in between.");
292
+ }
293
+ }
257
294
  console.log('Bundling...');
258
295
  const bundle = await traceSaveStage('bundle', () => bundleProject(projectDir), (value) => ({ bytes: Buffer.byteLength(value) }));
259
296
  const sizeKB = bundle.length / 1024;
@@ -368,11 +405,34 @@ export async function saveDeck(dir, opts = {}) {
368
405
  `"${title}" is live on the new client but its server is unchanged.`);
369
406
  }
370
407
  console.log('Uploading source archive...');
371
- await uploadSource(projectDir, result.deckId);
408
+ // The precondition only applies to the deck it was checked against.
409
+ const saved = await uploadSource(projectDir, result.deckId, result.deckId === existingDeckId ? expectedS3Key : undefined);
372
410
  console.log('Source archive saved.');
411
+ try {
412
+ writeSyncMarker(projectDir, result.deckId, saved, markerVia);
413
+ }
414
+ catch (e) {
415
+ // The save itself succeeded; a missing marker only means the next save adopts again.
416
+ console.error(`Could not record the saved version: ${e instanceof Error ? e.message : String(e)}`);
417
+ }
373
418
  }
374
419
  catch (e) {
375
420
  const code = e?.extensions?.code ?? '';
421
+ if (code === WEB_DECK_SOURCE_STALE_CODE) {
422
+ // Someone saved between the check above and this commit. The game itself is already
423
+ // live; only its saved source was refused. Reported like the check's own refusal.
424
+ const server = existingDeckId
425
+ ? await fetchServerSourceVersion(existingDeckId).catch(() => null)
426
+ : null;
427
+ const marker = existingDeckId ? readSyncMarker(projectDir, existingDeckId) : null;
428
+ console.error('The playable deck was updated, but its saved source was not: someone else saved it first.');
429
+ refuseSave(dir, {
430
+ savedAt: server?.updatedAt ?? null,
431
+ syncedAt: marker?.updatedAt ?? null,
432
+ savedS3Key: server?.s3Key ?? null,
433
+ });
434
+ return;
435
+ }
376
436
  if (code === 'LOGIN_REQUIRED') {
377
437
  console.error('Not logged in. Run `castle-web login` first.');
378
438
  }
@@ -0,0 +1,83 @@
1
+ export declare const WEB_SOURCE_SYNC_FILE: string;
2
+ /** `get-deck --side` copies of the saved source, one folder per saved version. */
3
+ export declare const SAVED_SOURCE_DIR: string;
4
+ export declare const SAVED_SOURCE_KEEP = 2;
5
+ export type SyncVia = 'get-deck' | 'save-deck' | 'adopt' | 'force';
6
+ export interface WebSourceSyncMarker {
7
+ deckId: string;
8
+ s3Key: string;
9
+ updatedAt: string;
10
+ syncedAt: string;
11
+ via: SyncVia;
12
+ }
13
+ export interface ServerSourceVersion {
14
+ s3Key: string;
15
+ updatedAt: string;
16
+ }
17
+ /** The folder's marker, or null when missing, malformed, or recorded for another deck. */
18
+ export declare function readSyncMarker(dir: string, deckId?: string): WebSourceSyncMarker | null;
19
+ export declare function writeSyncMarker(dir: string, deckId: string, source: ServerSourceVersion, via: SyncVia, now?: Date): WebSourceSyncMarker;
20
+ /** Removes a `source-status --notify` notice the serve has not consumed yet. */
21
+ export declare function clearSourceNewerNotice(dir: string): void;
22
+ export type SyncComparison = 'in-sync' | 'saved-newer' | 'lag';
23
+ /**
24
+ * The lag rule. `webDeckSource` reads a replica, so right after a save from this folder the
25
+ * server can still show the previous row: a different key alone is not proof of a newer save.
26
+ * Saved-newer only when the keys differ AND the server's save time is strictly newer than the
27
+ * marker's; otherwise it is lag, and the server's own check (primary, under lock) decides.
28
+ */
29
+ export declare function compareSync(marker: Pick<WebSourceSyncMarker, 's3Key' | 'updatedAt'>, server: ServerSourceVersion): SyncComparison;
30
+ export type SavePrecondition = {
31
+ kind: 'proceed';
32
+ /** undefined: omit the argument (no check); null: expect no saved source; string: expect this key. */
33
+ expectedS3Key: string | null | undefined;
34
+ /** No marker but a saved source exists: this folder is adopted as the deck's saved copy. */
35
+ adopt: boolean;
36
+ via: SyncVia;
37
+ } | {
38
+ kind: 'refuse';
39
+ savedAt: string;
40
+ syncedAt: string;
41
+ savedS3Key: string;
42
+ };
43
+ /** What save-deck does, given the folder's marker and the server's current saved source. */
44
+ export declare function decideSavePrecondition(marker: WebSourceSyncMarker | null, server: ServerSourceVersion | null, force: boolean): SavePrecondition;
45
+ export declare function fetchServerSourceVersion(deckId: string): Promise<ServerSourceVersion | null>;
46
+ /** A save time as people read it: `2026-08-18 13:21 UTC`, or the raw value if unparseable. */
47
+ export declare function humanTime(iso: string): string;
48
+ /** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
49
+ export declare const EXIT_SAVED_DECK_NEWER = 5;
50
+ export declare const SAVE_REFUSED_PREFIX = "CASTLE_SAVE_REFUSED ";
51
+ export declare const SAVED_DECK_NEWER_CODE = "SAVED_DECK_NEWER";
52
+ /** Ghost's code when its own check (primary, under lock) refuses the source commit. */
53
+ export declare const WEB_DECK_SOURCE_STALE_CODE = "WEB_DECK_SOURCE_STALE";
54
+ export interface SaveRefusal {
55
+ savedAt: string | null;
56
+ syncedAt: string | null;
57
+ savedS3Key: string | null;
58
+ }
59
+ /** The single machine-readable stdout line castle-www parses from a refused save. */
60
+ export declare function saveRefusedLine(refusal: SaveRefusal): string;
61
+ export declare function saveRefusedMessage(dir: string, refusal: SaveRefusal): string;
62
+ export type SourceStatus = 'in-sync' | 'saved-newer' | 'lag' | 'no-marker' | 'no-source' | 'no-deck';
63
+ export interface SourceStatusResult {
64
+ deckId: string | null;
65
+ status: SourceStatus;
66
+ marker: Omit<WebSourceSyncMarker, 'deckId'> | null;
67
+ server: ServerSourceVersion | null;
68
+ adopted?: true;
69
+ notified?: true;
70
+ }
71
+ export interface SourceStatusOptions {
72
+ adopt?: boolean;
73
+ notify?: boolean;
74
+ /** Injected by tests; defaults to the webDeckSource query. */
75
+ fetchServer?: (deckId: string) => Promise<ServerSourceVersion | null>;
76
+ now?: () => Date;
77
+ }
78
+ export declare function sourceNewerNotice(dir: string, savedAt: string, syncedAt: string): {
79
+ notice: string;
80
+ instruction: string;
81
+ };
82
+ export declare function sourceStatus(dir: string, opts?: SourceStatusOptions): Promise<SourceStatusResult>;
83
+ export declare function describeSourceStatus(result: SourceStatusResult): string;
@@ -0,0 +1,229 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as api from './api.js';
4
+ import { atomicWriteFileSync } from './atomicFile.js';
5
+ import { readCastleJson } from './castleJson.js';
6
+ import { WEB_SOURCE_NEWER_MARKER_FILE } from './cloudGit.js';
7
+ // Which saved source a deck folder came from. `web_deck_sources` holds one row per deck and
8
+ // mints a fresh `s3Key` on every save, so the key names one saved version exactly; the folder
9
+ // records the key it last fetched or saved, and a save compares it with the server's before
10
+ // writing over someone else's newer save.
11
+ //
12
+ // It lives in `.castle/agent/`: excluded from the source archive (so it never travels into a
13
+ // save or a remix), and a durable editor namespace in deck persistence (so a cold resume keeps
14
+ // it). A missing or malformed marker reads as absent: the folder is then adopted, never refused.
15
+ export const WEB_SOURCE_SYNC_FILE = path.join('.castle', 'agent', 'web-source-sync.json');
16
+ /** `get-deck --side` copies of the saved source, one folder per saved version. */
17
+ export const SAVED_SOURCE_DIR = path.join('.castle', 'agent', 'saved-source');
18
+ export const SAVED_SOURCE_KEEP = 2;
19
+ const VIAS = ['get-deck', 'save-deck', 'adopt', 'force'];
20
+ /** The folder's marker, or null when missing, malformed, or recorded for another deck. */
21
+ export function readSyncMarker(dir, deckId) {
22
+ let value;
23
+ try {
24
+ value = JSON.parse(fs.readFileSync(path.join(dir, WEB_SOURCE_SYNC_FILE), 'utf-8'));
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ if (!value ||
30
+ typeof value.deckId !== 'string' ||
31
+ typeof value.s3Key !== 'string' ||
32
+ !value.s3Key ||
33
+ typeof value.updatedAt !== 'string' ||
34
+ typeof value.syncedAt !== 'string' ||
35
+ !VIAS.includes(value.via)) {
36
+ return null;
37
+ }
38
+ if (deckId !== undefined && value.deckId !== deckId)
39
+ return null;
40
+ return {
41
+ deckId: value.deckId,
42
+ s3Key: value.s3Key,
43
+ updatedAt: value.updatedAt,
44
+ syncedAt: value.syncedAt,
45
+ via: value.via,
46
+ };
47
+ }
48
+ export function writeSyncMarker(dir, deckId, source, via, now = new Date()) {
49
+ const marker = {
50
+ deckId,
51
+ s3Key: source.s3Key,
52
+ updatedAt: source.updatedAt,
53
+ syncedAt: now.toISOString(),
54
+ via,
55
+ };
56
+ const file = path.join(dir, WEB_SOURCE_SYNC_FILE);
57
+ fs.mkdirSync(path.dirname(file), { recursive: true });
58
+ atomicWriteFileSync(file, `${JSON.stringify(marker, null, 2)}\n`);
59
+ // The folder now matches a saved version, so a pending "saved copy is newer" notice is moot.
60
+ clearSourceNewerNotice(dir);
61
+ return marker;
62
+ }
63
+ /** Removes a `source-status --notify` notice the serve has not consumed yet. */
64
+ export function clearSourceNewerNotice(dir) {
65
+ fs.rmSync(path.join(dir, WEB_SOURCE_NEWER_MARKER_FILE), { force: true });
66
+ }
67
+ /**
68
+ * The lag rule. `webDeckSource` reads a replica, so right after a save from this folder the
69
+ * server can still show the previous row: a different key alone is not proof of a newer save.
70
+ * Saved-newer only when the keys differ AND the server's save time is strictly newer than the
71
+ * marker's; otherwise it is lag, and the server's own check (primary, under lock) decides.
72
+ */
73
+ export function compareSync(marker, server) {
74
+ if (marker.s3Key === server.s3Key)
75
+ return 'in-sync';
76
+ const serverMs = Date.parse(server.updatedAt);
77
+ const markerMs = Date.parse(marker.updatedAt);
78
+ if (Number.isFinite(serverMs) && Number.isFinite(markerMs) && serverMs > markerMs) {
79
+ return 'saved-newer';
80
+ }
81
+ return 'lag';
82
+ }
83
+ /** What save-deck does, given the folder's marker and the server's current saved source. */
84
+ export function decideSavePrecondition(marker, server, force) {
85
+ if (force) {
86
+ // A third writer between this observation and the save still trips the server -- for a
87
+ // marked folder. An unmarked one never sends the precondition (below), forced or not.
88
+ return {
89
+ kind: 'proceed',
90
+ expectedS3Key: marker ? (server?.s3Key ?? null) : undefined,
91
+ adopt: false,
92
+ via: 'force',
93
+ };
94
+ }
95
+ if (!marker) {
96
+ // A folder with no marker never sends the precondition: it has nothing to compare, and a
97
+ // server refusal would only arrive after the deck went live. It is adopted (a row exists)
98
+ // or saved as the first source, and guarded from the marker the save writes.
99
+ return { kind: 'proceed', expectedS3Key: undefined, adopt: server !== null, via: 'save-deck' };
100
+ }
101
+ // No row is lag too (a first save the replica hasn't seen yet); the server decides.
102
+ if (server && compareSync(marker, server) === 'saved-newer') {
103
+ return {
104
+ kind: 'refuse',
105
+ savedAt: server.updatedAt,
106
+ syncedAt: marker.updatedAt,
107
+ savedS3Key: server.s3Key,
108
+ };
109
+ }
110
+ return { kind: 'proceed', expectedS3Key: marker.s3Key, adopt: false, via: 'save-deck' };
111
+ }
112
+ export async function fetchServerSourceVersion(deckId) {
113
+ const source = await api.webDeckSource(deckId);
114
+ return source ? { s3Key: source.s3Key, updatedAt: source.updatedAt } : null;
115
+ }
116
+ /** A save time as people read it: `2026-08-18 13:21 UTC`, or the raw value if unparseable. */
117
+ export function humanTime(iso) {
118
+ const ms = Date.parse(iso);
119
+ if (!Number.isFinite(ms))
120
+ return iso;
121
+ return `${new Date(ms).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
122
+ }
123
+ // --- save-deck refusal --------------------------------------------------------
124
+ /** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
125
+ export const EXIT_SAVED_DECK_NEWER = 5;
126
+ export const SAVE_REFUSED_PREFIX = 'CASTLE_SAVE_REFUSED ';
127
+ export const SAVED_DECK_NEWER_CODE = 'SAVED_DECK_NEWER';
128
+ /** Ghost's code when its own check (primary, under lock) refuses the source commit. */
129
+ export const WEB_DECK_SOURCE_STALE_CODE = 'WEB_DECK_SOURCE_STALE';
130
+ /** The single machine-readable stdout line castle-www parses from a refused save. */
131
+ export function saveRefusedLine(refusal) {
132
+ return `${SAVE_REFUSED_PREFIX}${JSON.stringify({
133
+ event: 'castle_web_save_refused',
134
+ code: SAVED_DECK_NEWER_CODE,
135
+ savedAt: refusal.savedAt,
136
+ syncedAt: refusal.syncedAt,
137
+ savedS3Key: refusal.savedS3Key,
138
+ })}`;
139
+ }
140
+ export function saveRefusedMessage(dir, refusal) {
141
+ const saved = refusal.savedAt ? `saved ${humanTime(refusal.savedAt)}` : 'saved from elsewhere';
142
+ const synced = refusal.syncedAt
143
+ ? `this folder last synced ${humanTime(refusal.syncedAt)}`
144
+ : 'this folder never synced with it';
145
+ return [
146
+ `Not saved: the saved copy of this deck is newer than this folder (${saved}; ${synced}).`,
147
+ 'Saving now would overwrite changes made elsewhere. Either:',
148
+ ` castle-web get-deck ${dir} --side fetch the saved copy beside this one (.castle/agent/saved-source/) to compare`,
149
+ ` castle-web save-deck ${dir} --force overwrite the saved copy with this folder`,
150
+ ].join('\n');
151
+ }
152
+ export function sourceNewerNotice(dir, savedAt, syncedAt) {
153
+ const notice = `The saved copy of this deck is newer than this workspace (saved ${humanTime(savedAt)}; ` +
154
+ `this workspace last synced ${humanTime(syncedAt)}). Ask before saving over it.`;
155
+ const instruction = [
156
+ `[Castle] The saved copy of this deck was saved at ${savedAt}, after this workspace last synced with it (${syncedAt}): someone saved this deck from somewhere else since, and this workspace does not have those changes.`,
157
+ `Do not run \`castle-web save-deck\` (and never \`save-deck --force\`) over the saved copy without the user's explicit OK: it would overwrite those changes.`,
158
+ `To compare, \`castle-web get-deck ${dir} --side\` fetches the saved copy into .castle/agent/saved-source/<stamp>/ without touching this workspace; diff it against the workspace and tell the user what differs.`,
159
+ 'Tell the user about this in one or two sentences and ask how they want to proceed.',
160
+ ].join('\n');
161
+ return { notice, instruction };
162
+ }
163
+ export async function sourceStatus(dir, opts = {}) {
164
+ const result = await computeSourceStatus(dir, opts);
165
+ // Whatever a notice said no longer holds unless the saved copy is still newer.
166
+ if (result.status !== 'saved-newer')
167
+ clearSourceNewerNotice(path.resolve(dir));
168
+ return result;
169
+ }
170
+ async function computeSourceStatus(dir, opts) {
171
+ const projectDir = path.resolve(dir);
172
+ // An unreadable or missing folder is a real error, unlike a folder that isn't a deck.
173
+ if (!fs.statSync(projectDir).isDirectory())
174
+ throw new Error(`Not a directory: ${projectDir}`);
175
+ fs.readdirSync(projectDir);
176
+ const deckId = readCastleJson(projectDir)?.deckId;
177
+ if (typeof deckId !== 'string' || !deckId) {
178
+ return { deckId: null, status: 'no-deck', marker: null, server: null };
179
+ }
180
+ const marker = readSyncMarker(projectDir, deckId);
181
+ const server = await (opts.fetchServer ?? fetchServerSourceVersion)(deckId);
182
+ const result = {
183
+ deckId,
184
+ status: 'no-source',
185
+ marker: marker
186
+ ? { s3Key: marker.s3Key, updatedAt: marker.updatedAt, syncedAt: marker.syncedAt, via: marker.via }
187
+ : null,
188
+ server,
189
+ };
190
+ if (!server)
191
+ return result;
192
+ if (!marker) {
193
+ 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;
200
+ }
201
+ result.status = compareSync(marker, server);
202
+ if (result.status === 'saved-newer' && opts.notify) {
203
+ const file = path.join(projectDir, WEB_SOURCE_NEWER_MARKER_FILE);
204
+ fs.mkdirSync(path.dirname(file), { recursive: true });
205
+ atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, marker.updatedAt))}\n`);
206
+ result.notified = true;
207
+ }
208
+ return result;
209
+ }
210
+ export function describeSourceStatus(result) {
211
+ switch (result.status) {
212
+ case 'no-deck':
213
+ return 'Not a saved deck (castle.json has no deckId).';
214
+ case 'no-source':
215
+ return `Deck ${result.deckId} has no saved source yet.`;
216
+ case 'no-marker':
217
+ return result.adopted
218
+ ? `Adopted this folder as deck ${result.deckId}'s saved copy (saved ${humanTime(result.server.updatedAt)}).`
219
+ : `This folder has no sync record for deck ${result.deckId}; the saved copy is from ${humanTime(result.server.updatedAt)}.`;
220
+ case 'in-sync':
221
+ return `In sync with the saved copy (saved ${humanTime(result.server.updatedAt)}).`;
222
+ case 'lag':
223
+ return `The server has not caught up with this folder's last save yet (${humanTime(result.marker.updatedAt)}).`;
224
+ case 'saved-newer':
225
+ return (`The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
226
+ `this folder last synced ${humanTime(result.marker.updatedAt)}).` +
227
+ (result.notified ? ' The agent has been told.' : ''));
228
+ }
229
+ }
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-09-26T15:36:56.023Z",
85
+ "publishedVersion": "2026-09-27T19:36:03.837Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "../../sdk": {
16
16
  "name": "castle-web-sdk",
17
- "version": "0.4.37",
17
+ "version": "0.4.40",
18
18
  "dev": true,
19
19
  "devDependencies": {
20
20
  "eslint": "^9.0.0",
@@ -53,6 +53,8 @@ export interface PlatformHandle {
53
53
  worldCharacterSend?(grantId: string): Promise<string>;
54
54
  worldCharacterCommand?(grantId: string): Promise<string>;
55
55
  worldCharacterRead?(grantId: string): Promise<string>;
56
+ worldCharacterRuntimeCreate?(argsJson: string): Promise<string>;
57
+ worldCharacterRuntimeList?(): Promise<string>;
56
58
  worldCharacterReject?(grantId: string, code?: string): void;
57
59
  readonly config: PlatformSessionConfig;
58
60
  }
@@ -55,6 +55,8 @@ export interface MultiplayerServerWorld {
55
55
  readonly characters: MultiplayerServerWorldCharacters;
56
56
  }
57
57
  export interface MultiplayerServerWorldCharacters {
58
+ create(input: MultiplayerWorldRuntimeCharacterCreateInput): Promise<MultiplayerWorldRuntimeCharacterCreateReceipt>;
59
+ list(): Promise<MultiplayerWorldCharacterList>;
58
60
  publicInspect<T = unknown>(): Promise<T>;
59
61
  publicRelay(input: {
60
62
  operationId: string;
@@ -63,6 +65,38 @@ export interface MultiplayerServerWorldCharacters {
63
65
  recipientCharacterIds: string[];
64
66
  }): Promise<unknown>;
65
67
  }
68
+ export interface MultiplayerWorldRuntimeCharacterKnowledge {
69
+ kind: "belief";
70
+ text: string;
71
+ }
72
+ export interface MultiplayerWorldRuntimeCharacterDefinition {
73
+ name: string;
74
+ instructions: string;
75
+ background?: string;
76
+ initialKnowledge?: readonly MultiplayerWorldRuntimeCharacterKnowledge[];
77
+ }
78
+ export interface MultiplayerWorldRuntimeCharacterCreateInput {
79
+ operationId: string;
80
+ definition: MultiplayerWorldRuntimeCharacterDefinition;
81
+ capabilities: {
82
+ actionIds: readonly string[];
83
+ };
84
+ }
85
+ export interface MultiplayerWorldCharacterSummary {
86
+ id: string;
87
+ name: string;
88
+ source: "published" | "runtime";
89
+ }
90
+ export interface MultiplayerWorldRuntimeCharacterCreateReceipt {
91
+ operationId: string;
92
+ character: MultiplayerWorldCharacterSummary & {
93
+ source: "runtime";
94
+ };
95
+ replayed: boolean;
96
+ }
97
+ export interface MultiplayerWorldCharacterList {
98
+ characters: readonly MultiplayerWorldCharacterSummary[];
99
+ }
66
100
  export interface MultiplayerWorldCharacterCommandRequest {
67
101
  readonly requestId: string;
68
102
  readonly operationId: string;
@@ -290,16 +290,28 @@ function createServerWorld(platformHandle) {
290
290
  }
291
291
  function createServerWorldCharacters(platformHandle) {
292
292
  return Object.freeze({
293
- async publicInspect() {
294
- if (typeof platformHandle.storage !== "function") {
295
- throw new TypeError("The shared character broker is unavailable.");
293
+ async create(input) {
294
+ if (typeof platformHandle.worldCharacterRuntimeCreate !== "function") {
295
+ throw new TypeError("The runtime character broker is unavailable.");
296
+ }
297
+ const operationId = assertWorldOperationId(input?.operationId);
298
+ const definition = assertRuntimeCharacterDefinition(input?.definition);
299
+ const capabilities = assertRuntimeCharacterCapabilities(input?.capabilities);
300
+ const result = parseSharedCharacterJson(await platformHandle.worldCharacterRuntimeCreate(JSON.stringify({ operationId, definition, capabilities })));
301
+ return parseRuntimeCharacterCreateReceipt(result, operationId);
302
+ },
303
+ async list() {
304
+ if (typeof platformHandle.worldCharacterRuntimeList !== "function") {
305
+ throw new TypeError("The runtime character broker is unavailable.");
296
306
  }
307
+ return parseRuntimeCharacterList(parseSharedCharacterJson(await platformHandle.worldCharacterRuntimeList()));
308
+ },
309
+ async publicInspect() {
310
+ requireSharedCharacterBroker(platformHandle);
297
311
  return parseSharedCharacterJson(await platformHandle.storage("worldCharacterPublicInspect", "{}"));
298
312
  },
299
313
  async publicRelay(input) {
300
- if (typeof platformHandle.storage !== "function") {
301
- throw new TypeError("The shared character broker is unavailable.");
302
- }
314
+ requireSharedCharacterBroker(platformHandle);
303
315
  const operationId = assertWorldOperationId(input?.operationId);
304
316
  const sourceId = assertWorldCharacterId(input?.sourceId, "sourceId", 128);
305
317
  const transmittingCharacterId = assertWorldCharacterId(input?.transmittingCharacterId, "transmittingCharacterId");
@@ -320,6 +332,142 @@ function createServerWorldCharacters(platformHandle) {
320
332
  },
321
333
  });
322
334
  }
335
+ const RUNTIME_CHARACTER_MAX_COUNT = 16;
336
+ const RUNTIME_CHARACTER_MAX_KNOWLEDGE = 8;
337
+ const RUNTIME_CHARACTER_PROMPT_MAX_CHARACTERS = 8_000;
338
+ const RUNTIME_CHARACTER_ID = /^runtime_[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
339
+ const SAFE_RUNTIME_ACTION_ID = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
340
+ const FORBIDDEN_RUNTIME_ACTION_IDS = new Set(["__proto__", "prototype", "constructor"]);
341
+ function requireSharedCharacterBroker(platformHandle) {
342
+ if (typeof platformHandle.storage !== "function") {
343
+ throw new TypeError("The shared character broker is unavailable.");
344
+ }
345
+ }
346
+ function assertRuntimeCharacterDefinition(value) {
347
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
348
+ throw new TypeError("session.world.characters.create: definition must be an object.");
349
+ }
350
+ const definition = value;
351
+ if (Object.keys(definition).some((key) => !["name", "instructions", "background", "initialKnowledge"].includes(key))) {
352
+ throw new TypeError("session.world.characters.create: definition contains an unsupported field.");
353
+ }
354
+ const name = assertRuntimeCharacterText(definition.name, "definition.name", 100, 400);
355
+ const instructions = assertRuntimeCharacterText(definition.instructions, "definition.instructions", 8_000, 32_000);
356
+ if (JSON.stringify(instructions).length - 2 > 10_000) {
357
+ throw new TypeError("session.world.characters.create: definition.instructions is too large when serialized.");
358
+ }
359
+ const background = definition.background === undefined
360
+ ? undefined
361
+ : assertRuntimeCharacterText(definition.background, "definition.background", 2_000, 8_000);
362
+ let initialKnowledge;
363
+ if (definition.initialKnowledge !== undefined) {
364
+ if (!Array.isArray(definition.initialKnowledge) ||
365
+ definition.initialKnowledge.length > RUNTIME_CHARACTER_MAX_KNOWLEDGE) {
366
+ throw new TypeError(`session.world.characters.create: definition.initialKnowledge may contain at most ${RUNTIME_CHARACTER_MAX_KNOWLEDGE} beliefs.`);
367
+ }
368
+ initialKnowledge = definition.initialKnowledge.map((entry, index) => {
369
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
370
+ throw new TypeError(`session.world.characters.create: definition.initialKnowledge[${index}] must be a belief.`);
371
+ }
372
+ const knowledge = entry;
373
+ if (Object.keys(knowledge).some((key) => key !== "kind" && key !== "text") ||
374
+ knowledge.kind !== "belief") {
375
+ throw new TypeError(`session.world.characters.create: definition.initialKnowledge[${index}] must contain only kind "belief" and text.`);
376
+ }
377
+ return {
378
+ kind: "belief",
379
+ text: assertRuntimeCharacterText(knowledge.text, `definition.initialKnowledge[${index}].text`, 500, 2_000),
380
+ };
381
+ });
382
+ }
383
+ const promptCharacters = instructions.length + (background?.length ?? 0) +
384
+ (initialKnowledge?.reduce((sum, item) => sum + item.text.length, 0) ?? 0);
385
+ if (promptCharacters > RUNTIME_CHARACTER_PROMPT_MAX_CHARACTERS) {
386
+ throw new TypeError(`session.world.characters.create: definition prompt fields may total at most ${RUNTIME_CHARACTER_PROMPT_MAX_CHARACTERS} characters.`);
387
+ }
388
+ return Object.freeze({
389
+ name,
390
+ instructions,
391
+ ...(background === undefined ? {} : { background }),
392
+ ...(initialKnowledge === undefined
393
+ ? {}
394
+ : { initialKnowledge: Object.freeze(initialKnowledge.map((item) => Object.freeze(item))) }),
395
+ });
396
+ }
397
+ function assertRuntimeCharacterCapabilities(value) {
398
+ if (!value ||
399
+ typeof value !== "object" ||
400
+ Array.isArray(value) ||
401
+ Object.keys(value).some((key) => key !== "actionIds")) {
402
+ throw new TypeError("session.world.characters.create: capabilities must contain only actionIds.");
403
+ }
404
+ const actionIds = value.actionIds;
405
+ if (!Array.isArray(actionIds) || actionIds.length > RUNTIME_CHARACTER_MAX_COUNT) {
406
+ throw new TypeError(`session.world.characters.create: capabilities.actionIds may contain at most ${RUNTIME_CHARACTER_MAX_COUNT} ids.`);
407
+ }
408
+ const normalized = actionIds.map((id, index) => {
409
+ if (typeof id !== "string" ||
410
+ !SAFE_RUNTIME_ACTION_ID.test(id) ||
411
+ FORBIDDEN_RUNTIME_ACTION_IDS.has(id)) {
412
+ throw new TypeError(`session.world.characters.create: capabilities.actionIds[${index}] is invalid.`);
413
+ }
414
+ return id;
415
+ });
416
+ if (new Set(normalized).size !== normalized.length) {
417
+ throw new TypeError("session.world.characters.create: capabilities.actionIds may not contain duplicates.");
418
+ }
419
+ return Object.freeze({ actionIds: Object.freeze([...normalized].sort()) });
420
+ }
421
+ function assertRuntimeCharacterText(value, field, maxCharacters, maxBytes) {
422
+ if (typeof value !== "string" ||
423
+ value.length === 0 ||
424
+ value.length > maxCharacters ||
425
+ value.includes("\0") ||
426
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(value) ||
427
+ new TextEncoder().encode(value).byteLength > maxBytes) {
428
+ throw new TypeError(`session.world.characters.create: ${field} must be valid non-empty text of at most ${maxCharacters} characters.`);
429
+ }
430
+ return value;
431
+ }
432
+ function parseRuntimeCharacterCreateReceipt(value, operationId) {
433
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
434
+ throw new TypeError("The platform returned an invalid runtime character receipt.");
435
+ }
436
+ const receipt = value;
437
+ const character = parseRuntimeCharacterSummary(receipt.character, true);
438
+ if (receipt.operationId !== operationId || typeof receipt.replayed !== "boolean") {
439
+ throw new TypeError("The platform returned an invalid runtime character receipt.");
440
+ }
441
+ return Object.freeze({ operationId, character, replayed: receipt.replayed });
442
+ }
443
+ function parseRuntimeCharacterList(value) {
444
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
445
+ throw new TypeError("The platform returned an invalid runtime character list.");
446
+ }
447
+ const characters = value.characters;
448
+ if (!Array.isArray(characters) || characters.length > RUNTIME_CHARACTER_MAX_COUNT) {
449
+ throw new TypeError("The platform returned an invalid runtime character list.");
450
+ }
451
+ const normalized = characters.map((character) => parseRuntimeCharacterSummary(character));
452
+ if (new Set(normalized.map((character) => character.id)).size !== normalized.length) {
453
+ throw new TypeError("The platform returned an invalid runtime character list.");
454
+ }
455
+ return Object.freeze({ characters: Object.freeze(normalized) });
456
+ }
457
+ function parseRuntimeCharacterSummary(value, requireRuntime = false) {
458
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
459
+ throw new TypeError("The platform returned an invalid runtime character summary.");
460
+ }
461
+ const summary = value;
462
+ const id = assertWorldCharacterId(summary.id, "character.id");
463
+ const name = assertRuntimeCharacterText(summary.name, "character.name", 100, 400);
464
+ if ((summary.source !== "runtime" && summary.source !== "published") ||
465
+ (requireRuntime && summary.source !== "runtime") ||
466
+ (summary.source === "runtime" && !RUNTIME_CHARACTER_ID.test(id))) {
467
+ throw new TypeError("The platform returned an invalid runtime character summary.");
468
+ }
469
+ return Object.freeze({ id, name, source: summary.source });
470
+ }
323
471
  function parseWorldSnapshot(value, operation) {
324
472
  if (!value || typeof value !== "object" || Array.isArray(value)) {
325
473
  throw worldError("The platform returned an invalid world checkpoint.", "read");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.219",
3
+ "version": "0.4.220",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"