castle-web-cli 0.4.197 → 0.4.199

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +9 -3
  3. package/dist/agent.js +25 -1
  4. package/dist/api.d.ts +1 -1
  5. package/dist/api.js +14 -3
  6. package/dist/byo-auth.js +4 -5
  7. package/dist/castle-host/host.js +215 -0
  8. package/dist/devSessionServer.js +40 -3
  9. package/dist/devSessionStorage.js +155 -0
  10. package/dist/filesChanged.d.ts +23 -0
  11. package/dist/filesChanged.js +15 -9
  12. package/dist/ide.d.ts +3 -0
  13. package/dist/ide.js +37 -25
  14. package/dist/init.js +1 -1
  15. package/dist/paramsFile.d.ts +80 -0
  16. package/dist/paramsFile.js +516 -0
  17. package/dist/paramsRegisterPlugin.d.ts +3 -0
  18. package/dist/paramsRegisterPlugin.js +81 -0
  19. package/dist/paramsTunes.d.ts +44 -0
  20. package/dist/paramsTunes.js +200 -0
  21. package/dist/paramsWrites.d.ts +30 -0
  22. package/dist/paramsWrites.js +138 -0
  23. package/dist/platformDoc.d.ts +1 -1
  24. package/dist/platformDoc.js +6 -20
  25. package/dist/save-deck.js +9 -1
  26. package/dist/serve.js +23 -15
  27. package/dist/shell/assets/index-DJSLmPmw.js +449 -0
  28. package/dist/shell/assets/index-uXcYGwQC.css +1 -0
  29. package/dist/shell/index.html +2 -2
  30. package/dist/textHash.d.ts +2 -0
  31. package/dist/textHash.js +28 -0
  32. package/kits/base/castle.json +1 -1
  33. package/kits/base/package-lock.json +1 -1
  34. package/kits/base/sdk/README.md +4 -0
  35. package/kits/base/sdk/castle.d.ts +4 -0
  36. package/kits/base/sdk/castle.js +2 -0
  37. package/kits/base/sdk/characters.d.ts +26 -0
  38. package/kits/base/sdk/characters.js +108 -0
  39. package/kits/base/sdk/commands.d.ts +70 -0
  40. package/kits/base/sdk/multiplayer.js +68 -0
  41. package/kits/base/sdk/paramsRegistry.d.ts +32 -0
  42. package/kits/base/sdk/paramsRegistry.js +100 -0
  43. package/kits/base/sdk/runtime.d.ts +7 -0
  44. package/kits/base/sdk/runtime.js +34 -0
  45. package/kits/base/sdk/server/storage.d.ts +77 -0
  46. package/kits/base/sdk/server/storage.js +272 -18
  47. package/kits/base/sdk/server/wrapper.d.ts +1 -1
  48. package/kits/physics-2d/behaviors/Collider.jsx +3 -3
  49. package/kits/physics-2d/behaviors/Joints.jsx +2 -2
  50. package/kits/physics-2d/castle.json +2 -2
  51. package/kits/physics-2d/editors/SceneEditor.jsx +5 -5
  52. package/kits/physics-2d/editors/pxArtTimeline.jsx +1 -1
  53. package/kits/physics-2d/editors/pxArtTimeline.module.css +73 -73
  54. package/kits/physics-2d/editors/themeEditor.module.css +17 -17
  55. package/kits/physics-2d/engine/castle-tokens.css +64 -0
  56. package/kits/physics-2d/engine/fields/fields.module.css +43 -37
  57. package/kits/physics-2d/engine/ui.jsx +1 -0
  58. package/kits/physics-2d/engine/ui.module.css +262 -288
  59. package/kits/physics-2d/package-lock.json +6 -1
  60. package/package.json +1 -1
  61. package/dist/shell/assets/index-MSHtKPXt.css +0 -1
  62. package/dist/shell/assets/index-yHGXRGlX.js +0 -449
