castle-web-cli 0.4.228 → 0.4.230

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 (236) hide show
  1. package/dist/agent-prompts.d.ts +11 -3
  2. package/dist/agent-prompts.js +153 -53
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +43 -33
  5. package/dist/api.d.ts +47 -2
  6. package/dist/api.js +85 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +779 -3
  9. package/dist/castleJson.d.ts +59 -0
  10. package/dist/castleJson.js +267 -3
  11. package/dist/check.js +27 -1
  12. package/dist/cloudGit.d.ts +20 -1
  13. package/dist/cloudGit.js +267 -10
  14. package/dist/contentPack.d.ts +49 -0
  15. package/dist/contentPack.js +273 -0
  16. package/dist/devExperiments.d.ts +21 -0
  17. package/dist/devExperiments.js +139 -0
  18. package/dist/devHub.d.ts +55 -0
  19. package/dist/devHub.js +187 -0
  20. package/dist/devSessionChild.js +3 -1
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +229 -44
  23. package/dist/experimentAssignment.d.ts +15 -0
  24. package/dist/experimentAssignment.js +41 -0
  25. package/dist/importCheckHook.d.ts +40 -0
  26. package/dist/importCheckHook.js +171 -0
  27. package/dist/importRegression.d.ts +15 -0
  28. package/dist/importRegression.js +100 -0
  29. package/dist/importTrust.d.ts +2 -0
  30. package/dist/importTrust.js +27 -0
  31. package/dist/importUpdateHook.d.ts +18 -0
  32. package/dist/importUpdateHook.js +31 -8
  33. package/dist/importUpdateHookRunner.js +19 -7
  34. package/dist/imports.d.ts +16 -0
  35. package/dist/imports.js +145 -33
  36. package/dist/index.js +8 -1
  37. package/dist/init.d.ts +3 -0
  38. package/dist/init.js +125 -8
  39. package/dist/install.js +4 -1
  40. package/dist/localPaths.js +4 -0
  41. package/dist/login.js +2 -2
  42. package/dist/platformDoc.js +3 -8
  43. package/dist/playPagePolicy.js +3 -1
  44. package/dist/remix.js +5 -0
  45. package/dist/routerTaskReport.d.ts +28 -0
  46. package/dist/routerTaskReport.js +56 -0
  47. package/dist/save-deck.d.ts +18 -0
  48. package/dist/save-deck.js +145 -6
  49. package/dist/serve.d.ts +8 -0
  50. package/dist/serve.js +94 -13
  51. package/dist/serverBundle.d.ts +1 -1
  52. package/dist/serverBundle.js +5 -1
  53. package/dist/sourceLineage.d.ts +42 -0
  54. package/dist/sourceLineage.js +380 -0
  55. package/dist/webSourceSync.d.ts +11 -0
  56. package/dist/webSourceSync.js +26 -9
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +301 -52
  60. package/kits/base/sdk/agent.js +4 -4
  61. package/kits/base/sdk/avatar.d.ts +12 -0
  62. package/kits/base/sdk/avatar.js +23 -0
  63. package/kits/base/sdk/castle.d.ts +6 -1
  64. package/kits/base/sdk/castle.js +3 -0
  65. package/kits/base/sdk/commands.d.ts +208 -0
  66. package/kits/base/sdk/commands.js +16 -0
  67. package/kits/base/sdk/context.d.ts +6 -0
  68. package/kits/base/sdk/experiments.d.ts +15 -0
  69. package/kits/base/sdk/experiments.js +83 -0
  70. package/kits/base/sdk/hub.d.ts +85 -0
  71. package/kits/base/sdk/hub.js +107 -0
  72. package/kits/base/sdk/multiplayer.d.ts +86 -6
  73. package/kits/base/sdk/multiplayer.js +157 -4
  74. package/kits/base/sdk/server/hub.d.ts +169 -0
  75. package/kits/base/sdk/server/hub.js +125 -0
  76. package/kits/base/sdk/server/platformHandle.d.ts +49 -2
  77. package/kits/base/sdk/server/storage.d.ts +55 -2
  78. package/kits/base/sdk/server/wrapper.d.ts +85 -6
  79. package/kits/base/sdk/server/wrapper.js +393 -30
  80. package/kits/base/sdk/transport.d.ts +2 -1
  81. package/kits/base/sdk/transport.js +13 -1
  82. package/kits/hub-game/.prettierrc +5 -0
  83. package/kits/hub-game/CLAUDE.md +146 -0
  84. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  88. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  89. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  90. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  91. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  92. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  93. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  94. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  95. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  96. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  97. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  98. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  99. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  100. package/kits/hub-game/castle.json +96 -0
  101. package/kits/hub-game/code/client/attention.js +133 -0
  102. package/kits/hub-game/code/client/avatar.js +288 -0
  103. package/kits/hub-game/code/client/cabinets.js +90 -0
  104. package/kits/hub-game/code/client/chat.js +135 -0
  105. package/kits/hub-game/code/client/chrome.js +1001 -0
  106. package/kits/hub-game/code/client/doorFrame.js +15 -0
  107. package/kits/hub-game/code/client/firstJoin.js +14 -0
  108. package/kits/hub-game/code/client/grab.js +241 -0
  109. package/kits/hub-game/code/client/hookLayer.js +230 -0
  110. package/kits/hub-game/code/client/idle.js +326 -0
  111. package/kits/hub-game/code/client/keys.js +48 -0
  112. package/kits/hub-game/code/client/pack.js +232 -0
  113. package/kits/hub-game/code/client/packFormat.js +397 -0
  114. package/kits/hub-game/code/client/say.js +127 -0
  115. package/kits/hub-game/code/client/sha256.js +80 -0
  116. package/kits/hub-game/code/client/sound.js +147 -0
  117. package/kits/hub-game/code/client/state.js +131 -0
  118. package/kits/hub-game/code/client/talk.js +259 -0
  119. package/kits/hub-game/code/client/together.js +365 -0
  120. package/kits/hub-game/code/client/wear.js +149 -0
  121. package/kits/hub-game/code/server/actors.js +627 -0
  122. package/kits/hub-game/code/server/blocks.js +103 -0
  123. package/kits/hub-game/code/server/cabinets.js +309 -0
  124. package/kits/hub-game/code/server/game.js +137 -0
  125. package/kits/hub-game/code/server/grab.js +247 -0
  126. package/kits/hub-game/code/server/history.js +96 -0
  127. package/kits/hub-game/code/server/hub.js +1904 -0
  128. package/kits/hub-game/code/server/idle.js +412 -0
  129. package/kits/hub-game/code/server/index.js +64 -0
  130. package/kits/hub-game/code/server/labels.js +59 -0
  131. package/kits/hub-game/code/server/manifest.js +527 -0
  132. package/kits/hub-game/code/server/npcs.js +745 -0
  133. package/kits/hub-game/code/server/party.js +381 -0
  134. package/kits/hub-game/code/server/place.js +43 -0
  135. package/kits/hub-game/code/server/say.js +83 -0
  136. package/kits/hub-game/code/server/wear.js +142 -0
  137. package/kits/hub-game/code/systems/hub.js +2230 -0
  138. package/kits/hub-game/docs/content-pack.md +151 -0
  139. package/kits/hub-game/docs/contract.md +1139 -0
  140. package/kits/hub-game/docs/style.md +137 -0
  141. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  142. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  143. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  144. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  145. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  146. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  147. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  148. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  149. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  150. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  151. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  152. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  153. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  154. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  155. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  156. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  157. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  158. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  159. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  160. package/kits/hub-game/eslint.config.js +20 -0
  161. package/kits/hub-game/fonts.generated.js +9 -0
  162. package/kits/hub-game/index.html +22 -0
  163. package/kits/hub-game/main.jsx +6 -0
  164. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  165. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  167. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  168. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  169. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  170. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  171. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  172. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  174. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  175. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  176. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  177. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  178. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  179. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  180. package/kits/hub-game/package-lock.json +365 -0
  181. package/kits/hub-game/package.json +32 -0
  182. package/kits/hub-game/scenes/main.scene +318 -0
  183. package/kits/hub-game/scripts/check.mjs +339 -0
  184. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  185. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  186. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  187. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  188. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  189. package/kits/hub-game/scripts/pack.mjs +192 -0
  190. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  191. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  192. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  193. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  194. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  195. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  196. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  197. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  198. package/kits/hub-game/scripts/test-door.mjs +56 -0
  199. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  200. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  201. package/kits/hub-game/scripts/test-hub-trip.mjs +1310 -0
  202. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  203. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  204. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  205. package/kits/hub-game/scripts/test-manifest.mjs +224 -0
  206. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  207. package/kits/hub-game/scripts/test-npcs.mjs +714 -0
  208. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  209. package/kits/hub-game/scripts/test-party.mjs +286 -0
  210. package/kits/hub-game/scripts/test-say.mjs +149 -0
  211. package/kits/hub-game/scripts/test-together.mjs +183 -0
  212. package/kits/hub-game/theme.style +3 -0
  213. package/kits/multiplayer-3d/castle.json +5 -5
  214. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  215. package/kits/multiplayer-3d/code/server/players.js +4 -1
  216. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  217. package/kits/multiplayer-3d/code/server/world.js +20 -7
  218. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  219. package/kits/physics-2d/castle.json +2 -2
  220. package/kits/physics-2d/engine/art.js +13 -0
  221. package/kits/physics-2d/engine/assets.js +4 -2
  222. package/kits/physics-2d/engine/scene.js +25 -5
  223. package/kits/physics-3d/CLAUDE.md +6 -1
  224. package/kits/physics-3d/castle.json +3 -3
  225. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +32 -4
  226. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  227. package/kits/physics-3d/engine3d/materials.js +29 -1
  228. package/kits/physics-3d/engine3d/world3d.js +65 -1
  229. package/kits/physics-3d/systems/physics3d.js +5 -2
  230. package/kits/real-time/castle.json +2 -2
  231. package/kits/real-time/code/client/connection.js +77 -7
  232. package/kits/real-time/code/client/gameHooks.js +63 -3
  233. package/kits/real-time/code/client/messages.js +7 -0
  234. package/kits/real-time/code/server/gameHooks.js +24 -0
  235. package/kits/real-time/code/server/session.js +390 -22
  236. package/package.json +2 -2
