castle-web-cli 0.4.250 → 0.4.251

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.
@@ -1 +1 @@
1
- export declare const CHARACTER_DOC = "# Characters, in practice\n\nRead this before writing or changing a deck's `characterBundle`, its\n`Characters` client code, or the server's story calls. Written fresh by the\nCastle CLI at every serve start, only because this deck's `castle.json` has a\n`characterBundle`. Characters are experimental and not open to players yet:\npublishing works, but conversations only run for accounts Castle has let in.\n\n## The three parts\n\n- **`characterBundle` in `castle.json`**: `version` (the bundle's label),\n `characters` (each `{ id, version, name, instructions }`), `eventTypes`\n (each `{ id, claims: [{ id, text, witnessCharacterIds }] }`) and `beats`.\n All four are required; `eventTypes` and `beats` may be empty. Ghost\n rejects unknown keys. Limits: 48 characters, 32 event types, 8 claims per\n event type, 12 witnesses per claim, 64 beats, `instructions` 8000\n characters, claim text 500, the whole bundle 192 KiB.\n- **Client**: `import { Characters } from \"castle-web-sdk\"`, then\n `Characters.open(id)`, and `send`, `status`, `history` and `reset` on the handle.\n- **Server**: `session.storage.playthrough(player.userId)` in the deck's\n server, with `recordEvent`, `deliverKnowledge`, `completeBeat`, `status`\n and `history` under `.characters`, plus `get`/`set`/`remove` for\n playthrough game state.\n\nEach player has their own copy of every character (a **playthrough**). Castle\npicks the characters' model; a deck cannot choose it or give a character tools.\nThis guide covers the basic bundle and playthrough API above; other bundle\nfields (gameplay, information rules, schedulers, runtime characters, actions,\nrepeatable events) are gated pilots that creator decks cannot use.\n\n## Publish before you test\n\nCharacters only run in a published deck, including in the local preview,\nwhich talks to the real character service under the deck's id. After any\nchange to `characterBundle`, run `save-deck` before trying a conversation.\nKeep the key in `castle.json`: every save publishes the bundle with that\nversion of the deck. `\"characterBundle\": null` removes it. Deleting the key\nsends nothing, so the last bundle stays tied to an older version of the deck\nand characters stop opening after the next save. A playthrough keeps the bundle\nit started with until the player resets.\n\n## Bundle rules\n\n- `instructions` is the character's private brief: personality, wants, voice,\n what it would never say. Keep story facts out of it; facts reach a character\n through events, so it learns them when they happen.\n- In the basic bundle an event type happens at most once per playthrough. Recording it tells no\n one; the server then delivers claims. `source: { type: \"creator_event\" }`\n reaches only a claim's declared witnesses; `source: { type: \"character\",\n characterId }` relays it from a character that already knows the same claims\n of the same occurrence. Nothing spreads on its own, and what a character says\n never becomes world fact.\n- A beat (`opportunity: \"opening\"`, `repeat: \"once_per_event\"`, the only\n values) opens the character's next reply with `openingText` once it knows\n the beat's `requiredClaimIds`. The reply carries `result.selectedBeat`. The\n beat is finished only when the server calls `completeBeat` with one of its\n `completionOutcomeIds`; apply game effects after that, not before.\n\n## Client rules\n\n- `Characters.open(id)` returns `{ generation, definitionVersion, character,\n previewAllowance }` and admits the player. It runs no model and spends\n nothing. Open every character before the server records events for that\n player, and again after a reset.\n- `send({ operationId, input })` returns before the reply: poll\n `status(operationId)` until `completed`, `failed` or `interrupted`. A\n finished status can arrive with `result: null`, so fetch status once more.\n `progress?.response` is a disposable draft while running; replace it with\n `result.response`.\n- Input is 1-2000 characters; operation ids are at most 120. One new\n `crypto.randomUUID()` per message, kept until the reply arrives. After a lost\n response, ask `status` or `history` with the same id. Never resend under a\n new id (that is a second, billed message), and never replay a message into a\n new generation for the player.\n- `history({ limit, cursor })` is newest first, `limit` 1-50, `cursor` null\n on the last page. Show completed operations with a `response`, oldest first.\n- `reset(operationId)` resets the whole deck playthrough for every character\n and returns a handle in the new generation. On a lost response, reopen: a\n higher generation means it happened; otherwise retry on the old handle with\n the same id. Clear every cached message, draft and story flag after.\n- Tag pending replies with character id and generation so a late reply never\n lands in another conversation or a fresh playthrough. Bind the send button and\n Enter key yourself (a `<form>` may not submit in the player frame) and keep\n movement keys from firing while typing.\n- Errors are `CastleError` codes: `CAULDRON_CHARACTER_UNAVAILABLE` (not open\n for this deck or player, service off, or the deck's daily limit reached),\n `CAULDRON_CHARACTER_BACKLOG_LIMIT` (the player's daily allowance is used up,\n or too many replies are waiting), `CAULDRON_CHARACTER_NOT_FOUND`,\n `CAULDRON_CHARACTER_INVALID_ARGUMENT`, `CAULDRON_CHARACTER_CONFLICT` (an\n operation id reused with different text) and\n `CAULDRON_STORAGE_STALE_GENERATION` (an old handle after a reset; reopen).\n In creator decks, players under 13 or of unknown age get no character talk,\n so the deck must still make sense without it.\n\n## Server rules\n\n- The story calls need a running server, even for one player: a `server`\n entry (`maxPlayers: 1`, `tickRate: 0` is fine) and a named room per player,\n keyed by a hash of the user id. The key only picks the room; identity comes\n from the callback's `player`. A private deck gets no server (`conn.isSolo`),\n so test on an unlisted deck.\n- Always `session.storage.playthrough(player.userId)`, never a user id from a\n message. Have the client send its `generation` with each story action and\n ignore actions from an earlier one.\n- Every story call takes an `operationId` and returns an operation that may be\n `queued` or `running`: poll `characters.status` until it finishes before\n using `result` (`recordEvent` gives `result.eventOccurrenceId`). Build\n operation ids from a client request id so a retried action cannot apply\n twice. History holds story operations too, so a restarted server can rebuild\n its state from it.\n- Keep story flags in `playthrough.get/set/remove`, which reset with the\n characters, not in `session.storage.user`.\n\n## Shared characters\n\nA destination in `server.destinations` with `characters: \"shared\"`,\n`selection: \"exact\"` and `persistence: \"world\"` makes the bundle's\ncharacters shared by everyone in that world: one memory per world, while each\nplayer sees only their own conversations. The bundle needs\n`\"conversation\": { \"version\": 1, \"authority\": \"server\", \"maxListeners\": 0 }`\n(up to 3 listeners) or every turn is refused. Clients join with\n`Multiplayer.joinDestination({ routeId, slot })` (each slot is its own world),\ncheck `connection.sharedCharacters`, send with `connection.requestCharacterTurn({\nrequestId, operationId, characterId, input, audience? })`, poll\n`getCharacterTurnStatus(operationId)` until it leaves `queued`/`running`\n(the reply is `response`), and load replies with `readCharacters({ requestId,\nquery: { type: \"history\", characterId, limit, cursor } })`, whose operations\ncarry `response` but not the player's words. `audience` is `{ characterIds\n}` for characters who overhear, `playerIds` (up to 7 connected players) and\n`disclosure` (`participants` by default, or `world`). After\n`CAULDRON_CHARACTER_TIMEOUT` or a closed connection, ask status with the same\noperation id; never resend under a new one.\n\nThe deck server must let each request through: `onWorldCharacterTurn(session,\nturn)` calls `turn.send()` or `turn.reject(code)`, and\n`onWorldCharacterCommand` (`apply`/`reject`) and `onWorldCharacterRead`\n(`read`/`reject`) do the same; returning without settling rejects. The\nserver cannot change the speaker, input or audience. A character runs one turn\nat a time with two more waiting (`CAULDRON_SHARED_CHARACTER_BUSY` past that).\nShared worlds have no playthroughs or resets, and `session.storage.playthrough`\nis not available in them.\n";
1
+ export declare const CHARACTER_DOC = "# Characters, in practice\n\nRead this before adding characters to a deck or changing its\n`characterBundle`, its `Characters` client code, a shared world's\ncharacter requests, or the server's story or character callbacks. Written fresh\nby the Castle CLI at every serve start. Characters are experimental: open to\nCastle creators, and the details may still change. Creator docs:\ndocs.castle.xyz/docs/cauldron/characters.\n\n## The three parts\n\n- **`characterBundle` in `castle.json`**: `version` (the bundle's label),\n `characters` (each `{ id, version, name, instructions }`), `eventTypes`\n (each `{ id, claims: [{ id, text, witnessCharacterIds }] }`) and `beats`.\n All four are required; `eventTypes` and `beats` may be empty. Ghost\n rejects unknown keys. Limits: 48 characters, 32 event types, 8 claims per\n event type, 12 witnesses per claim, 64 beats, `instructions` 8000\n characters, claim text 500, the whole bundle 192 KiB.\n- **Client**: `import { Characters } from \"castle-web-sdk\"`, then\n `Characters.open(id)`, and `send`, `status`, `history` and `reset` on the handle.\n- **Server**: `session.storage.playthrough(player.userId)` in the deck's\n server, with `recordEvent`, `deliverKnowledge`, `completeBeat`, `status`\n and `history` under `.characters`, plus `get`/`set`/`remove` for\n playthrough game state.\n\nEach player has their own copy of every character (a **playthrough**), unless\nthe bundle has a `conversation` block, which makes every character in it\nshared instead (see \"One kind per deck\" below). Castle picks the characters' model; a deck cannot choose it or give a character tools.\nThis guide covers the basic bundle and playthrough API above; other bundle\nfields (gameplay, information rules, schedulers, runtime characters, actions,\nrepeatable events) are gated pilots that creator decks cannot use.\n\n## Publish before you test\n\nCharacters only run in a published deck, including in the local preview,\nwhich talks to the real character service under the deck's id. After any\nchange to `characterBundle`, run `save-deck` before trying a conversation.\nKeep the key in `castle.json`: every save publishes the bundle with that\nversion of the deck. `\"characterBundle\": null` removes it. Deleting the key\nsends nothing, so the last bundle stays tied to an older version of the deck\nand characters stop opening after the next save. A playthrough keeps the bundle\nit started with until the player resets.\n\n## Bundle rules\n\n- `instructions` is the character's private brief: personality, wants, voice,\n what it would never say. Keep story facts out of it; facts reach a character\n through events, so it learns them when they happen.\n- In the basic bundle an event type happens at most once per playthrough. Recording it tells no\n one; the server then delivers claims. `source: { type: \"creator_event\" }`\n reaches only a claim's declared witnesses; `source: { type: \"character\",\n characterId }` relays it from a character that already knows the same claims\n of the same occurrence. Nothing spreads on its own, and what a character says\n never becomes world fact.\n- A beat (`opportunity: \"opening\"`, `repeat: \"once_per_event\"`, the only\n values) opens the character's next reply with `openingText` once it knows\n the beat's `requiredClaimIds`. The reply carries `result.selectedBeat`. The\n beat is finished only when the server calls `completeBeat` with one of its\n `completionOutcomeIds`; apply game effects after that, not before.\n\n## Client rules\n\n- `Characters.open(id)` returns `{ generation, definitionVersion, character,\n previewAllowance }` and admits the player. It runs no model and spends\n nothing. Open every character before the server records events for that\n player, and again after a reset.\n- `send({ operationId, input })` returns before the reply: poll\n `status(operationId)` until `completed`, `failed` or `interrupted`. A\n finished status can arrive with `result: null`, so fetch status once more.\n `progress?.response` is a disposable draft while running; replace it with\n `result.response`.\n- Input is 1-2000 characters; operation ids are at most 120. One new\n `crypto.randomUUID()` per message, kept until the reply arrives. After a lost\n response, ask `status` or `history` with the same id. Never resend under a\n new id (that is a second, billed message), and never replay a message into a\n new generation for the player.\n- `history({ limit, cursor })` is newest first, `limit` 1-50, `cursor` null\n on the last page. Show completed operations with a `response`, oldest first.\n- `reset(operationId)` resets the whole deck playthrough for every character\n and returns a handle in the new generation. On a lost response, reopen: a\n higher generation means it happened; otherwise retry on the old handle with\n the same id. Clear every cached message, draft and story flag after.\n- Tag pending replies with character id and generation so a late reply never\n lands in another conversation or a fresh playthrough. Bind the send button and\n Enter key yourself (a `<form>` may not submit in the player frame) and keep\n movement keys from firing while typing.\n- Errors are `CastleError` codes: `CAULDRON_CHARACTER_UNAVAILABLE` (not open\n for this deck or player, service off, or the deck's daily limit reached),\n `CAULDRON_CHARACTER_BACKLOG_LIMIT` (the player's daily allowance is used up,\n or too many replies are waiting), `CAULDRON_CHARACTER_NOT_FOUND`,\n `CAULDRON_CHARACTER_INVALID_ARGUMENT`, `CAULDRON_CHARACTER_CONFLICT` (an\n operation id reused with different text) and\n `CAULDRON_STORAGE_STALE_GENERATION` (an old handle after a reset; reopen).\n In creator decks, players under 13 or of unknown age get no character talk,\n so the deck must still make sense without it.\n\n## Server rules\n\n- The story calls need a running server, even for one player: a `server`\n entry (`maxPlayers: 1`, `tickRate: 0` is fine) and a named room per player,\n keyed by a hash of the user id. The key only picks the room; identity comes\n from the callback's `player`. A private deck gets no server (`conn.isSolo`),\n so test on an unlisted deck.\n- Always `session.storage.playthrough(player.userId)`, never a user id from a\n message. Have the client send its `generation` with each story action and\n ignore actions from an earlier one.\n- Every story call takes an `operationId` and returns an operation that may be\n `queued` or `running`: poll `characters.status` until it finishes before\n using `result` (`recordEvent` gives `result.eventOccurrenceId`). Build\n operation ids from a client request id so a retried action cannot apply\n twice. History holds story operations too, so a restarted server can rebuild\n its state from it.\n- Keep story flags in `playthrough.get/set/remove`, which reset with the\n characters, not in `session.storage.user`.\n\n## One kind per deck\n\nA deck has exactly one `characterBundle`, and its `conversation` block\ndecides the kind for every character in it:\n\n- **No `conversation` block**: playthrough characters, talked to with\n `Characters.open` / `send`. A shared destination refuses every turn.\n- **With the block**: shared characters, talked to through a shared\n destination. `Characters.send` is refused for all of them with\n `CAULDRON_CHARACTER_INVALID_ARGUMENT` (\"this deck's characterBundle has a\n conversation block...\").\n\nSo one deck cannot hold a playthrough character and a shared one. When someone\nasks for both, say so before building and let them choose: make them all\nshared (everyone meets them in the world), keep them all playthrough, or make\nthe shared world a second deck. Do not try a second bundle (a deck has one),\nand do not drop the `conversation` block to get a playthrough character\ntalking: that breaks every shared turn.\n\n## Shared characters\n\nA destination in `server.destinations` with `characters: \"shared\"`,\n`selection: \"exact\"` and `persistence: \"world\"` makes the bundle's\ncharacters shared by everyone in that world: one memory per world, while each\nplayer sees only their own conversations. The bundle needs\n`\"conversation\": { \"version\": 1, \"authority\": \"server\", \"maxListeners\": 0 }`\n(up to 3 listeners) or every turn is refused. Clients join with\n`Multiplayer.joinDestination({ routeId, slot })` (each slot is its own world),\ncheck `connection.sharedCharacters`, send with `connection.requestCharacterTurn({\nrequestId, operationId, characterId, input, audience? })`, poll\n`getCharacterTurnStatus(operationId)` until it leaves `queued`/`running`\n(the reply is `response`), and load replies with `readCharacters({ requestId,\nquery: { type: \"history\", characterId, limit, cursor } })`, whose operations\ncarry `response` but not the player's words. `audience` is `{ characterIds\n}` for characters who overhear, `playerIds` (up to 7 connected players) and\n`disclosure` (`participants` by default, or `world`). After\n`CAULDRON_CHARACTER_TIMEOUT` or a closed connection, ask status with the same\noperation id; never resend under a new one.\n\nThe deck server must let each request through: `onWorldCharacterTurn(session,\nturn)` calls `turn.send()` or `turn.reject(code)`, and\n`onWorldCharacterCommand` (`apply`/`reject`) and `onWorldCharacterRead`\n(`read`/`reject`) do the same; returning without settling rejects. The\nserver cannot change the speaker, input or audience. A character runs one turn\nat a time with two more waiting (`CAULDRON_SHARED_CHARACTER_BUSY` past that).\nShared worlds have no playthroughs or resets, and `session.storage.playthrough`\nis not available in them.\n";
@@ -1,17 +1,15 @@
1
- // The on-demand characters guide, written beside platform.md at serve start
2
- // only for a deck whose castle.json declares a characterBundle (platformDoc.ts
3
- // owns the path and the writing). Characters are experimental and not open to
4
- // creators yet, so nothing about them reaches a deck that has not opted in:
5
- // no bullet in platform.md, no line in any prompt. A deck with a bundle gets one
6
- // pointer bullet in its platform.md and this file. The creator-facing pages are
7
- // castle-docs docs/cauldron/characters; keep the two in step.
1
+ // The on-demand characters guide, written beside platform.md at every serve
2
+ // start (platformDoc.ts owns the path, the writing and the one pointer bullet in
3
+ // platform.md). The creator-facing pages are castle-docs
4
+ // docs/cauldron/characters; keep the two in step.
8
5
  export const CHARACTER_DOC = `# Characters, in practice
9
6
 
10
- Read this before writing or changing a deck's \`characterBundle\`, its
11
- \`Characters\` client code, or the server's story calls. Written fresh by the
12
- Castle CLI at every serve start, only because this deck's \`castle.json\` has a
13
- \`characterBundle\`. Characters are experimental and not open to players yet:
14
- publishing works, but conversations only run for accounts Castle has let in.
7
+ Read this before adding characters to a deck or changing its
8
+ \`characterBundle\`, its \`Characters\` client code, a shared world's
9
+ character requests, or the server's story or character callbacks. Written fresh
10
+ by the Castle CLI at every serve start. Characters are experimental: open to
11
+ Castle creators, and the details may still change. Creator docs:
12
+ docs.castle.xyz/docs/cauldron/characters.
15
13
 
16
14
  ## The three parts
17
15
 
@@ -29,8 +27,9 @@ publishing works, but conversations only run for accounts Castle has let in.
29
27
  and \`history\` under \`.characters\`, plus \`get\`/\`set\`/\`remove\` for
30
28
  playthrough game state.
31
29
 
32
- Each player has their own copy of every character (a **playthrough**). Castle
33
- picks the characters' model; a deck cannot choose it or give a character tools.
30
+ Each player has their own copy of every character (a **playthrough**), unless
31
+ the bundle has a \`conversation\` block, which makes every character in it
32
+ shared instead (see "One kind per deck" below). Castle picks the characters' model; a deck cannot choose it or give a character tools.
34
33
  This guide covers the basic bundle and playthrough API above; other bundle
35
34
  fields (gameplay, information rules, schedulers, runtime characters, actions,
36
35
  repeatable events) are gated pilots that creator decks cannot use.
@@ -118,6 +117,25 @@ it started with until the player resets.
118
117
  - Keep story flags in \`playthrough.get/set/remove\`, which reset with the
119
118
  characters, not in \`session.storage.user\`.
120
119
 
120
+ ## One kind per deck
121
+
122
+ A deck has exactly one \`characterBundle\`, and its \`conversation\` block
123
+ decides the kind for every character in it:
124
+
125
+ - **No \`conversation\` block**: playthrough characters, talked to with
126
+ \`Characters.open\` / \`send\`. A shared destination refuses every turn.
127
+ - **With the block**: shared characters, talked to through a shared
128
+ destination. \`Characters.send\` is refused for all of them with
129
+ \`CAULDRON_CHARACTER_INVALID_ARGUMENT\` ("this deck's characterBundle has a
130
+ conversation block...").
131
+
132
+ So one deck cannot hold a playthrough character and a shared one. When someone
133
+ asks for both, say so before building and let them choose: make them all
134
+ shared (everyone meets them in the world), keep them all playthrough, or make
135
+ the shared world a second deck. Do not try a second bundle (a deck has one),
136
+ and do not drop the \`conversation\` block to get a playthrough character
137
+ talking: that breaks every shared turn.
138
+
121
139
  ## Shared characters
122
140
 
123
141
  A destination in \`server.destinations\` with \`characters: "shared"\`,
@@ -2,7 +2,6 @@ export declare const PLATFORM_DOCS_DIR: string;
2
2
  export declare const PLATFORM_DOC_REL: string;
3
3
  export declare const MULTIPLAYER_DOC_REL: string;
4
4
  export declare const CHARACTER_DOC_REL: string;
5
- export declare function deckDeclaresCharacters(deckDir: string): boolean;
6
5
  export declare function everyDeckBullets(deckDir: string): string[];
7
6
  export declare const HOST_LIMIT_BULLETS: string[];
8
7
  export declare const CASTLE_UI_BULLETS: string[];
@@ -4,7 +4,6 @@ import * as path from 'path';
4
4
  import { resolveFileTypes } from './editorConfig.js';
5
5
  import { MULTIPLAYER_DOC } from './multiplayerDoc.js';
6
6
  import { CHARACTER_DOC } from './characterDoc.js';
7
- import { readCastleJson } from './castleJson.js';
8
7
  // The platform's own guidance to agents -- the rules identical in a bare deck
9
8
  // and a kit deck: the card, touch, assets and formats, imports, reloading,
10
9
  // editors. Its one home is here. The serve writes it under the deck's .castle/
@@ -28,18 +27,15 @@ export const PLATFORM_DOC_REL = path.join(PLATFORM_DOCS_DIR, 'platform.md');
28
27
  // holds its text, platform.md's Multiplayer section points at this path, and
29
28
  // nothing puts it in a prompt.
30
29
  export const MULTIPLAYER_DOC_REL = path.join(PLATFORM_DOCS_DIR, 'multiplayer.md');
31
- // The characters guide (characterDoc.ts), written only for a deck whose
32
- // castle.json declares a characterBundle, and removed again when it no longer
33
- // does. Characters are not open to creators, so no other deck hears of them.
30
+ // The characters guide (characterDoc.ts), read on demand like multiplayer.md
31
+ // and written for every deck. Characters are open to creators, and an agent
32
+ // adding them to a deck from scratch is the one that most needs the guide: a
33
+ // deck has no characterBundle until that agent writes one, and the docs are
34
+ // only rewritten at the next serve start.
34
35
  export const CHARACTER_DOC_REL = path.join(PLATFORM_DOCS_DIR, 'characters.md');
35
- export function deckDeclaresCharacters(deckDir) {
36
- const castleJson = readCastleJson(deckDir);
37
- const bundle = castleJson?.characterBundle;
38
- return typeof bundle === 'object' && bundle !== null && !Array.isArray(bundle);
39
- }
40
36
  const CHARACTER_POINTER = `## Characters