@@ -0,0 +1,200 @@
1
+ // Whether a write to a deck file was ONLY a tune -- someone moving a control in
2
+ // the Parameters panel -- and the one write path that can say so.
3
+ //
4
+ // The panel already marks its writes (`tuned`, see paramsWrites.ts), but that
5
+ // marker is a claim by a client and its job is the router journal. Deciding
6
+ // whether a running deck may fold a change in without restarting needs more
7
+ // than a claim: the answer is DERIVED here, by parsing the file on disk and the
8
+ // incoming text with the panel's own parser and checking that re-splicing the
9
+ // differing values reproduces the incoming bytes exactly. That covers the
10
+ // panel, its undo, and a number retyped in the code editor, and it costs the
11
+ // client nothing to plumb.
12
+ //
13
+ // The watcher coalesces a burst of writes into one broadcast, so "pure tune" is
14
+ // a property of the CHAIN from the last broadcast's text, not of one write. The
15
+ // ledger holds that chain, keyed by hash: anything that lands from somewhere
16
+ // else -- an agent, the terminal, a code save -- breaks it, and a broken chain
17
+ // is reported as no tune at all. Ambiguity always resolves to "not a tune",
18
+ // because the cost of that is a Restart button the person did not need and the
19
+ // cost of the other answer is a deck showing a file it is not running.
20
+ //
21
+ // The chain has to START somewhere, and the only honest starting point is the
22
+ // text a frame actually LOADED -- which is what `seed` records, called from the
23
+ // dev-serve transform that hands the module to the browser. A ledger that
24
+ // seeded itself from whatever happened to be on disk at the first write would
25
+ // vouch for a tune spliced on top of an agent's edit that the running deck has
26
+ // never seen. With no seed there is no live apply to authorize, so the answer
27
+ // is null.
28
+ import * as fs from 'fs';
29
+ import * as path from 'path';
30
+ import { resolveForkedFile } from './forks.js';
31
+ import { editParam, parseParams, PARAMS_DECLARATION, PARAMS_EXTS, } from './paramsFile.js';
32
+ import { textHash } from './textHash.js';
33
+ function flatten(doc) {
34
+ return doc.groups.flatMap((group) => group.slots);
35
+ }
36
+ /**
37
+ * The slots that differ between two versions of a params file, or null when the
38
+ * difference is anything more than their values.
39
+ *
40
+ * The byte-identity check at the end is what makes this trustworthy: it is not
41
+ * enough that the same slots hold different numbers, because a file can gain a
42
+ * line of code in the same write. Re-applying only the differing slots to the
43
+ * disk text has to reproduce the incoming text exactly, or nothing is claimed.
44
+ */
45
+ export function diffTune(diskText, incomingText) {
46
+ if (diskText === incomingText)
47
+ return null;
48
+ // Before the parser, because this runs on the way to disk for every write an
49
+ // editor client makes, and a drawing or a scene is hundreds of kilobytes that
50
+ // would otherwise be walked as TSX twice on every save.
51
+ if (!PARAMS_DECLARATION.test(diskText) || !PARAMS_DECLARATION.test(incomingText))
52
+ return null;
53
+ const disk = parseParams(diskText);
54
+ const incoming = parseParams(incomingText);
55
+ if (!disk.found || !incoming.found)
56
+ return null;
57
+ const before = flatten(disk);
58
+ const after = flatten(incoming);
59
+ if (before.length !== after.length)
60
+ return null;
61
+ const tuned = [];
62
+ for (let i = 0; i < before.length; i += 1) {
63
+ const from = before[i];
64
+ const to = after[i];
65
+ if (from.id !== to.id)
66
+ return null;
67
+ if (from.source === to.source)
68
+ continue;
69
+ if (from.value === undefined || to.value === undefined)
70
+ return null;
71
+ tuned.push({ id: from.id, before: from.value, after: to.value });
72
+ }
73
+ if (tuned.length === 0)
74
+ return null;
75
+ let text = diskText;
76
+ let doc = disk;
77
+ for (const slot of tuned) {
78
+ const next = editParam(text, doc, slot.id, slot.after);
79
+ text = next.text;
80
+ doc = next.doc;
81
+ }
82
+ return text === incomingText ? tuned : null;
83
+ }
84
+ export function createTuneLedger(deckDir) {
85
+ // The text the running deck holds for this path: set when a frame loads the
86
+ // module, and advanced by a broadcast the ledger could vouch for. ABSENT is
87
+ // the answer everything falls back to -- no frame is known to be running
88
+ // these bytes, so no tune may skip a reload.
89
+ const baseline = new Map();
90
+ const chain = new Map();
91
+ const readNow = (rel) => {
92
+ const file = resolveForkedFile(deckDir, rel) ?? path.join(deckDir, rel);
93
+ try {
94
+ return fs.readFileSync(file, 'utf8');
95
+ }
96
+ catch {
97
+ return '';
98
+ }
99
+ };
100
+ const isParamsPath = (rel) => PARAMS_EXTS.has(path.extname(rel).toLowerCase());
101
+ const seed = (rel, text) => {
102
+ if (!isParamsPath(rel))
103
+ return;
104
+ baseline.set(rel, textHash(text));
105
+ };
106
+ const verify = (rel, diskText, incomingText) => {
107
+ if (!isParamsPath(rel))
108
+ return null;
109
+ const started = chain.get(rel)?.expectedHash ?? baseline.get(rel);
110
+ if (started === undefined || textHash(diskText) !== started) {
111
+ chain.delete(rel);
112
+ return null;
113
+ }
114
+ const slots = diffTune(diskText, incomingText);
115
+ if (!slots) {
116
+ chain.delete(rel);
117
+ return null;
118
+ }
119
+ const merged = new Map((chain.get(rel)?.slots ?? []).map((slot) => [slot.id, slot]));
120
+ for (const slot of slots) {
121
+ const first = merged.get(slot.id);
122
+ merged.set(slot.id, first ? { ...first, after: slot.after } : slot);
123
+ }
124
+ chain.set(rel, { expectedHash: textHash(incomingText), slots: [...merged.values()] });
125
+ return slots;
126
+ };
127
+ const claim = (rel, event) => {
128
+ if (!isParamsPath(rel))
129
+ return null;
130
+ const entry = chain.get(rel);
131
+ chain.delete(rel);
132
+ if (event === 'delete') {
133
+ baseline.delete(rel);
134
+ return null;
135
+ }
136
+ const known = baseline.get(rel);
137
+ // Nothing verified reached this path, so something the ledger cannot vouch
138
+ // for did -- but an fs event is not proof the CONTENT moved. An agent
139
+ // writing the same lines back, a formatter that changed nothing, a version
140
+ // restore landing bytes that were already there: the frame is still running
141
+ // exactly this, so dropping the baseline would spend a Restart on nothing.
142
+ // A path with no baseline has nothing to keep, so it is not worth a read.
143
+ if (!entry) {
144
+ if (known !== undefined && textHash(readNow(rel)) !== known)
145
+ baseline.delete(rel);
146
+ return null;
147
+ }
148
+ const now = textHash(readNow(rel));
149
+ if (entry.expectedHash !== now) {
150
+ baseline.delete(rel);
151
+ return null;
152
+ }
153
+ baseline.set(rel, now);
154
+ return entry.slots;
155
+ };
156
+ return { seed, verify, claim };
157
+ }
158
+ /**
159
+ * The one place a whole-file write from an editor client lands.
160
+ *
161
+ * `ifMatch` is the fix for the clobber: the panel splices against the text it
162
+ * last read and skips external reloads while its own write is in flight, so a
163
+ * code save or an agent write landing inside a scrub window used to be
164
+ * overwritten silently. A caller that names the text it based its edit on gets
165
+ * a refusal instead, and can re-read and re-apply.
166
+ */
167
+ export function applyDeckWrite(opts) {
168
+ const { abs, rel, contents, ifMatch, ledger } = opts;
169
+ // Reading the target is only worth it for the two questions that need it. A
170
+ // deck editor saves whole drawings and scenes through here, and pulling
171
+ // hundreds of kilobytes off disk to hand them to nobody is pure cost.
172
+ const isParams = PARAMS_EXTS.has(path.extname(rel).toLowerCase());
173
+ let diskText = '';
174
+ if (isParams || ifMatch !== undefined) {
175
+ try {
176
+ diskText = fs.readFileSync(abs, 'utf8');
177
+ }
178
+ catch {
179
+ /* a file that is not there yet reads as empty, which is what it writes over */
180
+ }
181
+ }
182
+ if (ifMatch !== undefined && textHash(diskText) !== ifMatch) {
183
+ return {
184
+ ok: false,
185
+ conflict: true,
186
+ error: `${rel} changed since it was read.`,
187
+ };
188
+ }
189
+ if (isParams)
190
+ ledger?.verify(rel, diskText, contents);
191
+ try {
192
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
193
+ fs.writeFileSync(abs, contents, 'utf8');
194
+ }
195
+ catch (error) {
196
+ const message = error instanceof Error ? error.message : String(error);
197
+ return { ok: false, error: `Could not write ${rel}: ${message}` };
198
+ }
199
+ return { ok: true, path: rel };
200
+ }
@@ -0,0 +1,30 @@
1
+ type TunedValue = number | string | boolean;
2
+ export interface TunedSlot {
3
+ id: string;
4
+ before: TunedValue;
5
+ after: TunedValue;
6
+ }
7
+ export interface ParamsWriteEntry {
8
+ at: string;
9
+ path: string;
10
+ tuned: TunedSlot[];
11
+ }
12
+ export declare function paramsWritesPath(deckDir: string): string;
13
+ export declare function readParamsWrites(deckDir: string): ParamsWriteEntry[];
14
+ export declare function recordParamsWrite(deckDir: string, rel: string, tuned: unknown): void;
15
+ /**
16
+ * One line per slot tuned since `since`, as `<file> <key> (<how long ago>)`,
17
+ * newest `RENDER_LIMIT` first-seen positions kept and a closing `and N more`
18
+ * when that dropped any.
19
+ *
20
+ * No values: a block carrying `old -> new` measurably makes the router write the
21
+ * number into plan.md and raise the tune on turns about something else, and the
22
+ * file is the one source of truth for what a `PARAMS` value is now
23
+ * (memos 26-09-18-09-20 and 26-09-18-12-49). The router reads the file when it
24
+ * needs the number.
25
+ *
26
+ * A scrub lands many writes on one key, so slots collapse: first tune keeps the
27
+ * position, last tune gives the time.
28
+ */
29
+ export declare function panelWritesSince(deckDir: string, since: number, now?: number): string[];
30
+ export {};
@@ -0,0 +1,138 @@
1
+ // What the Parameters panel has changed, per deck.
2
+ //
3
+ // A panel tune reaches disk the same way a code save does -- one whole file,
4
+ // through `files/write` -- so the serve cannot otherwise tell a person moving a
5
+ // control from an agent rewriting a line, and neither can the watcher. A router
6
+ // comparing a `PARAMS` value to something it remembers settling then reads the
7
+ // person's own change as a regression an agent left behind (2026-09-15
8
+ // incident). This is the record that says who.
9
+ //
10
+ // It is runtime state under `.castle/`, which save-deck and the version store
11
+ // exclude, so it is never published and never versioned.
12
+ import * as fs from 'fs';
13
+ import * as path from 'path';
14
+ import { atomicWriteFileSync } from './atomicFile.js';
15
+ const LIMIT = 50;
16
+ const SLOTS_PER_ENTRY = 20;
17
+ const MAX_ID_LENGTH = 64;
18
+ const MAX_PATH_LENGTH = 256;
19
+ const MAX_VALUE_LENGTH = 256;
20
+ const RENDER_LIMIT = 12;
21
+ export function paramsWritesPath(deckDir) {
22
+ return path.join(deckDir, '.castle', 'agent', 'params-writes.json');
23
+ }
24
+ const isValue = (v) => typeof v === 'number' || typeof v === 'boolean' || typeof v === 'string';
25
+ const clip = (v) => typeof v === 'string' ? v.slice(0, MAX_VALUE_LENGTH) : v;
26
+ // An id and a path both reach the router prompt verbatim, so one carrying a
27
+ // newline or a control character could forge a line -- or a whole section -- of
28
+ // the turn. A newline is a legal filename character and resolveDeckPath admits
29
+ // it, so the path needs the same scan the client-supplied id does.
30
+ const isPlain = (v, max) => {
31
+ if (typeof v !== 'string' || v.length > max)
32
+ return false;
33
+ for (let i = 0; i < v.length; i += 1) {
34
+ const code = v.charCodeAt(i);
35
+ if (code < 0x20 || (code >= 0x7f && code <= 0x9f) || code === 0x2028 || code === 0x2029) {
36
+ return false;
37
+ }
38
+ }
39
+ return true;
40
+ };
41
+ const isId = (v) => isPlain(v, MAX_ID_LENGTH);
42
+ const isPath = (v) => isPlain(v, MAX_PATH_LENGTH);
43
+ function tunedSlots(raw) {
44
+ if (!Array.isArray(raw))
45
+ return [];
46
+ return raw
47
+ .filter((slot) => isId(slot?.id) && isValue(slot.before) && isValue(slot.after))
48
+ .slice(0, SLOTS_PER_ENTRY)
49
+ .map((slot) => ({ id: slot.id, before: clip(slot.before), after: clip(slot.after) }));
50
+ }
51
+ export function readParamsWrites(deckDir) {
52
+ try {
53
+ const parsed = JSON.parse(fs.readFileSync(paramsWritesPath(deckDir), 'utf8'));
54
+ if (!Array.isArray(parsed))
55
+ return [];
56
+ return parsed.flatMap((entry) => {
57
+ const tuned = tunedSlots(entry?.tuned);
58
+ return typeof entry?.at === 'string' && isPath(entry?.path) && tuned.length
59
+ ? [{ at: entry.at, path: entry.path, tuned }]
60
+ : [];
61
+ });
62
+ }
63
+ catch {
64
+ return [];
65
+ }
66
+ }
67
+ // The marker is a claim by the client, so anything that is not the shape is
68
+ // dropped rather than refused: the file was already written, and a journal is
69
+ // not worth failing a save over.
70
+ export function recordParamsWrite(deckDir, rel, tuned) {
71
+ try {
72
+ if (!isPath(rel))
73
+ return;
74
+ const slots = tunedSlots(tuned);
75
+ if (!slots.length)
76
+ return;
77
+ const entry = { at: new Date().toISOString(), path: rel, tuned: slots };
78
+ const file = paramsWritesPath(deckDir);
79
+ fs.mkdirSync(path.dirname(file), { recursive: true });
80
+ const kept = [...readParamsWrites(deckDir), entry].slice(-LIMIT);
81
+ atomicWriteFileSync(file, `${JSON.stringify(kept, null, 2)}\n`);
82
+ }
83
+ catch {
84
+ /* the deck has no writable .castle -- there is nothing to report to. */
85
+ }
86
+ }
87
+ function agoPhrase(ms) {
88
+ const minutes = Math.floor(ms / 60000);
89
+ if (minutes < 1)
90
+ return 'just now';
91
+ if (minutes < 60)
92
+ return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;
93
+ const hours = Math.round(minutes / 60);
94
+ if (hours < 48)
95
+ return `${hours} hour${hours === 1 ? '' : 's'} ago`;
96
+ const days = Math.round(hours / 24);
97
+ return `${days} day${days === 1 ? '' : 's'} ago`;
98
+ }
99
+ function mostRecent(slots) {
100
+ if (slots.length <= RENDER_LIMIT)
101
+ return slots;
102
+ const keep = new Set([...slots]
103
+ .sort((a, b) => b[1] - a[1])
104
+ .slice(0, RENDER_LIMIT)
105
+ .map(([key]) => key));
106
+ return slots.filter(([key]) => keep.has(key));
107
+ }
108
+ /**
109
+ * One line per slot tuned since `since`, as `<file> <key> (<how long ago>)`,
110
+ * newest `RENDER_LIMIT` first-seen positions kept and a closing `and N more`
111
+ * when that dropped any.
112
+ *
113
+ * No values: a block carrying `old -> new` measurably makes the router write the
114
+ * number into plan.md and raise the tune on turns about something else, and the
115
+ * file is the one source of truth for what a `PARAMS` value is now
116
+ * (memos 26-09-18-09-20 and 26-09-18-12-49). The router reads the file when it
117
+ * needs the number.
118
+ *
119
+ * A scrub lands many writes on one key, so slots collapse: first tune keeps the
120
+ * position, last tune gives the time.
121
+ */
122
+ export function panelWritesSince(deckDir, since, now = Date.now()) {
123
+ const seen = new Map();
124
+ for (const entry of readParamsWrites(deckDir)) {
125
+ const at = Date.parse(entry.at);
126
+ if (!Number.isFinite(at) || at <= since)
127
+ continue;
128
+ for (const slot of entry.tuned)
129
+ seen.set(`${entry.path}\0${slot.id}`, at);
130
+ }
131
+ const slots = [...seen];
132
+ const dropped = Math.max(slots.length - RENDER_LIMIT, 0);
133
+ const lines = mostRecent(slots).map(([key, at]) => {
134
+ const [file, id] = key.split('\0');
135
+ return `${file} ${id} (${agoPhrase(now - at)})`;
136
+ });
137
+ return dropped > 0 ? [...lines, `and ${dropped} more`] : lines;
138
+ }
@@ -10,5 +10,5 @@ export declare function platformGuide(deckDir: string): string;
10
10
  export declare function writePlatformDocs(deckDir: string): void;