@@ -0,0 +1,380 @@
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as zlib from 'zlib';
5
+ import * as api from './api.js';
6
+ // Which saved version a folder with no sync record came from. Without this, `source-status
7
+ // --adopt` records the deck's current saved version, which is right for a folder that was
8
+ // fetched from it and wrong for one copied from an older save (the Sep 13-14 legacy-home
9
+ // import left a few dozen such folders behind a save made elsewhere): adopting the current
10
+ // key would let the folder's next save overwrite the newer copy without a word.
11
+ //
12
+ // Every save is kept under its own key, so the folder is compared with the deck's saved
13
+ // versions by identical path + sha256. An older version is adopted only when it matches
14
+ // strictly more files than the current one; a folder that grew, shrank or was reworked since
15
+ // the current save still matches the current save best. Bounded by time and bytes: whatever
16
+ // is not settled within the budget falls back to the current version, as before.
17
+ /** Files that differ between any two copies of the same work: tooling rewrites and metadata. */
18
+ const NOISE_FILES = new Set([
19
+ 'castle.json',
20
+ 'package.json',
21
+ 'package-lock.json',
22
+ 'pnpm-lock.yaml',
23
+ 'pnpm-workspace.yaml',
24
+ 'CLAUDE.md',
25
+ 'AGENTS.md',
26
+ 'fonts.generated.js',
27
+ 'preview.png',
28
+ ]);
29
+ /** Top-level entries the archive leaves out (save-deck SOURCE_ARCHIVE_EXCLUDES). */
30
+ const ARCHIVE_EXCLUDES = new Set(['node_modules', 'dist', '.castle', '.git', 'imports']);
31
+ // Measured from when source-status starts, so its own source query counts too: castle-www's
32
+ // open gives the --adopt and --notify calls 15 s between them.
33
+ export const LINEAGE_BUDGET_MS = 9_000;
34
+ const MAX_VERSIONS_EXAMINED = 20;
35
+ const MAX_ARCHIVE_BYTES_TOTAL = 200 * 1024 * 1024;
36
+ const MAX_UNPACKED_BYTES = 512 * 1024 * 1024;
37
+ const MAX_FOLDER_FILES = 20_000;
38
+ const MAX_FOLDER_BYTES = 512 * 1024 * 1024;
39
+ /** Whether a source path counts toward a match: skips noise, dotfiles at the top, `._*`. */
40
+ export function countsTowardMatch(rel) {
41
+ const parts = rel.split('/');
42
+ if (parts.some((part) => part === '' || part === '.' || part === '..'))
43
+ return false;
44
+ if (parts[0].startsWith('.') || ARCHIVE_EXCLUDES.has(parts[0]))
45
+ return false;
46
+ if (parts.includes('node_modules'))
47
+ return false;
48
+ const base = parts[parts.length - 1];
49
+ if (base.startsWith('._'))
50
+ return false;
51
+ if (parts.length === 1 && NOISE_FILES.has(base))
52
+ return false;
53
+ return true;
54
+ }
55
+ class LineageLimit extends Error {
56
+ }
57
+ const HASH_CHUNK_BYTES = 1024 * 1024;
58
+ function hashFile(file, expired) {
59
+ const hash = crypto.createHash('sha256');
60
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
61
+ try {
62
+ const chunk = Buffer.allocUnsafe(HASH_CHUNK_BYTES);
63
+ for (;;) {
64
+ if (expired())
65
+ throw new LineageLimit('budget');
66
+ const read = fs.readSync(fd, chunk, 0, chunk.length, null);
67
+ if (read === 0)
68
+ break;
69
+ hash.update(chunk.subarray(0, read));
70
+ }
71
+ }
72
+ finally {
73
+ fs.closeSync(fd);
74
+ }
75
+ return hash.digest('hex');
76
+ }
77
+ /**
78
+ * The folder's regular files as the archive would carry them, hashed in chunks; null past the
79
+ * size caps or once `expired` says the time is up.
80
+ */
81
+ export function folderManifest(dir, expired = () => false) {
82
+ const out = new Map();
83
+ let bytes = 0;
84
+ const walk = (rel) => {
85
+ for (const entry of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
86
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
87
+ if (entry.isDirectory()) {
88
+ if (!rel && (ARCHIVE_EXCLUDES.has(entry.name) || entry.name.startsWith('.')))
89
+ continue;
90
+ if (entry.name === 'node_modules')
91
+ continue;
92
+ walk(child);
93
+ }
94
+ else if (entry.isFile() && countsTowardMatch(child)) {
95
+ // Sized before anything is read, so one huge asset cannot run memory or time out.
96
+ bytes += fs.lstatSync(path.join(dir, child)).size;
97
+ if (out.size >= MAX_FOLDER_FILES || bytes > MAX_FOLDER_BYTES)
98
+ throw new LineageLimit('folder');
99
+ out.set(child, hashFile(path.join(dir, child), expired));
100
+ }
101
+ }
102
+ };
103
+ try {
104
+ walk('');
105
+ }
106
+ catch (error) {
107
+ if (error instanceof LineageLimit)
108
+ return null;
109
+ throw error;
110
+ }
111
+ return out;
112
+ }
113
+ function readString(block, start, length) {
114
+ const slice = block.subarray(start, start + length);
115
+ const end = slice.indexOf(0);
116
+ return slice.subarray(0, end === -1 ? slice.length : end).toString('utf-8');
117
+ }
118
+ function readSize(block) {
119
+ const field = block.subarray(124, 136);
120
+ if (field[0] & 0x80) {
121
+ // base-256: a size too big for octal. Nothing a deck saves gets there; refuse it.
122
+ throw new LineageLimit('archive');
123
+ }
124
+ const text = readString(block, 124, 12).trim();
125
+ return text ? parseInt(text, 8) : 0;
126
+ }
127
+ function paxPath(body) {
128
+ let offset = 0;
129
+ let found;
130
+ while (offset < body.length) {
131
+ const space = body.indexOf(0x20, offset);
132
+ if (space === -1)
133
+ break;
134
+ const length = parseInt(body.subarray(offset, space).toString('utf-8'), 10);
135
+ if (!Number.isFinite(length) || length <= 0)
136
+ break;
137
+ const record = body.subarray(space + 1, offset + length - 1).toString('utf-8');
138
+ const eq = record.indexOf('=');
139
+ if (eq !== -1 && record.slice(0, eq) === 'path')
140
+ found = record.slice(eq + 1);
141
+ offset += length;
142
+ }
143
+ return found;
144
+ }
145
+ function normalizeArchivePath(name) {
146
+ let rel = name;
147
+ while (rel.startsWith('./'))
148
+ rel = rel.slice(2);
149
+ return rel.replace(/\/+$/, '');
150
+ }
151
+ /**
152
+ * The regular files of a gzipped tar, hashed as they stream (ustar, pax `path`, GNU long
153
+ * names). Links and everything else are skipped; nothing is written to disk.
154
+ */
155
+ export function archiveManifest(gz, expired = () => false) {
156
+ return new Promise((resolve, reject) => {
157
+ const out = new Map();
158
+ const gunzip = zlib.createGunzip();
159
+ let pending = Buffer.alloc(0);
160
+ let unpacked = 0;
161
+ let done = false;
162
+ // The tar's end blocks were read: the rest is only drained, so gunzip still checks its footer.
163
+ let ended = false;
164
+ // The entry being read: its remaining body bytes, padding, and what to do with them.
165
+ let body = null;
166
+ let nextName;
167
+ const finish = (error) => {
168
+ if (done)
169
+ return;
170
+ done = true;
171
+ if (error) {
172
+ gunzip.destroy();
173
+ reject(error);
174
+ }
175
+ else
176
+ resolve(out);
177
+ };
178
+ const endEntry = () => {
179
+ const entry = body;
180
+ body = null;
181
+ if (entry.kind === 'file' && entry.hash) {
182
+ const rel = normalizeArchivePath(entry.name);
183
+ if (countsTowardMatch(rel))
184
+ out.set(rel, entry.hash.digest('hex'));
185
+ }
186
+ else if (entry.kind === 'pax') {
187
+ nextName = paxPath(Buffer.concat(entry.collect)) ?? nextName;
188
+ }
189
+ else if (entry.kind === 'longname') {
190
+ nextName = readString(Buffer.concat(entry.collect), 0, Number.MAX_SAFE_INTEGER);
191
+ }
192
+ };
193
+ const consume = () => {
194
+ for (;;) {
195
+ if (body) {
196
+ if (body.remaining > 0) {
197
+ if (pending.length === 0)
198
+ return;
199
+ const take = Math.min(body.remaining, pending.length);
200
+ const chunk = pending.subarray(0, take);
201
+ body.hash?.update(chunk);
202
+ body.collect?.push(Buffer.from(chunk));
203
+ body.remaining -= take;
204
+ pending = pending.subarray(take);
205
+ continue;
206
+ }
207
+ if (pending.length < body.padding)
208
+ return;
209
+ pending = pending.subarray(body.padding);
210
+ endEntry();
211
+ continue;
212
+ }
213
+ if (pending.length < 512)
214
+ return;
215
+ const block = pending.subarray(0, 512);
216
+ pending = pending.subarray(512);
217
+ if (block.every((byte) => byte === 0)) {
218
+ ended = true;
219
+ pending = Buffer.alloc(0);
220
+ return;
221
+ }
222
+ const size = readSize(block);
223
+ const type = String.fromCharCode(block[156] || 0x30);
224
+ let name = readString(block, 0, 100);
225
+ if (readString(block, 257, 5) === 'ustar') {
226
+ const prefix = readString(block, 345, 155);
227
+ if (prefix)
228
+ name = `${prefix}/${name}`;
229
+ }
230
+ if (nextName !== undefined && type !== 'x' && type !== 'L') {
231
+ name = nextName;
232
+ nextName = undefined;
233
+ }
234
+ const kind = type === '0' || type === '7' ? 'file' : type === 'x' ? 'pax' : type === 'L' ? 'longname' : 'skip';
235
+ if ((kind === 'pax' || kind === 'longname') && size > 1024 * 1024)
236
+ throw new LineageLimit('archive');
237
+ body = {
238
+ remaining: size,
239
+ padding: (512 - (size % 512)) % 512,
240
+ hash: kind === 'file' ? crypto.createHash('sha256') : null,
241
+ collect: kind === 'pax' || kind === 'longname' ? [] : null,
242
+ kind,
243
+ name,
244
+ };
245
+ }
246
+ };
247
+ gunzip.on('data', (chunk) => {
248
+ if (done)
249
+ return;
250
+ unpacked += chunk.length;
251
+ if (unpacked > MAX_UNPACKED_BYTES) {
252
+ finish(new LineageLimit('archive'));
253
+ return;
254
+ }
255
+ if (expired()) {
256
+ finish(new LineageLimit('budget'));
257
+ return;
258
+ }
259
+ if (ended)
260
+ return;
261
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
262
+ try {
263
+ consume();
264
+ }
265
+ catch (error) {
266
+ finish(error instanceof Error ? error : new Error('unreadable archive'));
267
+ }
268
+ });
269
+ // Complete only with the tar's end blocks and gunzip's verified footer (gunzip errors
270
+ // without it): a cut-off current archive would otherwise lose the comparison unfairly.
271
+ gunzip.on('end', () => finish(ended ? undefined : new Error('truncated archive')));
272
+ gunzip.on('error', (error) => finish(error));
273
+ gunzip.end(gz);
274
+ });
275
+ }
276
+ /** How many files the two copies hold identically. */
277
+ export function matchScore(folder, saved) {
278
+ let score = 0;
279
+ for (const [rel, sha] of saved)
280
+ if (folder.get(rel) === sha)
281
+ score += 1;
282
+ return score;
283
+ }
284
+ async function fetchArchiveBytes(url, timeoutMs) {
285
+ const res = await fetch(url, { signal: AbortSignal.timeout(Math.max(1, timeoutMs)) });
286
+ if (!res.ok)
287
+ throw new Error(`archive fetch failed: HTTP ${res.status}`);
288
+ return Buffer.from(await res.arrayBuffer());
289
+ }
290
+ /**
291
+ * The saved version this folder descends from. Never throws: any failure (an older Ghost,
292
+ * a fetch error, the budget) settles on the current version, which is what adopt recorded
293
+ * before this existed.
294
+ */
295
+ export async function findLineage(dir, deckId, server, deps = {}) {
296
+ const nowMs = deps.nowMs ?? Date.now;
297
+ const deadline = deps.deadlineMs ?? nowMs() + LINEAGE_BUDGET_MS;
298
+ const expired = () => nowMs() >= deadline;
299
+ const fetchArchive = deps.fetchArchive ?? fetchArchiveBytes;
300
+ const current = (reason, examined = 0) => ({ outcome: 'skipped', version: server, examined, reason });
301
+ if (expired())
302
+ return current('budget');
303
+ let versions;
304
+ try {
305
+ versions = await (deps.listVersions ?? api.savedSourceHistory)(deckId, deadline - nowMs());
306
+ }
307
+ catch {
308
+ return current(expired() ? 'budget' : 'history_unavailable');
309
+ }
310
+ const head = versions.find((v) => v.s3Key === server.s3Key);
311
+ if (!head)
312
+ return current('current_not_listed');
313
+ const serverMs = Date.parse(server.updatedAt);
314
+ // Older saves only: a refused save leaves its object behind too, and one newer than the
315
+ // current row was never the saved copy.
316
+ const older = versions
317
+ .filter((v) => v.s3Key !== server.s3Key && Date.parse(v.savedAt) < serverMs)
318
+ .sort((a, b) => Date.parse(b.savedAt) - Date.parse(a.savedAt))
319
+ .slice(0, MAX_VERSIONS_EXAMINED - 1);
320
+ if (older.length === 0)
321
+ return { outcome: 'current', version: server, examined: 0 };
322
+ let folder;
323
+ try {
324
+ folder = folderManifest(dir, expired);
325
+ }
326
+ catch {
327
+ return current('folder_unreadable');
328
+ }
329
+ if (!folder)
330
+ return current(expired() ? 'budget' : 'folder_too_large');
331
+ let bytes = 0;
332
+ const read = async (version) => {
333
+ const remaining = deadline - nowMs();
334
+ bytes += version.bytes;
335
+ if (remaining <= 0 || bytes > MAX_ARCHIVE_BYTES_TOTAL)
336
+ return null;
337
+ try {
338
+ return await archiveManifest(await fetchArchive(version.archiveUrl, remaining), expired);
339
+ }
340
+ catch {
341
+ return null;
342
+ }
343
+ };
344
+ const score = async (version) => {
345
+ const manifest = await read(version);
346
+ return manifest && matchScore(folder, manifest);
347
+ };
348
+ const headManifest = await read(head);
349
+ if (headManifest === null)
350
+ return current(expired() ? 'budget' : 'current_unreadable', 1);
351
+ const headScore = matchScore(folder, headManifest);
352
+ // Everything the current save holds is here unchanged: whatever else the folder has, it
353
+ // is not missing that save's work.
354
+ if (headScore === headManifest.size)
355
+ return { outcome: 'current', version: server, examined: 1 };
356
+ let examined = 1;
357
+ let best = null;
358
+ let reason;
359
+ for (const version of older) {
360
+ const s = await score(version);
361
+ if (s === null) {
362
+ reason = nowMs() >= deadline ? 'budget' : bytes > MAX_ARCHIVE_BYTES_TOTAL ? 'bytes' : 'archive_unreadable';
363
+ if (reason !== 'archive_unreadable')
364
+ break;
365
+ continue;
366
+ }
367
+ examined += 1;
368
+ // Newest first, so a tie keeps the newer of two equally good older saves.
369
+ if (s > headScore && (!best || s > best.score))
370
+ best = { version, score: s };
371
+ }
372
+ if (!best)
373
+ return { outcome: 'current', version: server, examined, ...(reason ? { reason } : {}) };
374
+ return {
375
+ outcome: 'older',
376
+ version: { s3Key: best.version.s3Key, updatedAt: best.version.savedAt },
377
+ examined,
378
+ ...(reason ? { reason } : {}),
379
+ };
380
+ }
@@ -1,3 +1,4 @@
1
+ import type { Lineage, LineageDeps } from './sourceLineage.js';
1
2
  export declare const WEB_SOURCE_SYNC_FILE: string;