41
37
 
42
- - **Read \`${CHARACTER_DOC_REL}\` before writing or changing this deck's \`characterBundle\`, its \`Characters\` client code, or its server's story calls.** Characters are experimental; that guide has the bundle rules, the publish-before-testing rule, and the send, recovery and reset handling a hand-written conversation gets wrong.
38
+ - **Read \`${CHARACTER_DOC_REL}\` before adding characters to this deck or changing its \`characterBundle\`, its \`Characters\` client code, a shared world's character requests, or its server's story or character callbacks.** Characters are experimental; that guide has the bundle rules (including that a deck's characters are all playthrough or all shared), the publish-before-testing rule, the server callbacks shared characters need, and the send, recovery and reset handling a hand-written conversation gets wrong.
43
39
  `;
44
40
  const MEDIA = {
45
41
  images: ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'],
@@ -334,6 +330,8 @@ const COMMON_SECTIONS = `## Imports are read-only
334
330
  export function platformGuide(deckDir) {
335
331
  return `${COMMON_SECTIONS.trimEnd()}
336
332
 
333
+ ${CHARACTER_POINTER.trimEnd()}
334
+
337
335
  ## Formats, reloading, editors
338
336
 
339
337
  ${everyDeckBullets(deckDir).filter((b) => !b.includes('PARAMS')).join('\n')}
@@ -358,7 +356,7 @@ How every Castle deck works, from the Castle CLI. Written fresh at every serve
358
356
  start; the deck's own guide (its kit's CLAUDE.md under imports/) adds what its