11
11
  export declare const CLAUDE_MD_IMPORT_LINE: string;
12
12
  export declare const CLAUDE_MD_PLATFORM_SECTION: string;
13
- export type ClaudeMdMigration = 'absent' | 'current' | 'migrated' | 'added' | 'kept' | 'gated';
13
+ export type ClaudeMdMigration = 'absent' | 'current' | 'migrated' | 'added' | 'kept';
14
14
  export declare function migrateClaudeMd(deckDir: string): ClaudeMdMigration;
@@ -67,18 +67,6 @@ export function everyDeckBullets(deckDir) {
67
67
  MODE_BULLET,
68
68
  ];
69
69
  }
70
- // ------------------------------------------------------------------- the gate
71
- // Whether this serve may rewrite an EXISTING deck's root CLAUDE.md onto the
72
- // @import. That rewrite is the one irreversible thing here, so it reaches decks
73
- // on a gate rather than all at once; off unless the serve was told otherwise.
74
- // Everything else is unconditional -- the guide written under .castle/docs, the
75
- // section a new deck scaffolds with, the block spawned agents get -- because
76
- // the kits are one shared artifact and stopped restating these rules for
77
- // everyone at once, gate or no gate. The cloud editor sets it per user from a
78
- // feature gate; see serveOnPort in castle-www's cloudSandbox.ts.
79
- function mayMigrateClaudeMd() {
80
- return process.env.CASTLE_PLATFORM_DOC === 'on';
81
- }
82
70
  // The line has to stand on its own to count: this repo's CLAUDE.md names the