2
3
  /** `get-deck --side` copies of the saved source, one folder per saved version. */
3
4
  export declare const SAVED_SOURCE_DIR: string;
@@ -47,6 +48,8 @@ export declare function fetchServerSourceVersion(deckId: string): Promise<Server
47
48
  export declare function humanTime(iso: string): string;
48
49
  /** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
49
50
  export declare const EXIT_SAVED_DECK_NEWER = 5;
51
+ /** save-deck's exit code when an unsynced folder would move the saved deck's imports back. */
52
+ export declare const EXIT_IMPORTS_OLDER = 6;
50
53
  export declare const SAVE_REFUSED_PREFIX = "CASTLE_SAVE_REFUSED ";
51
54
  export declare const SAVED_DECK_NEWER_CODE = "SAVED_DECK_NEWER";
52
55
  /** Ghost's code when its own check (primary, under lock) refuses the source commit. */
@@ -66,6 +69,12 @@ export interface SourceStatusResult {
66
69
  marker: Omit<WebSourceSyncMarker, 'deckId'> | null;
67
70
  server: ServerSourceVersion | null;
68
71
  adopted?: true;
72
+ /** How --adopt chose the version it recorded (sourceLineage.ts). */
73
+ lineage?: {
74
+ outcome: Lineage['outcome'];
75
+ examined: number;
76
+ reason?: string;
77
+ };
69
78
  notified?: true;
70
79
  }