359
357
  kit provides on top of this.
360
358
 
361
- ${platformGuide(deckDir)}${deckDeclaresCharacters(deckDir) ? `\n${CHARACTER_POINTER}` : ''}`;
359
+ ${platformGuide(deckDir)}`;
362
360
  }
363
361
  // Written by the serve at every start, so the copy in a deck is exactly as
364
362
  // fresh as the CLI serving it. platform.md is the always-loaded one; the
@@ -376,12 +374,8 @@ export function writePlatformDocs(deckDir) {
376
374
  catch (error) {
377
375
  console.warn(`Could not write ${MULTIPLAYER_DOC_REL}: ${error instanceof Error ? error.message : String(error)}`);
378
376
  }
379
- const characterDoc = path.join(deckDir, CHARACTER_DOC_REL);
380
377
  try {
381
- if (deckDeclaresCharacters(deckDir))
382
- fs.writeFileSync(characterDoc, CHARACTER_DOC);
383
- else
384
- fs.rmSync(characterDoc, { force: true });
378
+ fs.writeFileSync(path.join(deckDir, CHARACTER_DOC_REL), CHARACTER_DOC);
385
379
  }
386
380
  catch (error) {
387
381
  console.warn(`Could not write ${CHARACTER_DOC_REL}: ${error instanceof Error ? error.message : String(error)}`);
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-11-19T05:45:37.255Z",
85
+ "publishedVersion": "2026-11-19T09:37:15.255Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -209,9 +209,6 @@ platform applies each request only while `writer` (from `claim`) still holds
209
209
  is per request: a `set` or `remove` too big for one request is split, and when
210
210
  the claim is lost partway the earlier requests stay written and the rest are not
211
211
  sent. Without the option the request is unchanged. castle-web serve refuses a checked write instead of emulating it.
212
- Writer checks are not yet supported in persistent-world sessions: there a checked
213
- write (`set`, `remove` or `increment` on a scope, playthrough `set` or `remove`) is refused with
214
- `CAULDRON_STORAGE_UNAVAILABLE` and nothing is written, until a server update ships.
215
212
  Deck-scope storage writes are not fenced by either generation; a server using
216
213
  `session.storage.deck` must discard its own stale queued writes and cached
217
214
  per-player values when it observes a newer reset marker.
@@ -21,9 +21,7 @@ export interface ServerStorageListPage<T extends Json = Json> {
21
21
  * `writer` (from `claim`) still holds `target` for this session, checked atomically
22
22
  * with the write; otherwise it rejects with `CAULDRON_STORAGE_WRITER_LOST`
23
23
  * (`committed: false`) and nothing is written. A `set` large enough to need several
24
- * requests checks each one, so a claim lost partway stops the rest. Not yet supported
25
- * in persistent-world sessions: there a checked write is refused with
26
- * `CAULDRON_STORAGE_UNAVAILABLE` (nothing written) until a server update ships.
24
+ * requests checks each one, so a claim lost partway stops the rest.
27
25
  */
28
26
  export interface ServerStorageWriteOptions {
29
27
  check?: {
@@ -664,8 +664,10 @@ function readPlace(block, where, defaultScene, serverMax, sceneExists, errors, d
664
664
  errors.push(`${where}.resumeWindowSec must be a whole number of seconds from 1 to 180, or absent.`);
665
665
  } else if (place.result) {
666
666
  errors.push(`${where}.resumeWindowSec is only for a place without a result.`);
667
- } else if (place.resumePose || place.houseResume || block.resumeArrivalPose !== undefined) {
668
- errors.push(`${where}.resumeWindowSec cannot combine with resumePose, houseResume or resumeArrivalPose.`);
667
+ } else if (place.houseResume || block.resumeArrivalPose !== undefined) {
668
+ // v1.230: resumePose may stay beside it, as the Town has both: the pinned window holds the
669
+ // same visit, and resumePose's cold pose store still restores a new id after it.
670
+ errors.push(`${where}.resumeWindowSec cannot combine with houseResume or resumeArrivalPose.`);
669
671
  } else {
670
672
  place.resumeWindowSec = sec;
671
673
  }
@@ -141,7 +141,7 @@ reading the saved deck, treats the same list as no unlocks at all.
141
141
  | `resumeArrivalPose` | true | v1.117, optional per place: preserve only the last server pose/facing for a same-player-id, same signed-in account reconnect strictly within 60 wall-clock seconds. Ordinary immediate `leave` and fresh `arrive` still run; the pose replaces normal placement after `arrive`. Result places also require `resume: true`. Cannot combine with `resume: { keep: true }`, `resumePose`, or `houseResume`. Server-only; absent leaves state, lifecycle and wire bytes unchanged. See §12. |
142
142
  | `writerLease` | true | v1.192, optional per place: newest instance to claim an account owns its per-player saves. Requires the host save API; otherwise pass-through. Server-only. See Writer leases below. |
143
143
  | `resumePose` | true | v1.98, per non-result place only: retain a same-id visit and its last pose/facing for strictly less than five wall-clock minutes, restoring before hello replay or the deck step. No leave/arrive on retention; explicit kit travel, expiry and shutdown still leave, and new IDs may restore a server-stored pose for the same account/place within ten minutes of departure; kit travel clears it, and so does a drop right after the player's own Back (v1.173 `hub-back`, §12). Absent: no retention state or behavior change. Server-only; no new wire fields. See §12. |
144
- | `resumeWindowSec` | integer | v1.199, per place without a result: a whole number of seconds, 1 to 180, that Castle holds a dropped player's visit for. On a capable host Ghost pins it into the session as `reconnectWindowMs`, and the kit then retains the same visit and pose through that deadline (inclusive) with no leave or arrival hook, as it does for the Town ("Door resume window"). Any other value, or the key with `result`, `resumePose`, `houseResume` or `resumeArrivalPose`, is a manifest error. Absent, an older Ghost or a host without reconnect grace: no window, and a drop ends the visit as before. Server-only; no wire change. |
144
+ | `resumeWindowSec` | integer | v1.199, per place without a result: a whole number of seconds, 1 to 180, that Castle holds a dropped player's visit for. On a capable host Ghost pins it into the session as `reconnectWindowMs`, and the kit then retains the same visit and pose through that deadline (inclusive) with no leave or arrival hook, as it does for the Town ("Door resume window"). Any other value, or the key with `result`, `houseResume` or `resumeArrivalPose`, is a manifest error (v1.230: `resumePose` may stand beside it). Absent, an older Ghost or a host without reconnect grace: no window, and a drop ends the visit as before. Server-only; no wire change. |
145
145
  | `heldOffers` | true | v1.180, per place, server-only: `hub.actions`, `hub.ask` and `hub.menu` offers made to a retained player are kept while they are away and replayed with fresh versions on their resume hello; calls made while away are recorded, not sent, and the latest is delivered at resume. Kept only for the same transport id, signed-in account and visit body (§12 "Held offers"). Only `true`; any other value is a manifest error, and so is the key in a place with no resume mode (`resume: { keep: true }`, `resumePose`, `houseResume`, or a place without a result, which a host may pin a reconnect window on; `resumeArrivalPose` has none). Absent: offers are pruned while disconnected and places re-offer from their resume hook, with identical behaviour and bytes. |
146
146
  | `talkLog` | true | v1.101, per place: NPC talk input and replies append to the platform’s private indefinite archive. Authored answers/openings wait for durable acknowledgment; model input/reply commit with their jobs. No player read API or TTL. Requires a host/runtime that offers transcript support; unavailable writes stop the answer. Absent key performs no archive requests and preserves existing protocol. |
147
147
  | `under13Choices` | true | Authored mind taps lead both published `childAsks` and legacy choices, including here (v1.150, §13). Otherwise published mind `childAsks` take precedence in every place (v1.142); otherwise v1.101, per place: NPC conversations for a player whose trusted server identity has `under13 === true` offer three canned lines and hide the text field. Both authored and model admission paths reject other words. Missing age stamp defaults false. Absent key preserves existing UI and protocol bytes; no client age inference. |
@@ -5476,6 +5476,7 @@ a deck written before them remains valid.
5476
5476
  | 2026-11-18 (v1.222) | Writer leases (server-only, no wire or manifest change): a fresh connection whose account has no connected visit here forgets that account's retained visits whether or not it is lost, and a visit back to a held claim (retained visits, or the 60 s end-save window) revalidates it; a claim another instance took meanwhile is replaced silently instead of losing the fresh visit. `hub.saves.deck`/`user` views are bound to the claim current when made, so a superseded visit's queued writes reject with `CAULDRON_STORAGE_WRITER_LOST`. `resumePose` takes, ends and clears its durable pose through the lease view, so a fenced instance no longer moves the pose revision. No deck opts in yet. |
5477
5477
  | 2026-11-18 (v1.223) | Writer leases (server-only, no wire or manifest change): a lone visit back that arrives while an earlier visit's revalidation is still out checks the claim again once that round settles (on whichever claim it settled), so a check from before another instance's takeover never lets the return proceed only to lose its first save. `resumePose` takes its snapshot through the lease view too, so it reads only once the claim settles and keeps a pose the previous writer saved just before; its 5 s read budget starts once the claim has settled. An older pending round that resumes on a replacement claim a newer arrival is already checking waits for that round and keeps the claim it found; it never inherits a claim that round reopens. A take holds its queue place at once, so an end asked while it waits for the claim runs after it. Without `writerLease` nothing changes. No deck opts in yet. |
5478
5478
  | 2026-11-18 (v1.224) | Writer leases (server-only): `await hub.saves.holds(view)` tells whether the claim a save view writes through is still active and has not been lost, after pending claim checks settle. Unrecognized views and lease-off stores answer true. No manifest or wire change. |
5479
+ | 2026-11-19 (v1.230) | §1 `resumeWindowSec` may stand beside `resumePose` (still refused beside `result`, `houseResume` and `resumeArrivalPose`): the pinned window holds the same visit and pose, and `resumePose`'s stored pose then places a new id for the same account up to ten minutes after departure, as the Town's places already do ("Door resume window"). Manifest validation only; no runtime or wire change. |
5479
5480
  | 2026-11-18 (v1.226) | Writer leases (server-only, no manifest or wire change): every `set`/`remove`/`increment` through a `hub.saves` view carries the platform writer check of the claim it is bound to, so a stale write is refused atomically instead of after a separate fence (the write-after-fence window is closed for ordinary writes where the platform checks). A refusal loses the claim and is never retried. Where a checked write answers `CAULDRON_STORAGE_UNAVAILABLE` (`castle-web serve`, persistent-world sessions; the details may sit under `extensions`) the session fences and writes unchecked as before; view `transaction`/`conditionalWrite` and root atomic calls keep their fence. Every lone arrival now claims anew and the place reloads (no revalidation of a held claim): queued writes of the previous visit go first for up to 5 s; claims are sent or retried only while a connected visit is here, and a resume picks a waiting claim up again. `holds(view)` also waits for the account's current claim. Without `writerLease` nothing changes. No deck opts in yet. |
5480
5481
  | 2026-11-18 (v1.228) | Writer leases (server-only, no manifest or wire change): `hub.saves.bind(store, view)` returns another store of the account (a `session.storage.playthrough` handle) bound to the claim `view` is bound to: `set`/`remove` carry that claim's writer check and run in account order, reads wait for that claim. The raw store when `view` is not a lease view or the lease is off. The Town conversation saves through it. No deck opts in yet. |
5481
5482
  | 2026-11-18 (v1.227) | Writer leases (server-only, no manifest or wire change): a `hub.saves` view `transaction` goes as one root transaction carrying the claim's writer check, so a superseded claim's bucket transaction is refused atomically (no fence; the receipt is unchanged). `hub.saves.onDrain(fn)` runs `fn(userId)` before a lone return waits for the previous visit's writes, so a place hands its own held writes for the account to their views first (within the same 5 s); a view's reads wait only for its own claim. Claims are compare-and-set on the lease revision read just before (`expectedRevision`, inert until the SDK carries it): a late claim after another instance's is refused, and looked again only for a connected visit. `resumePose` (lease on or off) sends a take's clear again under the same operation after a lost answer (for up to 30 s), and keeps the revision for the end save even when it arrives after the read budget. Without `writerLease` nothing changes, except that resumePose retry. No deck opts in yet. |
@@ -5688,8 +5689,11 @@ pinned retention (the Town's path) keeps the same visit, body and pose: no
5688
5689
  the host refuses the token and the next join is a fresh arrival.
5689
5690
 
5690
5691
  The Town keeps its own 180 s whatever it declares; owner houses keep
5691
- `houseResume`'s. The key cannot combine with `result`, `resumePose`,
5692
- `houseResume` or `resumeArrivalPose`. Absent, on an older Ghost, or on a host
5692
+ `houseResume`'s. The key cannot combine with `result`, `houseResume` or
5693
+ `resumeArrivalPose`. Since v1.230 it may stand beside `resumePose`, as the
5694
+ Town's places do: the pinned window holds the same visit and pose, and once it
5695
+ has passed `resumePose`'s stored pose still places a new id for the same
5696
+ account (up to ten minutes after departure). Absent, on an older Ghost, or on a host
5693
5697
  without grace, nothing is pinned and a drop ends the visit exactly as before.
5694
5698
 
5695
5699
  ### v1.115: owner-house reconnect retention
@@ -138,10 +138,15 @@ test('resume window is a bounded door opt-in and absent manifests stay unchanged
138
138
  for (const resumeWindowSec of [0, 181, 30.5, -1, '30', true, null, {}]) {
139
139
  assert(readManifest(base({ resumeWindowSec }), has).errors.length, String(resumeWindowSec));
140
140
  }
141
- for (const keys of [{ result: {} }, { resumePose: true }, { houseResume: true }, { resumeArrivalPose: true }]) {
141
+ for (const keys of [{ result: {} }, { houseResume: true }, { resumeArrivalPose: true }]) {
142
142
  const read = readManifest(base({ ...keys, resumeWindowSec: 60 }), has);
143
143
  assert(read.errors.some((e) => e.includes('resumeWindowSec')), JSON.stringify(keys));
144
144
  }
145
+ // v1.230: beside resumePose, as the Town has both.
146
+ const both = readManifest(base({ resumePose: true, resumeWindowSec: 180 }), has);
147
+ assert.deepEqual(both.errors, []);
148
+ assert.equal(both.manifest.places.main.resumeWindowSec, 180);
149
+ assert.equal(both.manifest.places.main.resumePose, true);
145
150
  });
146
151
 
147
152
  test("the kit's own manifest is valid", () => {
@@ -61,5 +61,5 @@
61
61
  "autoUpdateWhenImported": true,
62
62
  "deckId": "JH0SclbPVP0y",
63
63
  "cardId": "eXfAaUdbSU5A",
64
- "publishedVersion": "2026-11-18T00:50:50.040Z"
64
+ "publishedVersion": "2026-11-19T09:37:22.766Z"
65
65
  }
@@ -74,3 +74,22 @@ with +/-3 mm offsets, and slide along a 0.5 m barrier at 15 degrees. Curb
74
74
  crossings at 2, 8, and 15 cm keep exactly the same trajectories with the key
75
75
  off and on. Projection alone passes these checks with Rapier's existing
76
76
  average friction combine rule.
77
+
78
+ ## Squeezed between two solids
79
+
80
+ Without any key, a walking Player (a dynamic body with a `Player`) that
81
+ two fixed solids press from opposite sides is let go of friction. Rapier
82
+ averages the Player's friction 0 with a solid's (0.6 by default), and in a
83
+ gap narrower than the capsule that closes in a V shallower than that
84
+ friction's angle (16.7 degrees) the squeeze that would push the capsule out
85
+ also holds it: walking, backing out and jumping all move under 1 mm. The
86
+ Town's Garden counter beside a pond rim made one, and a restored pose put
87
+ the player back in it on every arrival. So before each fixed step
88
+ `systems/physics3d.js` (`unwedge`) reads the capsule's contacts: while two
89
+ near-vertical fixed faces within 5 mm of it have opposing normals (dot
90
+ below -0.5), its friction combine rule is Min (0 against anything), and
91
+ once free it is Average again. One wall, a square corner, floors and
92
+ slopes keep the average rule, so those walks are unchanged.
93
+ `npm run test:wall-slide` places the player in that V, 1.5 to 2 cm into
94
+ both solids, and requires it to walk over 1 m out of it and to jump over
95
+ 1 m, with the hover as an impulse and as a force.
@@ -38,9 +38,9 @@ const wall = (id, x, z, width, depth, type = 'fixed', solid = true) => ({
38
38
  },
39
39
  });
40
40
 
41
- async function makeWorld({ enabled, walls = [], angle = 15, orbit = false, x = -RADIUS - 0.002, z = 0, PlayerClass = Player } = {}) {
41
+ async function makeWorld({ enabled, walls = [], angle = 15, orbit = false, x = -RADIUS - 0.002, y = 1, z = 0, steady = false, settle = 180, PlayerClass = Player } = {}) {
42
42
  const actor = { id: 'player', runtime: {}, components: {
43
- Transform: transform(x, 1, z), Shape: { kind: 'capsule', radius: RADIUS, height: 1.4 },
43
+ Transform: transform(x, y, z), Shape: { kind: 'capsule', radius: RADIUS, height: 1.4 },
44
44
  Body: { type: 'dynamic', lockRotations: true, friction: 0, restitution: 0, gravityScale: 2 }, Solid: {}, Player: { ...props },
45
45
  } };
46
46
  const system = new Physics3DSystem();
@@ -48,7 +48,7 @@ async function makeWorld({ enabled, walls = [], angle = 15, orbit = false, x = -
48
48
  time: 0, keys: new Set(), persistent: { camAngle: (90 + angle) * Math.PI / 180 },
49
49
  data: { engine: { player: { ...(enabled === undefined ? {} : { slideOnWalls: enabled }) } } },
50
50
  actors: [actor, ...walls], maxFps: 0, three: null,
51
- cameraControl: orbit ? 'orbit' : undefined,
51
+ cameraControl: orbit ? 'orbit' : undefined, cameraFollowsRigidly: steady || undefined,
52
52
  getActors: () => scene.actors, getActor: (id) => scene.actors.find((a) => a.id === id),
53
53
  actorsWith: () => [], forEachBehavior: () => {},
54
54
  };
@@ -72,7 +72,7 @@ async function makeWorld({ enabled, walls = [], angle = 15, orbit = false, x = -
72
72
  system.afterBehaviors(scene, DT);
73
73
  }
74
74
  assert.ok(api.ready(), 'real Rapier initialized');
75
- for (let i = 0; i < 180; i += 1) frame();
75
+ for (let i = 0; i < settle; i += 1) frame();
76
76
  calls.length = 0;
77
77
  return { actor, scene, system, calls, frame, close: () => system.dispose(scene) };
78
78
  }
@@ -269,4 +269,74 @@ const mirrorSeam = await walk({ enabled: true, angle: 5, walls: joinedWalls(3, -
269
269
  assert.deepEqual(mirrorSeam.samples, seams.at(-1).result.samples, 'play mirror crosses offset seams identically');
270
270
  const mirrorBarrier = await walk({ enabled: true, walls: barrier(0.5), PlayerClass: PlayPlayer });
271
271
  assert.deepEqual(mirrorBarrier.samples, lowOn.samples, 'play mirror slides along low barriers identically');
272
- console.log('wall-slide: all checks passed (real Rapier; friction combine rule unchanged)');
272
+ // A V-shaped gap narrower than the capsule between two fixed solids (the
273
+ // Town's Garden counter beside a pond rim, whose faces meet at about 15
274
+ // degrees) must not hold a player still for good. Placed where a restored
275
+ // pose put one, 1.5-2 cm into both, the average friction combine rule
276
+ // (0.3 against the default 0.6) locked the wedge: walking, backing out
277
+ // and jumping all moved under 1 mm. The key is off, as in the Town.
278
+ const wedge = () => {
279
+ const counter = wall('counter', 54.7, 0, 1.8, 0.7);
280
+ Object.assign(counter.components.Transform, { y: 0.45, rotationY: 90 });
281
+ Object.assign(counter.components.Shape, { height: 0.9 });
282
+ const pond = wall('pond', 58.7, 0, 0, 0);
283
+ pond.components.Transform.y = 0.3;
284
+ pond.components.Shape = { kind: 'cylinder', radius: 3.1, height: 0.6 };
285
+ return [counter, pond];
286
+ };
287
+ for (const steady of [false, true]) for (const jump of [false, true]) {
288
+ // angle -90: the camera yaw is 0, so W walks -z, out of the wedge's mouth.
289
+ const w = await makeWorld({ walls: wedge(), angle: -90, x: 55.3854, y: 0.741, z: -0.8859, steady, settle: 1, PlayerClass: PlayPlayer });
290
+ try {
291
+ const start = w.frame();
292
+ const samples = [];
293
+ for (let i = 0; i < 36; i += 1) samples.push(w.frame(!jump, jump && i === 0));
294
+ const end = samples.at(-1);
295
+ const moved = Math.hypot(end.x - start.x, end.z - start.z);
296
+ const rose = Math.max(...samples.map((p) => p.y)) - start.y;
297
+ console.log(`wedge (steady ${steady}, ${jump ? 'jump' : 'walk'}): moved ${moved.toFixed(4)} m, rose ${rose.toFixed(4)} m`);
298
+ if (jump) assert.ok(rose > 1, 'a wedged player still jumps');
299
+ else assert.ok(moved > 1, 'a wedged player walks out of the wedge');
300
+ } finally { w.close(); }
301
+ }
302
+ // The Player component can come and go on a body that is kept (the body
303
+ // signatures leave it out): the squeeze is looked after while it is there,
304
+ // and the average rule is back once it is gone.
305
+ {
306
+ const RAPIER = await import('../engine3d/rapier.js');
307
+ const { Min, Average } = RAPIER.CoefficientCombineRule;
308
+ const wedged = () => makeWorld({ walls: wedge(), angle: -90, x: 55.3854, y: 0.741, z: -0.8859, settle: 0, PlayerClass: PlayPlayer });
309
+ // A Player added to a kept dynamic body: held without it, let go with it.
310
+ let w = await wedged();
311
+ try {
312
+ const props = w.actor.components.Player;
313
+ delete w.actor.components.Player;
314
+ const entry = () => w.system.bodies.get('player');
315
+ const from = w.frame();
316
+ const body = entry().body;
317
+ let at = from;
318
+ for (let i = 0; i < 36; i += 1) at = w.frame(true);
319
+ assert.ok(Math.hypot(at.x - from.x, at.z - from.z) < 0.01, 'a body without a Player stays held, as before');
320
+ assert.equal(entry().collider.frictionCombineRule(), Average, 'and keeps the average rule');
321
+ w.actor.components.Player = props;
322
+ for (let i = 0; i < 36; i += 1) at = w.frame(true);
323
+ assert.equal(entry().body, body, 'the body is kept when the Player comes');
324
+ assert.ok(Math.hypot(at.x - from.x, at.z - from.z) > 1, 'a Player added to a kept body walks out of the wedge');
325
+ } finally { w.close(); }
326
+ // The Player taken off a kept body while it is squeezed: the average rule is back.
327
+ w = await wedged();
328
+ try {
329
+ const entry = () => w.system.bodies.get('player');
330
+ w.frame();
331
+ w.frame();
332
+ const body = entry().body;
333
+ assert.equal(entry().collider.frictionCombineRule(), Min, 'a squeezed Player is let go of friction');
334
+ delete w.actor.components.Player;
335
+ w.frame();
336
+ assert.equal(entry().body, body, 'the body is kept when the Player goes');
337
+ assert.equal(entry().collider.frictionCombineRule(), Average, 'without a Player the average rule is back');
338
+ assert.ok(!entry().walker && !entry().unwedged, 'and the squeeze is no longer looked after');
339
+ } finally { w.close(); }
340
+ console.log('wedge: the Player component added to and taken off a kept body is followed');
341
+ }
342
+ console.log('wall-slide: all checks passed (real Rapier; average friction combine rule unless squeezed)');
@@ -242,7 +242,10 @@ export class Physics3DSystem {
242
242
  seen.add(actor.id);
243
243
  const sig = bodySignature(actor);
244
244
  const existing = this.bodies.get(actor.id);
245
- if (existing && existing.sig === sig) continue;
245
+ if (existing && existing.sig === sig) {
246
+ markWalker(existing, actor);
247
+ continue;
248
+ }
246
249
  if (existing) this.removeBody(actor.id);
247
250
  this.createBody(actor, sig);
248
251
  }
@@ -261,7 +264,9 @@ export class Physics3DSystem {
261
264
  collider = this.world.createCollider(colliderDescFor(actor, shape), body);
262
265
  this.byCollider.set(collider.handle, actor.id);
263
266
  }
264
- this.bodies.set(actor.id, { body, collider, sig, pushedKey: transformKey(t) });
267
+ const entry = { body, collider, sig, pushedKey: transformKey(t) };
268
+ markWalker(entry, actor);
269
+ this.bodies.set(actor.id, entry);
265
270
  }
266
271
 
267
272
  removeBody(actorId) {
@@ -341,6 +346,7 @@ export class Physics3DSystem {
341
346
  // only on step frames and stutter on displays faster than 60Hz.
342
347
  for (const entry of this.frozenPhysics ? this.frozenPhysics.stepEntries() : this.bodies.values()) {
343
348
  if (entry.body.bodyType() !== RAPIER.RigidBodyType.Dynamic) continue;
349
+ if (entry.walker) unwedge(this.world, entry);
344
350
  const p = entry.body.translation();
345
351
  const q = entry.body.rotation();
346
352
  entry.prev = { x: p.x, y: p.y, z: p.z, qx: q.x, qy: q.y, qz: q.z, qw: q.w };
@@ -622,13 +628,17 @@ export class Physics3DSystem {
622
628
  bodyFor(actor) {
623
629
  let entry = this.bodies.get(actor.id);
624
630
  const made = entry && this.remembered.get(entry);
625
- if (made && madeTheSame(made.madeFrom, actor)) return entry;
631
+ if (made && madeTheSame(made.madeFrom, actor)) {
632
+ markWalker(entry, actor);
633
+ return entry;
634
+ }
626
635
  const sig = bodySignature(actor);
627
636
  if (!entry || entry.sig !== sig) {
628
637
  if (entry) this.removeBody(actor.id);
629
638
  this.createBody(actor, sig);
630
639
  entry = this.bodies.get(actor.id);
631
640
  }
641
+ markWalker(entry, actor);
632
642
  this.remembered.set(entry, { madeFrom: rememberMaking(actor), pushedAt: null });
633
643
  return entry;
634
644
  }
@@ -786,6 +796,63 @@ function setEulerFromQuat(t, q) {
786
796
  t.rotationZ = tmpEuler.z / DEG;
787
797
  }
788
798
 
799
+ // A walking Player pressed between two fixed solids from opposite sides (a
800
+ // gap narrower than its capsule that closes in a shallow V, as the Town's
801
+ // Garden counter beside a pond rim does) is held by friction for good: the
802
+ // Player's friction is 0, but rapier averages it with the solid's (0.6 by
803
+ // default), and in a V shallower than the friction angle (0.3: 16.7 degrees)
804
+ // the squeeze that pushes it out also holds it, against walking, backing out
805
+ // and a jump alike. A restored pose puts it back there on every arrival.
806
+ // So while its contacts include two near-vertical fixed faces within
807
+ // SQUEEZE_SKIN whose normals oppose (dot below SQUEEZE_DOT), its friction is
808
+ // combined by the least (0 against anything) and the squeeze pushes it out;
809
+ // once free, the average rule returns. A player against one wall, or in a
810
+ // square corner, keeps the average rule: those walks are unchanged.
811
+ const SQUEEZE_SKIN = 0.005;
812
+ // Whether `step` looks after the entry's squeeze: a dynamic body with a
813
+ // collider whose actor has a Player. The body signatures leave Player out,
814
+ // so every pass that keeps a body asks again; an actor that stops being a
815
+ // walker gets the average rule back.
816
+ function markWalker(entry, actor) {
817
+ const walker = Boolean(actor.components.Player) && Boolean(entry.collider) &&
818
+ entry.body.bodyType() === RAPIER.RigidBodyType.Dynamic;
819
+ if (walker === Boolean(entry.walker)) return;
820
+ entry.walker = walker;
821
+ if (!walker && entry.unwedged) {
822
+ entry.unwedged = false;
823
+ entry.collider.setFrictionCombineRule?.(RAPIER.CoefficientCombineRule.Average);
824
+ }
825
+ }
826
+ const SQUEEZE_DOT = -0.5;
827
+ function unwedge(world, entry) {
828
+ const collider = entry.collider;
829
+ // A stand-in world without contact queries (tests' fakes) has no squeeze.
830
+ if (typeof world.contactPairsWith !== 'function' || typeof collider.setFrictionCombineRule !== 'function') return;
831
+ const faces = [];
832
+ world.contactPairsWith(collider, (other) => {
833
+ if (other.isSensor() || other.parent()?.bodyType() !== RAPIER.RigidBodyType.Fixed) return;
834
+ world.contactPair(collider, other, (manifold, flipped) => {
835
+ let nearest = Infinity;
836
+ for (let k = 0; k < manifold.numContacts(); k += 1) nearest = Math.min(nearest, manifold.contactDist(k));
837
+ if (!(nearest <= SQUEEZE_SKIN)) return;
838
+ const n = manifold.normal();
839
+ const across = Math.hypot(n.x, n.z);
840
+ if (across < 0.7) return;
841
+ const sign = flipped ? -1 : 1;
842
+ faces.push({ x: (sign * n.x) / across, z: (sign * n.z) / across });
843
+ });
844
+ });
845
+ let squeezed = false;
846
+ for (let i = 0; i < faces.length && !squeezed; i += 1) {
847
+ for (let j = i + 1; j < faces.length; j += 1) {
848
+ if (faces[i].x * faces[j].x + faces[i].z * faces[j].z < SQUEEZE_DOT) { squeezed = true; break; }
849
+ }
850
+ }
851
+ if (squeezed === Boolean(entry.unwedged)) return;
852
+ entry.unwedged = squeezed;
853
+ collider.setFrictionCombineRule(squeezed ? RAPIER.CoefficientCombineRule.Min : RAPIER.CoefficientCombineRule.Average);
854
+ }
855
+
789
856
  // rapier's query filter for `castRayFixed`: fixed bodies' solid colliders only.
790
857
  function fixedSolids() {
791
858
  const flags = RAPIER.QueryFilterFlags;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.250",
3
+ "version": "0.4.251",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"