83
71
  // path inside a sentence, and prose about the import must not read as a deck
84
72
  // carrying one.
@@ -152,12 +140,12 @@ export function claudeContextEnv(role) {
152
140
  }
153
141
  // A deck's quick reference as one agent role sees it. A task's claude
154
142
  // auto-loads the root CLAUDE.md -- but only a deck whose file carries the
155
- // @import line has the guide that way. A deck the migration has not reached
156
- // (gated off) or refused ('kept' -- someone edited its sections) still has the
157
- // four legacy sections inline and is missing just the every-deck bullets, which
158
- // left the kits' quick reference in the same change that added the guide. A
159
- // role that loads no CLAUDE.md (roleLoadsClaudeMd) takes the bullets here
160
- // whatever the deck's file says.
143
+ // @import line has the guide that way. A deck whose migration was refused
144
+ // ('kept' -- someone edited its sections) still has the four legacy sections
145
+ // inline and is missing just the every-deck bullets, which left the kits'
146
+ // quick reference in the same change that added the guide. A role that loads
147
+ // no CLAUDE.md (roleLoadsClaudeMd) takes the bullets here whatever the deck's
148
+ // file says.
161
149
  export function quickReferenceFor(deckDir, quickReference, role) {
162
150
  return roleLoadsClaudeMd(role) && deckLoadsGuide(deckDir)
163
151
  ? quickReference
@@ -342,8 +330,6 @@ const hash = (s) => crypto.createHash('sha256').update(s.trim()).digest('hex');
342
330
  // -- the deck chose its text; the prompt-side block still reaches spawned
343
331
  // agents). A file with no legacy sections at all just gains the section.
344
332
  export function migrateClaudeMd(deckDir) {
345
- if (!mayMigrateClaudeMd())
346
- return 'gated';
347
333
  const claudePath = path.join(deckDir, 'CLAUDE.md');
348
334
  let md;
349
335
  try {
package/dist/save-deck.js CHANGED
@@ -318,7 +318,15 @@ export async function saveDeck(dir, opts = {}) {
318
318
  // here can never overwrite their choice.
319
319
  if (backgroundImageFileId)
320
320
  cardInput.backgroundImageFileId = backgroundImageFileId;
321
- const result = await traceSaveStage('content_publish', () => api.updateCardAndDeckV2(deckInput, cardInput));
321
+ const result = await traceSaveStage('content_publish', () =>
322
+ // Character definitions are trusted publish metadata. They deliberately do
323
+ // not enter sceneData (the player downloads that payload); Ghost validates
324
+ // and stores this separate value for the character service. An explicit null
325
+ // clears prior definitions. Omitting the property preserves compatibility with
326
+ // deployed Ghost versions that predate the gated argument.
327
+ castleJson !== null && Object.prototype.hasOwnProperty.call(castleJson, 'characterBundle')
328
+ ? api.updateCardAndDeckV2(deckInput, cardInput, castleJson?.characterBundle ?? null)
329
+ : api.updateCardAndDeckV2(deckInput, cardInput));
322
330
  // Preserve any deck-owned config already in castle.json (notably the
323
331
  // `editor` block); save-deck only owns the identity fields below.
324
332
  const newCastleJson = {
package/dist/serve.js CHANGED
@@ -10,8 +10,10 @@ import { createIdeServer, FAVICON_FILES, FAVICON_LINK_TAGS } from './ide.js';
10
10
  import { createAgentServer } from './agent.js';
11
11
  import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin, sdkAliasPlugin, } from './vitePlugins.js';
12
12
  import { viteClientStubPlugin } from './viteClientStub.js';
13
+ import { paramsRegisterPlugin } from './paramsRegisterPlugin.js';
13
14
  import { createScriptErrors, scriptErrorsPlugin } from './scriptErrors.js';
14
15
  import { installFilesChangedWatcher } from './filesChanged.js';
16
+ import { applyDeckWrite, createTuneLedger } from './paramsTunes.js';
15
17
  import { autoUpdateImports, IMPORTS_DIR, lockImportTree } from './imports.js';
16
18
  import { ensureAgentsSymlink } from './init.js';
17
19
  import { migrateClaudeMd, PLATFORM_DOC_REL, writePlatformDocs } from './platformDoc.js';
@@ -721,7 +723,7 @@ async function devHostContext(projectDir) {
721
723
  username: me.username,
722
724
  };
723
725
  }
724
- async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multiplayerUrl, requestId, command, params) {
726
+ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multiplayerUrl, playSessionSlot, requestId, command, params) {
725
727
  const ctx = await devHostContext(projectDir);
726
728
  // The dev server services data commands via GraphQL but supplies no
727
729
  // platformHandler, so platform/capability commands (e.g. passes.purchase)
@@ -747,6 +749,7 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
747
749
  nonce: multiplayer.mintNonce(devMultiplayerIdentity(ctx)),
748
750
  sessionId: multiplayer.sessionId,
749
751
  soloReason: null,
752
+ ...(playSessionSlot ? { devReconnectScope: playSessionSlot } : {}),
750
753
  });
751
754
  },