71
80
  export interface SourceStatusOptions {
@@ -73,6 +82,8 @@ export interface SourceStatusOptions {
73
82
  notify?: boolean;
74
83
  /** Injected by tests; defaults to the webDeckSource query. */
75
84
  fetchServer?: (deckId: string) => Promise<ServerSourceVersion | null>;
85
+ /** Injected by tests; defaults to sourceLineage's findLineage. */
86
+ findLineage?: (dir: string, deckId: string, server: ServerSourceVersion, deps: LineageDeps) => Promise<Lineage>;
76
87
  now?: () => Date;
77
88
  }
78
89
  export declare function sourceNewerNotice(dir: string, savedAt: string, syncedAt: string): {
@@ -12,6 +12,8 @@ import { WEB_SOURCE_NEWER_MARKER_FILE } from './cloudGit.js';
12
12
  // It lives in `.castle/agent/`: excluded from the source archive (so it never travels into a
13
13
  // save or a remix), and a durable editor namespace in deck persistence (so a cold resume keeps
14
14
  // it). A missing or malformed marker reads as absent: the folder is then adopted, never refused.
15
+ // `source-status --adopt` records the saved version the folder actually matches
16
+ // (sourceLineage.ts), so a folder copied from an older save is told the saved copy is newer.
15
17
  export const WEB_SOURCE_SYNC_FILE = path.join('.castle', 'agent', 'web-source-sync.json');
16
18
  /** `get-deck --side` copies of the saved source, one folder per saved version. */
17
19
  export const SAVED_SOURCE_DIR = path.join('.castle', 'agent', 'saved-source');
@@ -123,6 +125,8 @@ export function humanTime(iso) {
123
125
  // --- save-deck refusal --------------------------------------------------------
124
126
  /** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
125
127
  export const EXIT_SAVED_DECK_NEWER = 5;
128
+ /** save-deck's exit code when an unsynced folder would move the saved deck's imports back. */
129
+ export const EXIT_IMPORTS_OLDER = 6;
126
130
  export const SAVE_REFUSED_PREFIX = 'CASTLE_SAVE_REFUSED ';
127
131
  export const SAVED_DECK_NEWER_CODE = 'SAVED_DECK_NEWER';
128
132
  /** Ghost's code when its own check (primary, under lock) refuses the source commit. */
@@ -168,6 +172,7 @@ export async function sourceStatus(dir, opts = {}) {
168
172
  return result;
169
173
  }
170
174
  async function computeSourceStatus(dir, opts) {
175
+ const startedAtMs = Date.now();
171
176
  const projectDir = path.resolve(dir);
172
177
  // An unreadable or missing folder is a real error, unlike a folder that isn't a deck.
173
178
  if (!fs.statSync(projectDir).isDirectory())
@@ -191,18 +196,29 @@ async function computeSourceStatus(dir, opts) {
191
196
  return result;
192
197
  if (!marker) {
193
198
  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;
199
+ if (!opts.adopt)
200
+ return result;
201
+ const { findLineage: defaultFindLineage, LINEAGE_BUDGET_MS } = await import('./sourceLineage.js');
202
+ const lineage = await (opts.findLineage ?? defaultFindLineage)(projectDir, deckId, server, {
203
+ deadlineMs: startedAtMs + LINEAGE_BUDGET_MS,
204
+ });
205
+ const written = writeSyncMarker(projectDir, deckId, lineage.version, 'adopt', opts.now?.());
206
+ result.marker = { s3Key: written.s3Key, updatedAt: written.updatedAt, syncedAt: written.syncedAt, via: written.via };
207
+ result.adopted = true;
208
+ result.lineage = {
209
+ outcome: lineage.outcome,
210
+ examined: lineage.examined,
211
+ ...(lineage.reason ? { reason: lineage.reason } : {}),
212
+ };
213
+ // Adopted at an older save: from here on it is an ordinary folder behind the saved copy.
214
+ if (lineage.outcome !== 'older')
215
+ return result;
200
216
  }
201
- result.status = compareSync(marker, server);
217
+ result.status = compareSync(result.marker, server);
202
218
  if (result.status === 'saved-newer' && opts.notify) {
203
219
  const file = path.join(projectDir, WEB_SOURCE_NEWER_MARKER_FILE);
204
220
  fs.mkdirSync(path.dirname(file), { recursive: true });
205
- atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, marker.updatedAt))}\n`);
221
+ atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, result.marker.updatedAt))}\n`);
206
222
  result.notified = true;
207
223
  }
208
224
  return result;
@@ -222,7 +238,8 @@ export function describeSourceStatus(result) {
222
238
  case 'lag':
223
239
  return `The server has not caught up with this folder's last save yet (${humanTime(result.marker.updatedAt)}).`;
224
240
  case 'saved-newer':
225
- return (`The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
241
+ return ((result.adopted ? `This folder matches an older save of deck ${result.deckId}. ` : '') +
242
+ `The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
226
243
  `this folder last synced ${humanTime(result.marker.updatedAt)}).` +
227
244
  (result.notified ? ' The agent has been told.' : ''));
228
245
  }
@@ -15,7 +15,7 @@ that framework provides. This one is true either way.
15
15
  <!-- Injected into Castle's create assistant every turn; keep this compact and factual. -->
16
16
 
17
17
  - `import { setup, initCard } from 'castle-web-sdk'`. Call `setup()` first, once; `initCard()` returns the element to render into (a React tree mounted at `#root` needs no `initCard`). Castle services — `Store`, `Leaderboard`, `Time`, `User`, `Haptics`, `Pass`, `Snapshot`, `Portal`, `Multiplayer`, `Lifecycle` — come from the same package. `Store` is how a deck saves anything; the older `Storage`/`SharedStorage` still work but should not be used in new decks; the full reference is `imports/castle.base/sdk/README.md`.
18
- - `Agent.chat({ messages, tools?, toolChoice?, model?, maxTokens?, reasoning?, onDelta?, signal? })` gets one chat completion from a language model (OpenAI message and tool format, default model `meta/muse-spark-1.3-contributor`; any OpenRouter model id with a per-token price) through Castle's deck-agent service, paid from the player's daily play allowance that characters share. `onDelta` streams text and reasoning pieces and each finished tool call; `signal` cancels; `reasoning: { effort: 'minimal' | 'low' | 'medium' | 'high' }` sets how hard the model thinks, and minimal answers soonest. It resolves with the whole `message`: the deck runs any `tool_calls` itself, appends the message unchanged (it can carry the model's `reasoning_details`) and the `tool` results, and calls again. Admin only: other players get `refused`; a player whose allowance for the day is spent gets `allowance_exhausted` (it resets at midnight UTC).
18
+ - `Agent.chat({ messages, tools?, toolChoice?, model?, maxTokens?, reasoning?, onDelta?, signal? })` gets one chat completion from a language model (OpenAI message and tool format, default model `meta/muse-spark-1.3-contributor`; any OpenRouter model id with a per-token price) through Castle's deck-agent service, paid from the player's daily play allowance that characters share. `onDelta` streams text and reasoning pieces and each finished tool call; `signal` cancels; `reasoning: { effort: 'minimal' | 'low' | 'medium' | 'high' }` sets how hard the model thinks, and minimal answers soonest. It resolves with the whole `message`: the deck runs any `tool_calls` itself, appends the message unchanged (it can carry the model's `reasoning_details`) and the `tool` results, and calls again. Castle admins and players given access only: other players get `refused`; a player whose allowance for the day is spent gets `allowance_exhausted` (it resets at midnight UTC).
19
19
  - `Decks.mine({ limit? })` and `Decks.saved({ limit? })` list decks a portal can lead to (the player's published decks; their bookmarks and playlists) as `{ deckId, title, creator, coverUrl }`, with `coverUrl` a `data:` url. Use them to offer a portal destination picker. Admin only: other players get a `PERMISSION_DENIED` error.
20
20
  - What each service cannot do is in that README beside the service: `Store` / `Storage` size caps (no media in storage), the Castle app build a command needs (older builds reject it with `UNKNOWN_COMMAND`), no clipboard command, no call that sets the deck's cover. Read it before telling someone a service can or cannot do something.
21
21
  - The SDK is a file of this import, not an npm package: `castle-web-sdk` resolves here. Nothing needs installing, and nothing in a deck's `package.json` names it.
@@ -35,8 +35,7 @@ named in the bullet above.
35
35
 
36
36
  The three calls almost every deck makes:
37
37
 
38
- - `setup()` — once, before anything else. Mounts the Castle card (5:7, or the
39
- whole stage for a deck that declares `castle-display` fill) and, while
38
+ - `setup()` — once, before anything else. Mounts the 5:7 Castle card and, while
40
39
  serving locally, forwards `console` output to the CLI.
41
40
  - `initCard()` — the element to draw into, when the deck renders into a
42
41
  `<canvas>` or raw DOM rather than a React tree at `#root`.
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-09-30T05:53:28.406Z",
85
+ "publishedVersion": "2026-10-04T01:28:15.203Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]