752
755
  });
@@ -1063,7 +1066,11 @@ export async function serve(dir, options = {}) {
1063
1066
  // createAgentServer exists, and `playtest_request` needs the agent server's
1064
1067
  // warm Chromium and task store.
1065
1068
  const playtestHolder = { run: null };
1066
- const { broadcast, handleUpgrade: handleCastleUpgrade } = startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, devSession, playtestHolder);
1069
+ // Every write from an editor client goes through this, so the watcher can say
1070
+ // whether a broadcast is only tuned values -- and a write from anywhere else
1071
+ // breaks the chain, which is exactly what makes the answer trustworthy.
1072
+ const tuneLedger = createTuneLedger(projectDir);
1073
+ const { broadcast, handleUpgrade: handleCastleUpgrade } = startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, devSession, playtestHolder, tuneLedger);
1067
1074
  broadcastDevLog = broadcast;
1068
1075
  // Failed module transforms, remembered here so a deck whose entry never
1069
1076
  // evaluated can still be told what broke (scriptErrors.ts).
@@ -1074,6 +1081,7 @@ export async function serve(dir, options = {}) {
1074
1081
  const ideServer = createIdeServer({
1075
1082
  deckDir: projectDir,
1076
1083
  deckLabel: path.basename(projectDir),
1084
+ tuneLedger,
1077
1085
  // Same closure the agent server gets: invalidate then reload every tab.
1078
1086
  // `viteHolder` is read lazily because Vite is created further down.
1079
1087
  restart: () => {
@@ -1160,6 +1168,7 @@ export async function serve(dir, options = {}) {
1160
1168
  forksOverlayPlugin(),
1161
1169
  importsAliasPlugin(),
1162
1170
  sdkAliasPlugin(),
1171
+ paramsRegisterPlugin(projectDir, tuneLedger),
1163
1172
  sceneFilesPlugin(),
1164
1173
  scriptErrorsPlugin(scriptErrors),
1165
1174
  ],
@@ -1225,6 +1234,7 @@ export async function serve(dir, options = {}) {
1225
1234
  },
1226
1235
  invalidate: (paths) => invalidateModuleCaches(vite, paths),
1227
1236
  log: (line) => appendCapped(logFile, line),
1237
+ claimTunes: (relPath, event) => tuneLedger.claim(relPath, event),
1228
1238
  });
1229
1239
  // Bring content up first so `--open` cannot race an iframe against a port
1230
1240
  // that is not listening yet. Vite opens the shell from inside `vite.listen()`.
@@ -1403,7 +1413,7 @@ function handlePlaytestRequest(ws, msg, playtestHolder) {
1403
1413
  },
1404
1414
  }).then((result) => reply(result), (err) => reply({ ok: false, output: `Error: ${err instanceof Error ? err.message : String(err)}` }));
1405
1415
  }
1406
- function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, multiplayer, playtestHolder) {
1416
+ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, multiplayer, playtestHolder, tuneLedger) {
1407
1417
  // The control socket is upgraded directly on Vite's HTTP server. Browser
1408
1418
  // shell clients use the named path and a one-use ticket; pre-bridge SDKs use
1409
1419
  // a separate ticket carrying their content role. The root path is accepted
@@ -1481,6 +1491,7 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
1481
1491
  let msg = JSON.parse(text);
1482
1492
  let bridgeRole = null;
1483
1493
  let bridgeContentOrigin = null;
1494
+ let playSessionSlot = null;
1484
1495
  if (msg.type === 'deck_bridge') {
1485
1496
  if (legacyRole)
1486
1497
  return;
@@ -1489,6 +1500,10 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
1489
1500
  typeof msg.message !== 'object')
1490
1501
  return;
1491
1502
  bridgeRole = msg.role;
1503
+ if (bridgeRole === 'play' &&
1504
+ typeof msg.playSessionSlot === 'string' &&
1505
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(msg.playSessionSlot))
1506
+ playSessionSlot = msg.playSessionSlot;
1492
1507
  bridgeContentOrigin = trustedBridgeContentOrigin(security, req, bridgeRole, msg.contentOrigin);
1493
1508
  msg = msg.message;
1494
1509
  if (!BRIDGED_CONTENT_MESSAGES.has(String(msg.type)))
@@ -1613,7 +1628,7 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
1613
1628
  }));
1614
1629
  return;
1615
1630
  }
1616
- const response = writeProjectFile(projectDir, msg.path, msg.contents);
1631
+ const response = writeProjectFile(projectDir, msg.path, msg.contents, tuneLedger);
1617
1632
  ws.send(JSON.stringify({
1618
1633
  type: 'write_file_response',
1619
1634
  requestId: msg.requestId,
@@ -1646,7 +1661,7 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
1646
1661
  ? devMultiplayerUrlFromOrigin(bridgeContentOrigin ??
1647
1662
  security.contentOrigins(req)[bridgeRole === 'edit' ? 'editOrigin' : 'playOrigin'])
1648
1663
  : multiplayerUrl;
1649
- void handleCastleCommand(ws, projectDir, broadcast, multiplayer, commandMultiplayerUrl, msg.requestId, msg.command, msg.params);
1664
+ void handleCastleCommand(ws, projectDir, broadcast, multiplayer, commandMultiplayerUrl, playSessionSlot, msg.requestId, msg.command, msg.params);
1650
1665
  }
1651
1666
  }
1652
1667
  catch {
@@ -1695,7 +1710,7 @@ function trustedBridgeContentOrigin(security, request, role, value) {
1695
1710
  };
1696
1711
  return security.verifyContentRequest(synthetic) === role ? origin : null;
1697
1712
  }
1698
- function writeProjectFile(projectDir, requestedPath, contents) {
1713
+ function writeProjectFile(projectDir, requestedPath, contents, ledger) {
1699
1714
  if (typeof requestedPath !== 'string' || requestedPath.trim() === '') {
1700
1715
  return { ok: false, error: 'Missing file path.' };
1701
1716
  }
@@ -1738,15 +1753,8 @@ function writeProjectFile(projectDir, requestedPath, contents) {
1738
1753
  }
1739
1754
  target = fork;
1740
1755
  }
1741
- try {
1742
- fs.mkdirSync(path.dirname(target), { recursive: true });
1743
- fs.writeFileSync(target, contents, 'utf-8');
1744
- return { ok: true, path: normalized };
1745
- }
1746
- catch (error) {
1747
- const message = error instanceof Error ? error.message : String(error);
1748
- return { ok: false, error: `Could not write ${requestedPath}: ${message}` };
1749
- }
1756
+ const written = applyDeckWrite({ abs: target, rel: relPosix, contents, ledger });
1757
+ return written.ok ? { ok: true, path: normalized } : { ok: false, error: written.error };
1750
1758
  }
1751
1759
  // Resolve a deck-relative path for a mutating op (write/rename). Same guards as
1752
1760
  // `writeProjectFile`: no traversal, no protected dirs, imports only via an own