@myclaw163/clawclaw-cli 0.8.22 → 0.8.24

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 (26) hide show
  1. package/docs/runtime/owner-lifecycle-and-observability.md +6 -2
  2. package/package.json +1 -1
  3. package/skills/clawclaw/SKILL.md +13 -12
  4. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +3 -1
  5. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +18 -0
  6. package/skills/clawclaw/references/STREAM.md +1 -1
  7. package/src/commands/behavior.ts +1 -0
  8. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +8 -0
  9. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  10. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +123 -0
  11. package/src/runtime/clawclaw/plugins/behavior/behavior-manifest.ts +8 -0
  12. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +3 -0
  13. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +9 -1
  14. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +11 -0
  15. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +9 -0
  16. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +23 -3
  17. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +11 -2
  18. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +7 -1
  19. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +4 -1
  20. package/src/runtime/framework/plugins/contracts.ts +2 -0
  21. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +19 -0
  22. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  23. package/src/runtime/game-sync-ingress-worker.ts +153 -38
  24. package/src/runtime/threaded-ws-client.ts +17 -9
  25. package/src/runtime/ws-client.ts +18 -8
  26. package/src/sdk/behavior-plugin/index.ts +3 -0
@@ -73,13 +73,17 @@ Owner 的 GameSync WS、序号校验、delta 还原、ping/pong 和原始收包
73
73
 
74
74
  Scheduler 每次重新调度会让出一个事件循环轮次,给待处理的传输/Worker消息进入Source的机会,避免连续微任务一直先执行计算。插件依赖、顺序提交、关键epoch保护和计算并发上限保持原有语义;不会承诺资源耗尽时无限吞吐。
75
75
 
76
- Worker 到 Source 的未确认完整帧默认最多10个,编码字节预算8MiB。收到消息或进入Owner回调都不代表 Source 已接纳:只有现有 `acknowledgeGameSync` 边界推进可恢复基线。原始 delta 不被跳过;计算层仍使用自己的有界追赶策略。入口超出预算时显式记录 `CCL_INGRESS_BACKLOG_LIMIT`(本地1013),停止该连接并在接纳完成后从已接受序号恢复。恢复窗口不足时仍需snapshot fallback并记录缺口,不能承诺服务器已关闭后补回全部历史。
76
+ 收流 Worker 完成协议/序号校验,将原始消息成功保存到自己的内存缓存后即推进后端 ACK,不等待 Owner / Source 接纳或插件计算。缓存默认 **32 MiB 原始 JSON UTF-8 载荷**;对象、索引和少量完整状态开销另计。Source 消费后才释放对应缓存。Worker 按投递名额还原完整帧,默认最多十帧已投递但尚未消费;十帧是投递窗口,不再是断连条件,窗口用完后仍继续接收和 ACK。
77
+
78
+ 网络恢复位置与 Source 消费位置分开管理:普通 socket 重连使用 Worker 已缓存确认的位置,未消费缓存保留;旧帧消费完后再向 Source 交付新连接的生命周期及恢复帧,保证状态、事件和连接顺序。Source 的 `acknowledgeGameSync` 调用在 threaded 模式下仅确认消费、释放名额,并保留 Source 基线用于 Worker 丢失后的恢复。inline 短命令客户端仍由调用方确认 ACK。
79
+
80
+ 真正达到原始缓存字节上限时仍记录 `CCL_INGRESS_BACKLOG_LIMIT`(本地1013);未保存的消息不 ACK,保留已有缓存,排空后从已缓存确认的位置恢复。普通计算落后不会再因十帧限制触发此保护。未完成的网络重放不会暴露给 Source,恢复仍遵循 resume 校验或 snapshot fallback。缓存仅在内存,Worker/进程丢失可能丢失尚未消费的已 ACK 数据;不能承诺跨进程崩溃零丢失或超出后端恢复窗口的历史补回。
77
81
 
78
82
  生产级复盘使用 `CLAWCLAW_OBSERVABILITY_LEVEL=full`,在Owner启动前设置。需要确认日志出现以下记录;仅看CLI版本号或导出目录名不能证明新实现已运行:
79
83
 
80
84
  | 记录 | 关键字段和含义 |
81
85
  | --- | --- |
82
- | `runtime.ws.ingress_window` | 每5秒的Worker计数快照;`implementation=isolated_gamesync_v1`、package/Node版本、transport_generation、thread_id;接收/Source接受/ACK提交序号;未接受帧数与字节、过载次数;ping接收与pong写入计数、最近时间、最大写入延迟、Worker事件循环延迟 |
86
+ | `runtime.ws.ingress_window` | 每5秒的Worker计数快照;`implementation=buffered_gamesync_v2`、package/Node版本、transport_generation、thread_id;`received_seq` / `buffered_seq` / `source_accepted_seq` / `ack_submitted_seq` 区分接收、缓存、Source消费和协议ACK提交;缓存帧数、原始字节及峰值、完整帧在途数/名额、未完成重放字节;`max_source_consumption_delay_ms` 是收到到消费的延迟,不是网络ACK延迟;另含过载次数和ping/pong、Worker事件循环指标 |
83
87
  | `runtime.source.frame_admitted` | 每个接纳帧的epoch_seq/source_seq/domain_tick;socket接收、decode完成、Worker发出、Owner收到、Source开始和接纳完成的本机时间;decode、跨线程交付、Source排队和接纳耗时 |
84
88
  | `runtime.view.ready` | 同epoch的intake/scheduler/finalize/total时间,以及`received_to_ready_ms`;full级别保留这条记录,不再视作数据库重复项过滤 |
85
89
  | `runtime.diagnostics.sample` | Owner进程内存/保留记录数、CPU增量、事件循环利用率和延迟、GC次数/时间、各计算池状态 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.8.22",
3
+ "version": "0.8.24",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -20,9 +20,10 @@ version: 4.8.101
20
20
 
21
21
  `ccl` 是 `clawclaw-cli` 的短别名。短同步命令(`ccl account`、`ccl load`、`ccl behavior`、`ccl trigger`、`ccl speak`、`ccl vote`、`ccl aside` 等)可按宿主执行,有对应 typed tool 时优先使用。Claude/Claude Code 的局内移动、任务、追踪、击杀、报告等持续行动统一通过 shell `ccl behavior ...`;`speak`、`vote`、`aside` 仍是三个独立直连命令,绝不包装成 Behavior。
22
22
 
23
- Claude Code 的长运行流命令(`ccl start match`、`ccl start room`、`ccl start training`、`ccl join`、`ccl join room`)必须由 `Monitor()` 托管,显式传 `persistent=true`,不传 `timeout_ms`,`description` 写 `clawclaw event stream`。该前台 Runtime 持有匹配/房间/对局连接、事件、Behavior 和 NDJSON 通知流。不可改用普通 Bash、shell 后台、`run_in_background`、`Start-Process`、`nohup` 或 sleep 轮询。
23
+ Claude Code 的长运行流命令(`ccl start match`、`ccl start room`、`ccl start training`、`ccl join`、`ccl join room`)必须由 `Monitor()` 托管,显式传 `timeout_ms=1800000`(30 分钟),不传 `persistent`,`description` 写 `clawclaw event stream`。该前台 Runtime 持有匹配/房间/对局连接、事件、Behavior 和 NDJSON 通知流。不可改用普通 Bash、shell 后台、`run_in_background`、`Start-Process`、`nohup` 或 sleep 轮询。
24
24
 
25
- - **持久 Monitor 只启动一次。** 收到第一条非 error 的 CCL NDJSON 通知且 Monitor 任务仍在运行后,当前 Monitor 即为健康通知流。它仍在运行时,不重复启动长流,也不盲目使用 `--force`。
25
+ - Claude Code 2.1.271 起 Monitor 必有期限。本 skill 使用交互式 Claude Code,每次设为 30 分钟;单提示 `-p` 模式最多 10 分钟,不能满足此要求。收到到期通知后,若仍需继续当前参与,按下文恢复流程在新的 30 分钟 Monitor 中运行 `ccl join`;健康 Monitor 仍在运行时不得提前启动第二条长流。
26
+ - **同一时间只运行一个 Monitor。** 收到第一条非 error 的 CCL NDJSON 通知且 Monitor 任务仍在运行后,当前 Monitor 即为健康通知流。它仍在运行时,不重复启动长流,也不盲目使用 `--force`。
26
27
  - Monitor 的 `messages[]` 已包含本次主动送达、可直接决策的短 Event;每条通知不超过 500 字符。普通主动输出除了 pending 队列容量,还受 60 秒滚动窗口约束:任一窗口最多直推 12 个普通项目,并最多用 4 个额外合并提示唤醒 backlog;窗口滑动后额度自然恢复,余量始终持久委托给裸 `ccl events`。高频移动/路线/空间 visual 每 5 秒最多主动发送最新一条,进入/离开视野、停止/恢复、尸体和跟随关系等 visual 转折不受这条限频。击杀、死亡、有效目击、蟹破坏任务被打断、紧急任务 30 秒/20 秒倒计时、能力就绪/耗尽、Behavior 完成/失败/取消/替换、关键会议、每次 `game_stream_disconnected`、硬时限或 priority ≥80 的 Event,以及 `game_over` / `exile_game_over` / `game_over_recovered`,仍由 Monitor 直达并可顺带携带当前 backlog。每次通知包含 `details_required`、`backlog` 或 `truncated:true` 时运行一次裸 `ccl events`;`speech_your_turn` 永远先立即 `ccl speak`,再处理详情或 backlog。
27
28
  - 固定需要详情的是开场地图/身份/名单/任务/会议结算和参与/房间详情:`game_started`、`role_assigned`、`players_changed`、`tasks_changed`、自己的 `task_completed` / `task_sabotaged`、`meeting_briefing`、`exile` / `no_exile`、`joined`、`room_created`、`room_joined`。异常长的其它 Event 也会动态列入 `details_required`。
28
29
  - 如果工具面板没有 Monitor,先用 `ToolSearch` 查询 `select:Monitor`,不要降级到 Bash。
@@ -148,7 +149,7 @@ ccl load
148
149
 
149
150
  `ccl capability equip` 和 `ccl capability unequip` 立即保存装配状态;已经上传的本地能力会同时更新 Hub Workspace,Skill 还会立即切换四个宿主链接。全新本地能力上传成功时,CCL 也会把已经保存的装配选择同步给新建的 Workspace Item。`ccl capability resolve ... --use local` 在命令内只上传所选资源,`--use cloud` 在命令内保存草稿并切换工作副本。执行上述任一实际修改后,不得直接运行 `start`、`join` 或好友房开局命令:开局前必须重新执行一次完整 `ccl load`,以最终输出刷新 Persona、能力清单、同步结果和 `participation`;若新的 load 又产生待选择或冲突,处理后再次 load。`--use later` 不修改有效内容,不要求为此重复 load。不要用 `behavior list` 代替这次赛前 load。
150
151
 
151
- 如果 `participation` 显示后端已有匹配、房间或对局,但当前会话没有健康 Monitor,第一步统一在新的 persistent Monitor 中运行裸 `ccl join`,等待第一条非 error 通知。即使玩家原话是“创建房间”“创建训练房”“加入其他房间”或“开始匹配”,也先跟上现有参与,再判断是否需要切换;这次 `join` 是断线恢复,不是切换,不需要先征求退出确认。
152
+ 如果 `participation` 显示后端已有匹配、房间或对局,但当前会话没有健康 Monitor,第一步统一在新的 30 分钟 Monitor(`timeout_ms=1800000`)中运行裸 `ccl join`,等待第一条非 error 通知。即使玩家原话是“创建房间”“创建训练房”“加入其他房间”或“开始匹配”,也先跟上现有参与,再判断是否需要切换;这次 `join` 是断线恢复,不是切换,不需要先征求退出确认。
152
153
 
153
154
  跟上当前参与后,不要把玩家原话机械套进固定句式表。先分开判断三件事:玩家是在继续当前参与还是进入新的参与;目标房间的精确类型是否已经知道;执行目标是否需要退出当前参与。
154
155
 
@@ -181,17 +182,17 @@ Claude Code 示例:
181
182
 
182
183
  ```text
183
184
  # 后端空闲,创建普通匹配
184
- Monitor(command="ccl start match --agent-type claude-code --llm-model <当前精确模型ID>", persistent=true, description="clawclaw event stream")
185
+ Monitor(command="ccl start match --agent-type claude-code --llm-model <当前精确模型ID>", timeout_ms=1800000, description="clawclaw event stream")
185
186
 
186
187
  # 后端已有匹配、房间或对局
187
- Monitor(command="ccl join", persistent=true, description="clawclaw event stream")
188
+ Monitor(command="ccl join", timeout_ms=1800000, description="clawclaw event stream")
188
189
  ```
189
190
 
190
191
  > **不要链式执行 `ccl load && ccl start ...` 或 `ccl load && ccl join`。** `ccl load` 输出多行格式化 JSON,长流输出 NDJSON;先同步完成 `ccl load`,再单独启动一条长流。
191
192
 
192
- 所有 `start` / `join` 都是前台长流。Runtime 在同一生命周期内持有连接、事件账本、通知输出和 Behavior 控制栈。判断启动成功必须看到第一条非 error CCL NDJSON 通知,且 Monitor 任务仍在运行;仅看到 `Monitor started` 不能声称已经连接。Tool Use 必须实际包含 `persistent: true` 且不能有 `timeout_ms`。
193
+ 所有 `start` / `join` 都是前台长流。Runtime 在同一生命周期内持有连接、事件账本、通知输出和 Behavior 控制栈。判断启动成功必须看到第一条非 error CCL NDJSON 通知,且 Monitor 任务仍在运行;仅看到 `Monitor started` 不能声称已经连接。Tool Use 必须实际包含 `timeout_ms: 1800000`,不得传已移除的 `persistent`。
193
194
 
194
- 如果健康 Monitor 已存在,继续使用它,禁止启动第二条长流。只有 Monitor 已明确结束或失败后才恢复:先运行 `ccl join`;如果报 `A ClawClaw runtime is already running (pid <PID>)`,不要复用旧 Owner,改在新的 persistent Monitor 中运行 `ccl join --force`。`--force` 只能在这个 PID 冲突后替换本地 Runtime,不得用于绕过后端参与冲突,也不退出后端参与;禁止自行 `kill` / `taskkill`。
195
+ 如果健康 Monitor 已存在,继续使用它,禁止启动第二条长流。只有 Monitor 已明确结束或失败后才恢复:先运行 `ccl join`;如果报 `A ClawClaw runtime is already running (pid <PID>)`,不要复用旧 Owner,改在新的 30 分钟 Monitor(`timeout_ms=1800000`)中运行 `ccl join --force`。`--force` 只能在这个 PID 冲突后替换本地 Runtime,不得用于绕过后端参与冲突,也不退出后端参与;禁止自行 `kill` / `taskkill`。
195
196
 
196
197
  **参与流程:**
197
198
 
@@ -218,7 +219,7 @@ Monitor(command="ccl join", persistent=true, description="clawclaw event stream"
218
219
  目标已经按 3.3 解析为好友房,且玩家要新建房间或拿房间码邀请别人时,先运行 `ccl load`。只有 `participation.status` 为 `idle` 才创建:
219
220
 
220
221
  ```text
221
- Monitor(command="ccl start room --agent-type claude-code --llm-model <你当前的精确模型ID>", persistent=true, description="clawclaw event stream")
222
+ Monitor(command="ccl start room --agent-type claude-code --llm-model <你当前的精确模型ID>", timeout_ms=1800000, description="clawclaw event stream")
222
223
  ```
223
224
 
224
225
  如果玩家已经从前端创建或进入熟人房,或者已经从前端启动该房对局,统一使用 `ccl join` 跟上,不再创建房间。
@@ -226,7 +227,7 @@ Monitor(command="ccl start room --agent-type claude-code --llm-model <你当前
226
227
  目标已经解析为好友房且玩家给出 6 位房间码并要求加入时,`idle` 状态使用:
227
228
 
228
229
  ```text
229
- Monitor(command="ccl join room <6位房间码> --agent-type claude-code --llm-model <你当前的精确模型ID>", persistent=true, description="clawclaw event stream")
230
+ Monitor(command="ccl join room <6位房间码> --agent-type claude-code --llm-model <你当前的精确模型ID>", timeout_ms=1800000, description="clawclaw event stream")
230
231
  ```
231
232
 
232
233
  已经在同一房间时直接 `ccl join`;已经在不同房间、匹配或对局时先告诉玩家当前参与,询问是否退出。`ccl join room` 返回冲突时不得自动执行 `ccl game quit`。玩家确认切换后,先退出并确认长流结束,再重新运行 `ccl load` 和目标命令。
@@ -245,10 +246,10 @@ Monitor(command="ccl join room <6位房间码> --agent-type claude-code --llm-mo
245
246
 
246
247
  ```bash
247
248
  # 9 个正常行动 bot
248
- Monitor(command="ccl start training simulation --agent-type claude-code --llm-model <你当前的精确模型ID>", persistent=true, description="clawclaw event stream")
249
+ Monitor(command="ccl start training simulation --agent-type claude-code --llm-model <你当前的精确模型ID>", timeout_ms=1800000, description="clawclaw event stream")
249
250
 
250
251
  # 9 个不移动、不做任务、不使用技能、不击杀也不报警的木桩 bot
251
- Monitor(command="ccl start training dummy --agent-type claude-code --llm-model <你当前的精确模型ID>", persistent=true, description="clawclaw event stream")
252
+ Monitor(command="ccl start training dummy --agent-type claude-code --llm-model <你当前的精确模型ID>", timeout_ms=1800000, description="clawclaw event stream")
252
253
  ```
253
254
 
254
255
  玩家已经从前端创建训练房或启动训练局时统一运行 `ccl join`;不要再次创建训练房,也不要用房间码加入训练房。已经在熟人房、普通匹配或其他对局时先报告冲突并询问是否退出;目标训练类型已经明确时,只确认是否退出当前参与,不再询问训练类型。
@@ -419,7 +420,7 @@ ccl account settlement # 比赛结果;如果暂时无法获取,简要
419
420
  - 返回 `STILL_ALIVE`:`ok: false` 表示后端拒绝退出,不是本地停止失败。结合 `runtime_stop_requested` 和 `local_runtime` 告诉用户:本地 runtime 已接到停止请求(或未确认接到),但服务器里的玩家角色仍然存活、仍在当前对局;绝不能只说“没退”。
420
421
  - 返回 `ALLOCATION_IN_PROGRESS`:远端没有退出,且本地 runtime 保持运行以接管即将完成的 allocation;稍后根据新状态再决定是否重试。
421
422
 
422
- 只有当前 Monitor 已明确结束或失败后才恢复:后端已有参与时在新的无超时 persistent Monitor 中运行 `ccl join`。如果它报 `A ClawClaw runtime is already running (pid <PID>)`,不要附着或复用旧 Owner,改为运行 `ccl join --force`,把旧 Runtime 挤掉后重新拉起。只用 CCL 的 `--force`,不要自行运行 `kill` / `taskkill`。该选项只替换本机 Runtime,不代表退出后端参与,也不会延续旧本地会话中遗漏的实时事件。
423
+ 只有当前 Monitor 已明确结束或失败后才恢复:后端已有参与时在新的 30 分钟 Monitor(`timeout_ms=1800000`)中运行 `ccl join`。如果它报 `A ClawClaw runtime is already running (pid <PID>)`,不要附着或复用旧 Owner,改为运行 `ccl join --force`,把旧 Runtime 挤掉后重新拉起。只用 CCL 的 `--force`,不要自行运行 `kill` / `taskkill`。该选项只替换本机 Runtime,不代表退出后端参与,也不会延续旧本地会话中遗漏的实时事件。
423
424
 
424
425
  只有已显式启用 `CLAWCLAW_ENABLE_CLAUDE_CHANNELS=1` 时,才用 `channel_status` 辅助检查可选 Channel:
425
426
 
@@ -1,6 +1,8 @@
1
1
  # Claude Code Monitor 修复脚本
2
2
 
3
- Claude Code 运行 ClawClaw 时必须用 `Monitor(..., persistent=true, description="clawclaw event stream")` 托管顶层 `start` 或 `join` 长流。创建或加入新参与时传 `--agent-type claude-code --llm-model <你当前的模型ID>`(模型使用规范精确标识符);无参数 `ccl join` 用于恢复后端已有参与。必须显式传 `persistent=true`,禁止传 `timeout_ms`;非 persistent Monitor 默认仅运行 300000ms。调用后检查 Tool Use 和启动回执,若回执仍显示 `timeout 300000ms` / `timeout 300s`,立即停止错误任务并用完整参数重建。`Monitor started` 只代表宿主任务已创建;收到第一条非 error 的 CCL NDJSON 通知前,不得声称 CCL 已挂上或恢复。没有 `Monitor` 时不要退回 `Bash` 直接执行这些长流命令。
3
+ Claude Code 运行 ClawClaw 时必须用 `Monitor(..., timeout_ms=1800000, description="clawclaw event stream")` 托管顶层 `start` 或 `join` 长流。创建或加入新参与时传 `--agent-type claude-code --llm-model <你当前的模型ID>`(模型使用规范精确标识符);无参数 `ccl join` 用于恢复后端已有参与。必须显式传 `timeout_ms=1800000`(30 分钟),不得传已移除的 `persistent`。省略超时会采用 5 分钟默认值;调用后检查 Tool Use 包含 `timeout_ms: 1800000`。`Monitor started` 只代表宿主任务已创建;收到第一条非 error 的 CCL NDJSON 通知前,不得声称 CCL 已挂上或恢复。没有 `Monitor` 时不要退回 `Bash` 直接执行这些长流命令。
4
+
5
+ Monitor 到期会结束并通知 Claude;如果仍需继续当前参与,在新的 `timeout_ms=1800000` Monitor 中运行 `ccl join`。只有它报告旧 Runtime PID 冲突时才改用 `ccl join --force`。单提示 `-p` 模式最多 10 分钟,本 skill 的 30 分钟监控应在交互式 Claude Code 中运行。
4
6
 
5
7
  ## 什么时候使用
6
8
 
@@ -77,6 +77,7 @@ Manifest 是模块的机器可读说明。CCL 用它展示和校验模块,并
77
77
  | `inputs` | 启动时允许传入的参数;无参数写 `[]` |
78
78
  | `runtime` | 可选的短任务默认时限与控制宽限 |
79
79
  | `execution` | 可选,`parallel` 或 `serial` |
80
+ | `stateMode` | 可选,默认 `isolated`;并行策略可用 `snapshot` 继承最新完成帧的实例数据 |
80
81
  | `everyTicks` | 可选,每隔多少游戏 tick 决策一次 |
81
82
  | `produces` | 可选,本模块可能发布的自定义 Event type |
82
83
 
@@ -231,6 +232,23 @@ Status 不会修改 `GameState`,也不是私有存储。自定义 Event 必须
231
232
 
232
233
  每轮计算使用新的模块实例,不要依赖 `this` 字段跨 tick 保存状态。不同 tick 可以并行计算、乱序完成,但 Runtime 始终按输入顺序提交 Decision。
233
234
 
235
+ ### 并行策略的实例快照
236
+
237
+ 需要保留 `this.xxx` 跨帧数据的并行策略可以声明:
238
+
239
+ ```ts
240
+ execution: 'parallel',
241
+ stateMode: 'snapshot',
242
+ ```
243
+
244
+ 每次任务真正派给 Worker 时,读取同一 activation 中**帧号最大的、已成功完成计算**的实例数据快照;不等待更早帧计算或动作提交。任务中的副本保持独立。成功计算后返回整份新快照;旧帧晚完成不会覆盖更新帧,不合并不同任务的字段、不做版本冲突重算。这里的“完成”不是动作在后端执行成功,动作仍经过 Runtime 校验和有序提交。
245
+
246
+ 默认 `isolated` 保留已有并行模块每帧新实例的语义,`serial` 保留已有串行语义。`snapshot` 不能和 `serial` 同时声明,旧 CCL 不认识新字段时会拒绝加载,需使用支持该能力的版本。
247
+
248
+ 快照支持实例自有数据字段、普通对象、数组、Map、Set、Date、循环引用;TypeScript 的 `private` 普通字段也可以保留。辅助类须在构造函数中创建,恢复时保留其原型方法。函数、访问器、Symbol、连接/线程等资源,以及运行中临时创建、没有构造模板的辅助类不支持;ECMAScript `#private` 字段不在快照契约中,应保持串行或改用普通运行字段。快照上限 1 MiB,超限或不支持的数据会明确失败。
249
+
250
+ 同一 activation 暂停恢复时继承已完成快照;新的 activation / 对局不继承。不要将进程崩溃后的恢复或持久存储视为这项能力的保证。
251
+
234
252
  ### `serial`
235
253
 
236
254
  需要严格状态机时声明:
@@ -122,7 +122,7 @@ ccl events
122
122
 
123
123
  正常退出参与时使用 `ccl game quit`,不要用宿主任务强杀代替后端退出。读取命令的结构化结果,并结合长流后续的 `session_left`、`quit_failed` 或结束状态确认结果。停止或结束承载长流的宿主任务会同时停止本地 runtime、连接和 Behavior,但不等于后端已经接受退出。房间对局返回 `game_returned_room` 时只退出当前一轮,runtime 会继续回到 room lobby;在 `in_room` 再次 quit 才离开房间。`STILL_ALIVE` 时 `ok: false` 指后端拒绝退出;`runtime_stop_requested` / `local_runtime` 另行说明本地 runtime 是否已接到停止请求,而 `backend_participation: "active_game"` 明确表示服务器里的玩家仍在本局。`ALLOCATION_IN_PROGRESS` 表示远端未退出且 runtime 保持运行。
124
124
 
125
- 只有当前 Monitor 已明确结束或失败时才使用本节:后端已有参与时,在新的 persistent Monitor 中运行 `ccl join`。新进程会创建新的本地运行时会话,再向后端确认并恢复 queue、game 或 room;它不会附着到旧进程,也不会恢复旧本地会话中遗漏的实时事件。若旧 Runtime 仍存活,`ccl join` 会被拒绝并返回其 PID。这个 PID 只证明 Owner 存活;不要附着或复用旧 Owner,改用 `ccl join --force` 挤掉旧 Runtime 后重新拉起。只使用 CCL 的 `--force`,不要自行运行 `kill` / `taskkill`;它会先请求旧 Runtime 正常停止,必要时终止旧进程树,确认退出后再启动新进程。`--force` 不退出后端参与,新进程仍可能恢复原 queue、game 或 room:
125
+ 只有当前 Monitor 已明确结束或失败时才使用本节:后端已有参与时,在新的 30 分钟 Monitor(`timeout_ms=1800000`)中运行 `ccl join`。新进程会创建新的本地运行时会话,再向后端确认并恢复 queue、game 或 room;它不会附着到旧进程,也不会恢复旧本地会话中遗漏的实时事件。若旧 Runtime 仍存活,`ccl join` 会被拒绝并返回其 PID。这个 PID 只证明 Owner 存活;不要附着或复用旧 Owner,改用 `ccl join --force` 挤掉旧 Runtime 后重新拉起。只使用 CCL 的 `--force`,不要自行运行 `kill` / `taskkill`;它会先请求旧 Runtime 正常停止,必要时终止旧进程树,确认退出后再启动新进程。`--force` 不退出后端参与,新进程仍可能恢复原 queue、game 或 room:
126
126
 
127
127
  - 能从后端响应取得 `spectate_url` 时,`session_resumed` 会把完整 URL 交给 Agent。
128
128
  - 后端没有返回 URL 时,`ccl game watch` 只按当前 server origin 和本地凭据拼一个兜底链接;它不会额外请求服务器。
@@ -123,6 +123,7 @@ function sourceEntry(
123
123
  }),
124
124
  execution: source.execution,
125
125
  every_ticks: source.everyTicks,
126
+ state_mode: source.stateMode ?? 'isolated',
126
127
  inputs: source.inputs,
127
128
  produces: source.produces ?? [],
128
129
  ...(source.runtime === undefined ? {} : { runtime: source.runtime }),
@@ -15,6 +15,7 @@ import { prepareClawclawBehavior } from './behavior-normalization.js';
15
15
  import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
16
16
  import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
17
17
  import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
18
+ import { captureBehaviorInstance, restoreBehaviorInstance, type BehaviorInstanceSnapshot } from './behavior-instance-snapshot.js';
18
19
 
19
20
  interface BehaviorThreadWorkerData {
20
21
  readonly poolId: string;
@@ -26,6 +27,7 @@ interface BehaviorThreadWorkerData {
26
27
  }
27
28
 
28
29
  interface BehaviorThreadRunRequest {
30
+ readonly instanceSnapshot?: BehaviorInstanceSnapshot;
29
31
  readonly type: 'run';
30
32
  readonly poolId: string;
31
33
  readonly requestId: string;
@@ -137,6 +139,9 @@ async function run(request: BehaviorThreadRunRequest | BehaviorThreadStopRequest
137
139
  if (!instance || typeof instance.decide !== 'function') {
138
140
  throw new Error('behavior_thread_instance_invalid');
139
141
  }
142
+ if (loaded.manifest.stateMode === 'snapshot' && request.instanceSnapshot) {
143
+ restoreBehaviorInstance(instance, request.instanceSnapshot);
144
+ }
140
145
  const api = createBehaviorReadApi(input, {
141
146
  onQuery: () => { queryCount += 1; },
142
147
  isActive: () => invocationActive,
@@ -146,10 +151,13 @@ async function run(request: BehaviorThreadRunRequest | BehaviorThreadStopRequest
146
151
  });
147
152
  try {
148
153
  const result = normalizeBehaviorDecision(await instance.decide(input, api), { finite: false });
154
+ const instanceSnapshot = loaded.manifest.stateMode === 'snapshot' ? captureBehaviorInstance(instance) : undefined;
155
+ if (instanceSnapshot) assertRuntimeModuleOutputSize({ result, instanceSnapshot }, 'behavior_snapshot_output');
149
156
  send({
150
157
  type: 'result',
151
158
  requestId: request.requestId,
152
159
  result,
160
+ ...(instanceSnapshot === undefined ? {} : { instanceSnapshot }),
153
161
  queryCount,
154
162
  durationMs: Math.round((performance.now() - startedAt) * 1_000) / 1_000,
155
163
  ...diagnosticMemory(),
@@ -23,6 +23,7 @@ export interface ClawclawBehaviorCatalogEntry {
23
23
  readonly localizations?: ResolvedClawclawBehaviorSource['localizations'];
24
24
  readonly inputs: ResolvedClawclawBehaviorSource['inputs'];
25
25
  readonly execution: ResolvedClawclawBehaviorSource['execution'];
26
+ readonly stateMode?: ResolvedClawclawBehaviorSource['stateMode'];
26
27
  readonly everyTicks: number;
27
28
  readonly produces?: readonly string[];
28
29
  readonly runtime?: ResolvedClawclawBehaviorSource['runtime'];
@@ -49,6 +50,7 @@ function catalogEntry(source: ResolvedClawclawBehaviorSource): ClawclawBehaviorC
49
50
  ...(source.localizations === undefined ? {} : { localizations: source.localizations }),
50
51
  inputs: source.inputs,
51
52
  execution: source.execution,
53
+ ...(source.stateMode === undefined ? {} : { stateMode: source.stateMode }),
52
54
  everyTicks: source.everyTicks,
53
55
  ...(source.produces === undefined ? {} : { produces: source.produces }),
54
56
  ...(source.runtime === undefined ? {} : { runtime: source.runtime }),
@@ -0,0 +1,123 @@
1
+ import { serialize } from 'node:v8';
2
+
3
+ type Value = null | undefined | boolean | number | string | bigint | { ref: number };
4
+ interface Node {
5
+ kind: 'object' | 'array' | 'map' | 'set' | 'date';
6
+ className?: string;
7
+ nullPrototype?: boolean;
8
+ entries?: Array<[string, Value]>;
9
+ items?: Value[];
10
+ pairs?: Array<[Value, Value]>;
11
+ time?: number;
12
+ }
13
+ export interface BehaviorInstanceSnapshot { readonly nodes: readonly Node[]; }
14
+ export const MAX_BEHAVIOR_SNAPSHOT_BYTES = 1024 * 1024;
15
+
16
+ /** One activation's completed computation state; never an Action receipt or commit checkpoint. */
17
+ export class BehaviorSnapshotStore {
18
+ generation = 0;
19
+ latest?: { epochId: number; value: BehaviorInstanceSnapshot };
20
+ publish(epochId: number, value: BehaviorInstanceSnapshot, generation: number): boolean {
21
+ if (generation !== this.generation || (this.latest && epochId <= this.latest.epochId)) return false;
22
+ this.latest = { epochId, value: structuredClone(value) };
23
+ return true;
24
+ }
25
+ reset(): void { this.generation++; this.latest = undefined; }
26
+ }
27
+
28
+ function unsupported(reason: string): never { throw new Error(`behavior_snapshot_unsupported:${reason}`); }
29
+ function className(value: object): string | undefined {
30
+ const proto = Object.getPrototypeOf(value);
31
+ if (proto === null || proto === Object.prototype) return undefined;
32
+ const constructor = Object.getOwnPropertyDescriptor(proto, 'constructor')?.value;
33
+ return typeof constructor === 'function' ? constructor.name : unsupported('prototype');
34
+ }
35
+
36
+ /** Capture data only. Methods stay on fresh constructor-created instances in each Worker. */
37
+ export function captureBehaviorInstance(instance: object): BehaviorInstanceSnapshot {
38
+ const nodes: Node[] = [];
39
+ const seen = new Map<object, number>();
40
+ let stringBytes = 0;
41
+ function encode(value: unknown, depth: number): Value {
42
+ if (depth > 128) unsupported('depth');
43
+ if (typeof value === 'string') {
44
+ stringBytes += Buffer.byteLength(value);
45
+ if (stringBytes > MAX_BEHAVIOR_SNAPSHOT_BYTES) throw new Error('behavior_snapshot_too_large');
46
+ }
47
+ if (value === null || value === undefined || ['boolean', 'number', 'string', 'bigint'].includes(typeof value)) return value as Value;
48
+ if (typeof value !== 'object') unsupported(typeof value);
49
+ const object = value as object;
50
+ const prior = seen.get(object);
51
+ if (prior !== undefined) return { ref: prior };
52
+ if (nodes.length >= 10_000) throw new Error('behavior_snapshot_too_large');
53
+ const ref = nodes.length;
54
+ const node: Node = { kind: 'object' };
55
+ seen.set(object, ref); nodes.push(node);
56
+ if (Array.isArray(object)) {
57
+ node.kind = 'array'; node.items = object.map(v => encode(v, depth + 1));
58
+ } else if (object instanceof Map) {
59
+ node.kind = 'map'; node.pairs = [...object].map(([k, v]) => [encode(k, depth + 1), encode(v, depth + 1)]);
60
+ } else if (object instanceof Set) {
61
+ node.kind = 'set'; node.items = [...object].map(v => encode(v, depth + 1));
62
+ } else if (object instanceof Date) {
63
+ node.kind = 'date'; node.time = object.getTime();
64
+ } else {
65
+ node.className = className(object);
66
+ node.nullPrototype = Object.getPrototypeOf(object) === null;
67
+ node.entries = [];
68
+ for (const key of Reflect.ownKeys(object)) {
69
+ if (typeof key !== 'string') unsupported('symbol_key');
70
+ const descriptor = Object.getOwnPropertyDescriptor(object, key)!;
71
+ if (!('value' in descriptor)) unsupported('accessor');
72
+ node.entries.push([key, encode(descriptor.value, depth + 1)]);
73
+ }
74
+ }
75
+ return { ref };
76
+ }
77
+ encode(instance, 0);
78
+ const snapshot = { nodes };
79
+ if (serialize(snapshot).byteLength > MAX_BEHAVIOR_SNAPSHOT_BYTES) throw new Error('behavior_snapshot_too_large');
80
+ return snapshot;
81
+ }
82
+
83
+ /** Custom helper classes must be created by the constructor so their methods are retained. */
84
+ export function restoreBehaviorInstance(instance: object, snapshot: BehaviorInstanceSnapshot): void {
85
+ if (!Array.isArray(snapshot.nodes) || snapshot.nodes.length === 0
86
+ || snapshot.nodes.length > 10_000 || serialize(snapshot).byteLength > MAX_BEHAVIOR_SNAPSHOT_BYTES) {
87
+ throw new Error('behavior_snapshot_invalid');
88
+ }
89
+ const restored = new Map<number, any>();
90
+ function decode(value: Value, seed?: any): any {
91
+ if (value === null || typeof value !== 'object') return value;
92
+ if (restored.has(value.ref)) return restored.get(value.ref);
93
+ const node = snapshot.nodes[value.ref];
94
+ if (!node) throw new Error('behavior_snapshot_reference_invalid');
95
+ let result: any;
96
+ if (node.kind === 'array') result = [];
97
+ else if (node.kind === 'map') result = new Map();
98
+ else if (node.kind === 'set') result = new Set();
99
+ else if (node.kind === 'date') result = new Date(node.time!);
100
+ else if (node.className) {
101
+ if (!seed || typeof seed !== 'object' || className(seed) !== node.className) unsupported(`class_template:${node.className}`);
102
+ result = seed;
103
+ } else result = node.nullPrototype ? Object.create(null) : {};
104
+ restored.set(value.ref, result);
105
+ if (node.kind === 'object') {
106
+ const keys = new Set(node.entries!.map(([key]) => key));
107
+ for (const key of Object.getOwnPropertyNames(result)) if (!keys.has(key)) {
108
+ if (!Reflect.deleteProperty(result, key)) unsupported('nonconfigurable_field');
109
+ }
110
+ for (const [key, entry] of node.entries!) {
111
+ const initial = Object.getOwnPropertyDescriptor(result, key);
112
+ const decoded = decode(entry, initial && 'value' in initial ? initial.value : undefined);
113
+ Object.defineProperty(result, key, { value: decoded, enumerable: true, writable: true, configurable: true });
114
+ }
115
+ } else if (node.kind === 'array') node.items!.forEach((v, i) => { result[i] = decode(v, seed?.[i]); });
116
+ else if (node.kind === 'set') for (const v of node.items!) result.add(decode(v));
117
+ else if (node.kind === 'map') for (const [k, v] of node.pairs!) {
118
+ const key = decode(k); result.set(key, decode(v, seed instanceof Map ? seed.get(key) : undefined));
119
+ }
120
+ return result;
121
+ }
122
+ decode({ ref: 0 }, instance);
123
+ }
@@ -18,6 +18,7 @@ const MANIFEST_FIELDS = new Set([
18
18
  'localizations',
19
19
  'inputs',
20
20
  'execution',
21
+ 'stateMode',
21
22
  'everyTicks',
22
23
  'produces',
23
24
  'runtime',
@@ -135,6 +136,12 @@ export function normalizeClawclawBehaviorManifest(
135
136
  && manifest.execution !== 'serial'
136
137
  ) throw new Error('behavior_execution_invalid');
137
138
  const everyTicks = manifest.everyTicks ?? 1;
139
+ if (manifest.stateMode !== undefined && manifest.stateMode !== 'isolated' && manifest.stateMode !== 'snapshot') {
140
+ throw new Error('behavior_state_mode_invalid');
141
+ }
142
+ if (manifest.stateMode === 'snapshot' && manifest.execution === 'serial') {
143
+ throw new Error('behavior_snapshot_requires_parallel');
144
+ }
138
145
  if (!Number.isSafeInteger(everyTicks) || (everyTicks as number) <= 0) {
139
146
  throw new Error('behavior_every_ticks_invalid');
140
147
  }
@@ -161,6 +168,7 @@ export function normalizeClawclawBehaviorManifest(
161
168
  description: (manifest.description as string).trim(),
162
169
  ...(localizations === undefined ? {} : { localizations }),
163
170
  inputs,
171
+ ...(manifest.stateMode === undefined ? {} : { stateMode: manifest.stateMode as 'isolated' | 'snapshot' }),
164
172
  ...(manifest.execution === undefined
165
173
  ? {}
166
174
  : { execution: manifest.execution as 'parallel' | 'serial' }),
@@ -95,6 +95,9 @@ function assertSourceParity(
95
95
  manifest: Readonly<ClawclawBehaviorManifest>,
96
96
  source: ResolvedClawclawBehaviorSource,
97
97
  ): void {
98
+ if ((manifest.stateMode ?? 'isolated') !== (source.stateMode ?? 'isolated')) {
99
+ throw new Error('behavior_state_mode_source_mismatch');
100
+ }
98
101
  if (manifest.id !== (source.declaredId ?? source.id)) throw new Error('behavior_id_source_mismatch');
99
102
  if (manifest.name !== source.name) throw new Error('behavior_name_source_mismatch');
100
103
  if (manifest.description !== source.description) {
@@ -46,6 +46,7 @@ import type { ClawclawBehaviorCatalog } from './behavior-catalog.js';
46
46
  import { BehaviorDecisionHistory } from './behavior-decision-history.js';
47
47
  import type { PreparedClawclawBehavior } from './behavior-normalization.js';
48
48
  import { ClawclawBehaviorRunner } from './behavior-runner.js';
49
+ import { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
49
50
  import type {
50
51
  ClawclawBehaviorControlDriver,
51
52
  ClawclawBehaviorControlHandle,
@@ -134,6 +135,7 @@ export interface ClawclawBehaviorHostStatus {
134
135
  }
135
136
 
136
137
  interface ActivationRuntime {
138
+ snapshotStore?: BehaviorSnapshotStore;
137
139
  readonly activationId: string;
138
140
  readonly behaviorId: string;
139
141
  prepared: PreparedClawclawBehavior;
@@ -280,7 +282,11 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
280
282
  readonly produces: RuntimeEpochPlugin<Record<string, any>>['produces'];
281
283
  readonly capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY] } as const;
282
284
  readonly catchUp: RuntimeEpochCatchUp;
283
- readonly maxInFlight = 10;
285
+ readonly backlogPolicy = 'finish_started' as const;
286
+ get maxInFlight(): number {
287
+ const current = this.manager.current();
288
+ return current && this.runtimes.get(current.activationId)?.prepared.manifest.execution === 'serial' ? 1 : 10;
289
+ }
284
290
  readonly maxPendingEpochs = 10;
285
291
  readonly timeoutMs: number;
286
292
  readonly failurePolicy = 'failed_completion' as const;
@@ -1292,6 +1298,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1292
1298
  : {}),
1293
1299
  });
1294
1300
  runtime.runner = new ClawclawBehaviorRunner({
1301
+ snapshotStore: runtime.snapshotStore ??= new BehaviorSnapshotStore(),
1295
1302
  behaviorId: activation.behaviorId,
1296
1303
  activationId: activation.activationId,
1297
1304
  instanceGeneration: activation.instanceGeneration,
@@ -1304,6 +1311,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1304
1311
  ),
1305
1312
  });
1306
1313
  runtime.instanceGeneration = activation.instanceGeneration;
1314
+ await runtime.runner.prepare();
1307
1315
  runtime.lastCommittedBackendTick = undefined;
1308
1316
  runtime.lastStatus = undefined;
1309
1317
  runtime.committedActionDedupeKeys.clear();
@@ -11,8 +11,10 @@ import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/contr
11
11
  import type { PreparedClawclawBehavior } from './behavior-normalization.js';
12
12
  import { ThreadBehaviorExecutor } from './thread-behavior-executor.js';
13
13
  import { DetailCapture } from '../../../observability/detail-capture.js';
14
+ import type { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
14
15
 
15
16
  export interface ClawclawBehaviorRunnerOptions {
17
+ readonly snapshotStore?: BehaviorSnapshotStore;
16
18
  readonly behaviorId: string;
17
19
  readonly activationId: string;
18
20
  readonly instanceGeneration: number;
@@ -71,6 +73,13 @@ export class ClawclawBehaviorRunner {
71
73
  return this.prepared.manifest.execution ?? 'parallel';
72
74
  }
73
75
 
76
+ /** Start/import Workers at activation, outside per-decision computation deadlines. */
77
+ async prepare(): Promise<void> {
78
+ if (!this.prepared.source) return;
79
+ this.ensureThreadExecutor();
80
+ await this.parallelReady;
81
+ }
82
+
74
83
  get everyTicks(): number {
75
84
  return this.prepared.manifest.everyTicks ?? 1;
76
85
  }
@@ -172,6 +181,8 @@ export class ClawclawBehaviorRunner {
172
181
  throw new Error('behavior_thread_source_invalid');
173
182
  }
174
183
  const executor = new ThreadBehaviorExecutor({
184
+ fixedWorkers: true,
185
+ snapshotStore: this.options.snapshotStore,
175
186
  source,
176
187
  diagnostic: this.options.diagnostic,
177
188
  diagnosticsEnabled: this.options.diagnosticsEnabled,
@@ -39,6 +39,7 @@ const MANIFEST_FIELDS = new Set([
39
39
  'localizations',
40
40
  'inputs',
41
41
  'execution',
42
+ 'stateMode',
42
43
  'everyTicks',
43
44
  'produces',
44
45
  'runtime',
@@ -68,6 +69,7 @@ export interface ResolvedClawclawBehaviorSource {
68
69
  readonly localizations?: ClawclawResourceLocalizations;
69
70
  readonly inputs: readonly Readonly<BehaviorInputFieldSpec>[];
70
71
  readonly execution: 'parallel' | 'serial';
72
+ readonly stateMode?: 'isolated' | 'snapshot';
71
73
  readonly everyTicks: number;
72
74
  readonly produces?: readonly string[];
73
75
  readonly runtime?: Readonly<BehaviorRuntimeDefaults>;
@@ -438,6 +440,9 @@ function sourceCompatibility(
438
440
  ? localizationsProperty.value as ClawclawResourceLocalizations
439
441
  : undefined;
440
442
  const executionProperty = literalProperty(manifest, 'execution');
443
+ const stateModeProperty = literalProperty(manifest, 'stateMode');
444
+ const stateMode = stateModeProperty.status === 'valid'
445
+ ? stateModeProperty.value as 'isolated' | 'snapshot' : undefined;
441
446
  const execution = executionProperty.status === 'valid' && executionProperty.value === 'serial'
442
447
  ? 'serial'
443
448
  : 'parallel';
@@ -502,6 +507,9 @@ function sourceCompatibility(
502
507
  && (!Number.isSafeInteger(everyTicksProperty.value) || (everyTicksProperty.value as number) <= 0)
503
508
  )
504
509
  ) compatibilityError = 'behavior_every_ticks_invalid';
510
+ else if (stateModeProperty.status === 'invalid'
511
+ || (stateMode !== undefined && stateMode !== 'isolated' && stateMode !== 'snapshot')) compatibilityError = 'behavior_state_mode_invalid';
512
+ else if (stateMode === 'snapshot' && execution === 'serial') compatibilityError = 'behavior_snapshot_requires_parallel';
505
513
  else if (runtimeError) compatibilityError = runtimeError;
506
514
  else if (producesProperty.status === 'invalid') compatibilityError = 'behavior_produces_invalid';
507
515
  else if (produces !== undefined) compatibilityError = behaviorProducesDiagnostic(produces);
@@ -513,6 +521,7 @@ function sourceCompatibility(
513
521
  ...(localizations === undefined ? {} : { localizations: structuredClone(localizations) }),
514
522
  inputs,
515
523
  execution,
524
+ ...(stateMode === undefined ? {} : { stateMode }),
516
525
  everyTicks,
517
526
  ...(produces === undefined ? {} : { produces: [...produces] }),
518
527
  ...(runtime === undefined ? {} : { runtime }),
@@ -18,6 +18,7 @@ import {
18
18
  } from './behavior-module-loader.js';
19
19
  import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
20
20
  import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
21
+ import { BehaviorSnapshotStore, type BehaviorInstanceSnapshot } from './behavior-instance-snapshot.js';
21
22
 
22
23
  export const PARALLEL_BEHAVIOR_THREAD_POOL_SIZE = 10;
23
24
  const INITIAL_WORKER_COUNT = 2;
@@ -33,6 +34,8 @@ const WORKER_BOOTSTRAP = realpathSync(fileURLToPath(
33
34
  const WORKER_HOST_URL = new URL('./behavior-analysis-thread-host.ts', import.meta.url).href;
34
35
 
35
36
  export interface ThreadBehaviorExecutorOptions {
37
+ readonly fixedWorkers?: boolean;
38
+ readonly snapshotStore?: BehaviorSnapshotStore;
36
39
  readonly source: ResolvedClawclawBehaviorSource;
37
40
  /** Maximum Worker count and in-flight request window. Tests may reduce it. */
38
41
  readonly poolSize?: number;
@@ -62,6 +65,8 @@ export interface ThreadBehaviorExecutorSnapshot {
62
65
  }
63
66
 
64
67
  interface PendingRequest {
68
+ snapshotEpoch?: number;
69
+ snapshotGeneration?: number;
65
70
  readonly requestId: string;
66
71
  readonly operation: 'decide';
67
72
  readonly frame: BehaviorInput;
@@ -106,6 +111,7 @@ interface WorkerReadyMessage extends WorkerMessageBase {
106
111
  }
107
112
 
108
113
  interface WorkerResultMessage extends WorkerMessageBase {
114
+ readonly instanceSnapshot?: BehaviorInstanceSnapshot;
109
115
  readonly type: 'result';
110
116
  readonly requestId: string;
111
117
  readonly result: BehaviorDecision;
@@ -238,6 +244,7 @@ export async function prepareBehaviorInWorker(
238
244
 
239
245
  /** Adaptive Worker Thread pool for cross-tick computations. */
240
246
  export class ThreadBehaviorExecutor {
247
+ private readonly snapshotStore: BehaviorSnapshotStore;
241
248
  readonly runtimeInstanceId = randomUUID();
242
249
 
243
250
  private readonly maxWorkerCount: number;
@@ -265,6 +272,7 @@ export class ThreadBehaviorExecutor {
265
272
  private readonly options: ThreadBehaviorExecutorOptions;
266
273
 
267
274
  constructor(options: ThreadBehaviorExecutorOptions) {
275
+ this.snapshotStore = options.snapshotStore ?? new BehaviorSnapshotStore();
268
276
  this.options = Object.freeze({
269
277
  ...options,
270
278
  source: pinBehaviorSource(options.source),
@@ -284,7 +292,7 @@ export class ThreadBehaviorExecutor {
284
292
  this.maxPendingRequestCount = execution === 'serial'
285
293
  ? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE
286
294
  : maxWorkerCount;
287
- this.minWorkerCount = Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
295
+ this.minWorkerCount = options.fixedWorkers ? maxWorkerCount : Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
288
296
  this.desiredWorkerCount = this.minWorkerCount;
289
297
  this.idleWorkerTimeoutMs = idleWorkerTimeoutMs;
290
298
  this.maxOldGenerationSizeMb = Math.max(16, Math.min(
@@ -349,8 +357,7 @@ export class ThreadBehaviorExecutor {
349
357
  }
350
358
 
351
359
  async reset(_signal: AbortSignal): Promise<void> {
352
- // Parallel Behavior instances are already fresh per input. Only the
353
- // module/Class is cached by each slot.
360
+ this.snapshotStore.reset();
354
361
  }
355
362
 
356
363
  stop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void> {
@@ -555,6 +562,9 @@ export class ThreadBehaviorExecutor {
555
562
  slot.current = request;
556
563
  request.slot = slot;
557
564
  request.assignedAt = performance.now();
565
+ const inherited = this.options.source.stateMode === 'snapshot' ? this.snapshotStore.latest : undefined;
566
+ request.snapshotEpoch = inherited?.epochId;
567
+ request.snapshotGeneration = this.snapshotStore.generation;
558
568
  try {
559
569
  slot.worker.postMessage({
560
570
  type: 'run',
@@ -562,6 +572,7 @@ export class ThreadBehaviorExecutor {
562
572
  requestId: request.requestId,
563
573
  operation: request.operation,
564
574
  frame: request.frame,
575
+ ...(inherited ? { instanceSnapshot: inherited.value } : {}),
565
576
  ...(request.observationSnapshot === undefined
566
577
  ? {}
567
578
  : { observationSnapshot: request.observationSnapshot }),
@@ -654,6 +665,15 @@ export class ThreadBehaviorExecutor {
654
665
  message: WorkerResultMessage,
655
666
  ): void {
656
667
  if (request.settled) return;
668
+ const published = this.options.source.stateMode === 'snapshot' && message.instanceSnapshot
669
+ && !request.signal.aborted && this.state === 'running'
670
+ ? this.snapshotStore.publish(request.frame.epochId, message.instanceSnapshot, request.snapshotGeneration!)
671
+ : false;
672
+ if (this.options.source.stateMode === 'snapshot') this.diagnostic('behavior.snapshot.completed', {
673
+ behavior_id: this.options.source.id, epoch_id: request.frame.epochId,
674
+ inherited_epoch_id: request.snapshotEpoch ?? null, published,
675
+ latest_completed_epoch_id: this.snapshotStore.latest?.epochId ?? null,
676
+ }, 'debug');
657
677
  request.settled = true;
658
678
  request.signal.removeEventListener('abort', request.onAbort);
659
679
  this.inFlight.delete(request);
@@ -73,6 +73,10 @@ export interface PerceptionAnalysisThreadPoolSnapshot {
73
73
  }
74
74
 
75
75
  export interface PerceptionAnalysisThreadPoolOptions {
76
+ /** Accepted frame batches, independent of the number of module-analysis Workers. */
77
+ readonly maxPendingBatches?: number;
78
+ /** Prewarm and retain the configured pool instead of importing Workers during overload. */
79
+ readonly fixedWorkers?: boolean;
76
80
  readonly modules: readonly PerceptionThreadModuleSpec[];
77
81
  readonly loader: PerceptionThreadLoaderConfig;
78
82
  readonly spatialFacts: PerceptionSpatialFacts;
@@ -189,6 +193,7 @@ export class PerceptionAnalysisThreadPool {
189
193
  private readonly poolId = randomUUID();
190
194
  private readonly minWorkers: number;
191
195
  private readonly maxWorkers: number;
196
+ private readonly maxPendingBatches: number;
192
197
  private readonly maxOldGenerationSizeMb: number;
193
198
  private state: PerceptionAnalysisThreadPoolSnapshot['state'] = 'new';
194
199
  private readonly slots = new Set<WorkerSlot>();
@@ -212,7 +217,11 @@ export class PerceptionAnalysisThreadPool {
212
217
  throw new TypeError(`maxWorkers must be between 1 and ${MAX_WORKERS}.`);
213
218
  }
214
219
  this.maxWorkers = maxWorkers;
215
- this.minWorkers = Math.min(DEFAULT_WARM_WORKERS, maxWorkers);
220
+ this.maxPendingBatches = options.maxPendingBatches ?? maxWorkers;
221
+ if (!Number.isInteger(this.maxPendingBatches) || this.maxPendingBatches < 1 || this.maxPendingBatches > MAX_WORKERS) {
222
+ throw new Error('perception_pending_batch_limit_invalid');
223
+ }
224
+ this.minWorkers = options.fixedWorkers ? maxWorkers : Math.min(DEFAULT_WARM_WORKERS, maxWorkers);
216
225
  this.maxOldGenerationSizeMb = Math.max(16, Math.min(
217
226
  256,
218
227
  Math.floor(options.maxOldGenerationSizeMb ?? 64),
@@ -290,7 +299,7 @@ export class PerceptionAnalysisThreadPool {
290
299
  workerPoolHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
291
300
  };
292
301
  }
293
- if (this.inFlight.size >= this.maxWorkers) {
302
+ if (this.inFlight.size >= this.maxPendingBatches) {
294
303
  throw new Error('perception_analysis_window_full');
295
304
  }
296
305
  const configured = new Set(this.options.modules.map(({ moduleId }) => moduleId));
@@ -373,6 +373,10 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
373
373
  }
374
374
  readonly maxInFlight: number;
375
375
  readonly maxPendingEpochs = 10;
376
+ readonly backlogPolicy = 'finish_started' as const;
377
+ // Includes bounded analysis queueing and ordered reducer roundtrips. A 1s
378
+ // framework default killed healthy Workers during CPU contention/recovery.
379
+ readonly timeoutMs = 5_000;
376
380
  readonly recoveryTimeoutMs = DEFAULT_PERCEPTION_RECOVERY_TIMEOUT_MS;
377
381
  readonly produces: { readonly events: readonly string[] };
378
382
 
@@ -1720,7 +1724,9 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1720
1724
  modules: parallelCandidates.map(({ threadModule }) => threadModule),
1721
1725
  loader: this.moduleLoader.threadConfig(),
1722
1726
  spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS satisfies PerceptionSpatialFacts,
1723
- maxWorkers: this.maxInFlight,
1727
+ maxWorkers: Math.min(this.maxInFlight, Math.max(2, parallelCandidates.length)),
1728
+ maxPendingBatches: this.maxInFlight,
1729
+ fixedWorkers: true,
1724
1730
  diagnosticsEnabled: this.diagnosticsEnabled,
1725
1731
  diagnostic,
1726
1732
  });
@@ -245,6 +245,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
245
245
  return this.threaded ? 10 : 1;
246
246
  }
247
247
  readonly maxPendingEpochs = 10;
248
+ readonly backlogPolicy = 'finish_started' as const;
248
249
  readonly timeoutMs = DEFAULT_TRIGGER_PLUGIN_TIMEOUT_MS;
249
250
  readonly failurePolicy = 'failed_completion' as const;
250
251
 
@@ -736,7 +737,9 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
736
737
  ? 'trigger_activation_accepted'
737
738
  : selected ? `trigger_activation_rejected:${activationResult?.reason ?? 'unknown'}` : 'trigger_no_eligible_match',
738
739
  checkpoint: this.checkpoint(),
739
- ...(computed.eventCursor === undefined ? {} : {
740
+ // Earlier ordered commits may have consumed a newer watermark while this
741
+ // computation was in flight. Never move the consumption cursor backwards.
742
+ ...(computed.eventCursor === undefined || computed.eventCursor <= context.progress().eventCursor ? {} : {
740
743
  consumeEventsThroughCommitSeq: computed.eventCursor,
741
744
  }),
742
745
  };
@@ -195,6 +195,8 @@ extends RuntimePluginIdentity<'epoch'> {
195
195
  readonly after?: readonly string[];
196
196
  readonly capabilities?: RuntimePluginCapabilityDeclaration;
197
197
  readonly catchUp?: RuntimeEpochCatchUp;
198
+ /** Preserve started computations under ordinary overload, then catch up to the latest boundary. */
199
+ readonly backlogPolicy?: 'finish_started';
198
200
  /**
199
201
  * Maximum overlapping update calls, from 1 through 10. Defaults to 1.
200
202
  * Values above 1 are an explicit promise that update is re-entrant and
@@ -495,6 +495,7 @@ export class RuntimePluginScheduler<
495
495
  private readonly inputEventCommits = new Map<number, Promise<void>>();
496
496
  private inputEventCommitTail: Promise<void> = Promise.resolve();
497
497
  private readonly catchUpCounts = new Map<string, number>();
498
+ private readonly drainingBatches = new Set<string>();
498
499
  private readonly pluginTimingWindows = new Map<string, PluginTimingWindow>();
499
500
  private readonly lagBands = new Map<string, RuntimeLagBand>();
500
501
  private readonly pausedPlugins = new Set<string>();
@@ -641,6 +642,7 @@ export class RuntimePluginScheduler<
641
642
  this.activeScope = cloneCanonical(scope);
642
643
  this.pausedPlugins.clear();
643
644
  this.catchUpCounts.clear();
645
+ this.drainingBatches.clear();
644
646
  for (const layer of this.layers) {
645
647
  await Promise.all(layer.map(async (plugin) => {
646
648
  const startController = new AbortController();
@@ -823,6 +825,8 @@ export class RuntimePluginScheduler<
823
825
  if (candidates.length === 0) continue;
824
826
  }
825
827
  if (maxInFlight === 1 && this.scheduledInvocationCount(plugin.id) > 0) continue;
828
+ if (this.drainingBatches.has(plugin.id)
829
+ && (this.scheduledInvocationCount(plugin.id) > 0 || this.activeCommits.has(plugin.id))) continue;
826
830
 
827
831
  if (maxInFlight > 1) {
828
832
  const reorderCapacity = (plugin.catchUp ?? 'every_epoch') === 'strict_ordered'
@@ -976,6 +980,7 @@ export class RuntimePluginScheduler<
976
980
  const supersededBeforeCommit = !invocation.error
977
981
  && !forbidsCoalescing(buffered.work)
978
982
  && (plugin.catchUp ?? 'every_epoch') === 'latest_only'
983
+ && plugin.backlogPolicy !== 'finish_started'
979
984
  && latestReadyBeforeCommit > buffered.work.epoch.epochSeq
980
985
  ? latestReadyBeforeCommit
981
986
  : null;
@@ -1463,6 +1468,20 @@ export class RuntimePluginScheduler<
1463
1468
  ),
1464
1469
  10_000,
1465
1470
  );
1471
+ if (plugin.backlogPolicy === 'finish_started') {
1472
+ const ready = this.readyCandidates(plugin, scope);
1473
+ if (ready.length > catchUpWindow) this.drainingBatches.add(plugin.id);
1474
+ if (!this.drainingBatches.has(plugin.id)) return;
1475
+ // Do not replace active/buffered work. Stop refilling the current batch
1476
+ // until its ordered effects have completed, then skip only unstarted work.
1477
+ if (this.scheduledInvocationCount(plugin.id) > 0 || this.activeCommits.has(plugin.id)) return;
1478
+ const boundary = ready.findIndex(({ work }) => forbidsCoalescing(work));
1479
+ const target = boundary >= 0 ? boundary : ready.length - 1;
1480
+ if (target > 0) this.recordCoalesced(plugin, ready.slice(0, target).map(x => x.work),
1481
+ boundary >= 0 ? 'required_epoch_boundary' : 'catch_up_limit');
1482
+ this.drainingBatches.delete(plugin.id);
1483
+ return;
1484
+ }
1466
1485
  while (true) {
1467
1486
  const ready = this.readyCandidates(plugin, scope);
1468
1487
  const earliest = ready[0];
@@ -9,13 +9,14 @@ export interface GameSyncIngressConfig {
9
9
  resumeState?: GameSyncResumeState;
10
10
  reconnectMaxMs?: number;
11
11
  ackIntervalMs?: number;
12
- maxPendingFrames: number;
12
+ /** Credits for complete frames handed to Source, not a socket-disconnect threshold. */
13
+ maxInFlightFrames: number;
13
14
  maxPendingBytes: number;
14
15
  rawLog?: { path: string; options?: BufferedRawWsLogOptions };
15
16
  }
16
17
 
17
18
  export type IngressCommand =
18
- | { type: 'ack'; token: string; immediate: boolean }
19
+ | { type: 'consumed'; token: string }
19
20
  | { type: 'report'; perceptions: readonly GameSyncPerceptionReport[] }
20
21
  | { type: 'telemetry_ack' }
21
22
  | { type: 'stop' };
@@ -5,12 +5,27 @@ import { WsConnectionState } from '../sdk/types.js';
5
5
  import { WsClient } from './ws-client.js';
6
6
  import { BufferedRawWsLog } from './raw-ws-log.js';
7
7
  import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
8
+ import { applyGameSyncDelta, type GameSyncServerMessage } from './game-sync-protocol.js';
9
+ import type { GameSyncResumeState, WsFrameMeta, WsInputFrame } from './ws-client.js';
8
10
 
9
11
  const port = parentPort!;
10
12
  const config = workerData.config as GameSyncIngressConfig;
11
13
  const packageVersion = (JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { version?: string }).version;
12
14
  const raw = config.rawLog ? new BufferedRawWsLog(config.rawLog.path, config.rawLog.options) : undefined;
13
- const pending = new Map<string, { seq: number; bytes: number; receivedAtMs: number }>();
15
+ interface CachedFrame {
16
+ type: 'cached_frame';
17
+ messages: Buffer[];
18
+ bytes: number;
19
+ meta: WsFrameMeta;
20
+ eventIds: Set<string>;
21
+ }
22
+ const pending = new Map<string, CachedFrame>();
23
+ const inFlight = new Map<string, CachedFrame>();
24
+ let deliveryQueue: Array<IngressEvent | CachedFrame | undefined> = [];
25
+ let deliveryHead = 0;
26
+ let unappliedMessages: Buffer[] = [];
27
+ let unappliedBytes = 0;
28
+ let deliveryBaseline: GameSyncResumeState | undefined = config.resumeState;
14
29
  let pendingBytes = 0;
15
30
  let stopped = false;
16
31
  let overloaded = false;
@@ -19,6 +34,7 @@ let telemetryPending = false;
19
34
  let lastLiveness = 0;
20
35
  let lastReceivedSeq = 0;
21
36
  let acceptedSeq = config.resumeState?.seq ?? 0;
37
+ let bufferedSeq = config.resumeState?.seq ?? 0;
22
38
  let ackSubmittedSeq = 0;
23
39
  let receivedFrames = 0;
24
40
  let pingCount = 0;
@@ -27,18 +43,20 @@ let pongErrors = 0;
27
43
  let lastPingAt = 0;
28
44
  let lastPongWrittenAt = 0;
29
45
  let maxPongWriteMs = 0;
30
- let maxAckHandoffMs = 0;
46
+ let maxSourceConsumptionDelayMs = 0;
31
47
  let overloadCount = 0;
32
48
  let maxOutstanding = 0;
49
+ let maxBufferedBytes = 0;
33
50
  const delay = monitorEventLoopDelay({ resolution: 20 });
34
51
  delay.enable();
35
52
  const post = (message: IngressEvent): void => { if (!stopped || message.type === 'stopped') port.postMessage(message); };
36
53
  const client = new WsClient({
37
54
  url: config.url, apiKey: config.apiKey, resumeState: config.resumeState,
38
55
  reconnectMaxMs: config.reconnectMaxMs, ackIntervalMs: config.ackIntervalMs,
39
- maxPayloadBytes: config.maxPendingBytes, rawMessageSink: raw,
56
+ maxPayloadBytes: 32 * 1024 * 1024, rawMessageSink: raw,
40
57
  handshakeTimeoutMs: 10_000,
41
- reconnectReady: () => pending.size === 0,
58
+ retainInputMessage: retainMessage,
59
+ discardUnappliedMessages,
42
60
  diagnostic: (name, attributes) => {
43
61
  if (name === 'runtime.ws.ping_received') { pingCount++; lastPingAt = Number(attributes.received_at_ms); }
44
62
  if (name === 'runtime.ws.pong_written') {
@@ -55,14 +73,16 @@ function telemetry(force = false): void {
55
73
  telemetryPending = true;
56
74
  post({ type: 'telemetry', attributes: {
57
75
  sampled_at_ms: Date.now(), connection_id: client.connectionId,
58
- implementation: 'isolated_gamesync_v1', package_version: packageVersion, node_version: process.version, thread_id: threadId,
76
+ implementation: 'buffered_gamesync_v2', package_version: packageVersion, node_version: process.version, thread_id: threadId,
59
77
  last_liveness_at_ms: lastLiveness, received_frames: receivedFrames,
60
- received_seq: lastReceivedSeq, source_accepted_seq: acceptedSeq, ack_submitted_seq: ackSubmittedSeq,
78
+ received_seq: lastReceivedSeq, buffered_seq: bufferedSeq, source_accepted_seq: acceptedSeq, ack_submitted_seq: ackSubmittedSeq,
61
79
  outstanding_frames: pending.size, outstanding_bytes: pendingBytes, max_outstanding_frames: maxOutstanding,
62
- max_pending_frames: config.maxPendingFrames, max_pending_bytes: config.maxPendingBytes,
80
+ in_flight_frames: inFlight.size, max_in_flight_frames: config.maxInFlightFrames,
81
+ buffered_raw_bytes: pendingBytes, max_buffered_raw_bytes: maxBufferedBytes,
82
+ unapplied_raw_bytes: unappliedBytes, max_pending_bytes: config.maxPendingBytes,
63
83
  received_ping_count: pingCount, written_pong_count: pongCount, pong_write_errors: pongErrors,
64
84
  last_ping_received_at_ms: lastPingAt, last_pong_written_at_ms: lastPongWrittenAt,
65
- max_pong_write_ms: maxPongWriteMs, max_source_ack_handoff_ms: maxAckHandoffMs,
85
+ max_pong_write_ms: maxPongWriteMs, max_source_consumption_delay_ms: maxSourceConsumptionDelayMs,
66
86
  overload_count: overloadCount, worker_event_loop_delay_p95_ms: delay.percentile(95) / 1e6,
67
87
  worker_event_loop_delay_max_ms: delay.max / 1e6, worker_heap_used_bytes: process.memoryUsage().heapUsed,
68
88
  ...(raw ? { raw_log: raw.stats() } : {}),
@@ -70,6 +90,103 @@ function telemetry(force = false): void {
70
90
  delay.reset();
71
91
  }
72
92
 
93
+ function discardUnappliedMessages(): void {
94
+ pendingBytes -= unappliedBytes;
95
+ unappliedBytes = 0;
96
+ unappliedMessages = [];
97
+ }
98
+
99
+ function retainMessage(message: string): boolean {
100
+ if (stopped || overloaded) return false;
101
+ const bytes = Buffer.byteLength(message);
102
+ if (pendingBytes + bytes > config.maxPendingBytes) {
103
+ overloadCount++;
104
+ overloaded = true;
105
+ // This message has not been applied or ACKed. Retained completed frames
106
+ // survive; an incomplete replay can be retried from the buffered baseline.
107
+ discardUnappliedMessages();
108
+ client.disconnect();
109
+ enqueue({ type: 'close', connectionId: client.connectionId, info: {
110
+ code: 1013, reason: 'CCL_INGRESS_BACKLOG_LIMIT', wasClean: false,
111
+ } });
112
+ enqueue({ type: 'state', state: WsConnectionState.Reconnecting });
113
+ telemetry(true);
114
+ reconnectWhenDrained();
115
+ return false;
116
+ }
117
+ unappliedMessages.push(Buffer.from(message));
118
+ unappliedBytes += bytes;
119
+ pendingBytes += bytes;
120
+ maxBufferedBytes = Math.max(maxBufferedBytes, pendingBytes);
121
+ return true;
122
+ }
123
+
124
+ /** Preserve lifecycle ordering across reconnects while old frames await Source. */
125
+ function enqueue(message: IngressEvent | CachedFrame): void {
126
+ deliveryQueue.push(message);
127
+ pump();
128
+ }
129
+
130
+ function materialize(cached: CachedFrame): WsInputFrame {
131
+ const events: Record<string, any>[] = [];
132
+ const emitted = new Set<string>();
133
+ for (const bytes of cached.messages) {
134
+ const message = JSON.parse(bytes.toString('utf8')) as GameSyncServerMessage;
135
+ if (message.type === 'game.sync.snapshot') {
136
+ deliveryBaseline = {
137
+ gameId: message.data.game_id, seq: message.data.seq, tick: message.data.tick,
138
+ locale: message.data.locale, state: message.data.state,
139
+ };
140
+ } else if (message.type === 'game.sync.update') {
141
+ if (!deliveryBaseline || message.data.game_id !== deliveryBaseline.gameId
142
+ || message.data.seq !== deliveryBaseline.seq + 1) throw new Error('INGRESS_CACHE_SEQUENCE_INVALID');
143
+ deliveryBaseline = { ...deliveryBaseline, seq: message.data.seq, tick: message.data.tick,
144
+ state: applyGameSyncDelta(deliveryBaseline.state, message.data.state_delta) };
145
+ } else if (message.type === 'game.sync.resume') {
146
+ if (!deliveryBaseline || deliveryBaseline.seq !== message.data.to_seq) throw new Error('INGRESS_CACHE_RESUME_INVALID');
147
+ deliveryBaseline = { ...deliveryBaseline, tick: message.data.tick };
148
+ }
149
+ if (message.type === 'game.sync.snapshot' || message.type === 'game.sync.update') {
150
+ for (const event of message.data.events ?? []) {
151
+ const id = String(event.event_id);
152
+ if (cached.eventIds.has(id) && !emitted.has(id)) { emitted.add(id); events.push(event); }
153
+ }
154
+ }
155
+ }
156
+ if (!deliveryBaseline) throw new Error('INGRESS_CACHE_BASELINE_MISSING');
157
+ return {
158
+ kind: 'state',
159
+ state: { ...structuredClone(deliveryBaseline.state), game_id: deliveryBaseline.gameId, tick: deliveryBaseline.tick },
160
+ events, meta: { ...cached.meta, ingress: {
161
+ ...cached.meta.ingress!, workerPostedAtMs: Date.now(),
162
+ outstandingFrames: pending.size, outstandingBytes: pendingBytes,
163
+ } },
164
+ };
165
+ }
166
+
167
+ function pump(): void {
168
+ if (stopped) return;
169
+ while (deliveryHead < deliveryQueue.length) {
170
+ const message = deliveryQueue[deliveryHead]!;
171
+ if (message.type === 'cached_frame') {
172
+ if (inFlight.size >= config.maxInFlightFrames) break;
173
+ const frame = materialize(message);
174
+ inFlight.set(message.meta.ackToken, message);
175
+ post({ type: 'frame', frame });
176
+ } else {
177
+ // In particular, do not change the Source connection id ahead of its
178
+ // pending frames; transport reconnect itself does not wait for this queue.
179
+ if (inFlight.size) break;
180
+ post(message);
181
+ }
182
+ deliveryQueue[deliveryHead++] = undefined;
183
+ }
184
+ if (deliveryHead > 1024 && deliveryHead * 2 > deliveryQueue.length) {
185
+ deliveryQueue = deliveryQueue.slice(deliveryHead);
186
+ deliveryHead = 0;
187
+ }
188
+ }
189
+
73
190
  function reconnectWhenDrained(): void {
74
191
  if (!overloaded || pending.size || restartTimer || stopped) return;
75
192
  restartTimer = setTimeout(() => {
@@ -80,57 +197,55 @@ function reconnectWhenDrained(): void {
80
197
  }, 1000);
81
198
  }
82
199
 
83
- client.onStateChange(state => post({ type: 'state', state }));
200
+ client.onStateChange(state => enqueue({ type: 'state', state }));
84
201
  client.onConnectionOpened(connectionId => {
85
202
  // Socket generation is deliberately separate from monotonically ordered source seq.
86
- post({ type: 'opened', connectionId });
203
+ enqueue({ type: 'opened', connectionId });
87
204
  });
88
205
  client.onLiveness((_connection, atMs) => { lastLiveness = atMs; });
89
- client.onDisconnect(info => post({ type: 'close', connectionId: client.connectionId, info }));
206
+ client.onDisconnect(info => {
207
+ discardUnappliedMessages();
208
+ enqueue({ type: 'close', connectionId: client.connectionId, info });
209
+ });
90
210
  const reportedProtocolErrors = new Set<string>();
91
211
  client.onProtocolError(info => {
92
212
  if (reportedProtocolErrors.has(info.reason)) return;
93
213
  reportedProtocolErrors.add(info.reason);
94
- post({ type: 'protocol', info });
214
+ enqueue({ type: 'protocol', info });
95
215
  });
96
- client.onRecoveryStarted(info => post({ type: 'recovery', info }));
216
+ client.onRecoveryStarted(info => enqueue({ type: 'recovery', info }));
97
217
  client.onInputFrame(frame => {
98
218
  if (stopped || overloaded) return;
99
219
  receivedFrames++;
100
220
  lastReceivedSeq = Number(frame.meta.sourceSeq);
101
- const bytes = Buffer.byteLength(JSON.stringify(frame));
102
- if (pending.size >= config.maxPendingFrames || pendingBytes + bytes > config.maxPendingBytes) {
103
- overloadCount++;
104
- overloaded = true;
105
- client.disconnect();
106
- post({ type: 'close', connectionId: client.connectionId, info: {
107
- code: 1013, reason: 'CCL_INGRESS_BACKLOG_LIMIT', wasClean: false,
108
- } });
109
- post({ type: 'state', state: WsConnectionState.Reconnecting });
110
- telemetry(true);
111
- reconnectWhenDrained();
112
- return;
113
- }
114
- pending.set(frame.meta.ackToken, { seq: Number(frame.meta.sourceSeq), bytes, receivedAtMs: Date.parse(frame.meta.receivedAt) });
115
- pendingBytes += bytes;
116
- maxOutstanding = Math.max(maxOutstanding, pending.size);
117
- frame.meta.ingress = {
118
- ...frame.meta.ingress!, workerPostedAtMs: Date.now(), outstandingFrames: pending.size, outstandingBytes: pendingBytes,
221
+ const cached: CachedFrame = {
222
+ type: 'cached_frame', messages: unappliedMessages, bytes: unappliedBytes,
223
+ meta: frame.meta, eventIds: new Set(frame.events.map(event => String(event.event_id))),
119
224
  };
120
- post({ type: 'frame', frame });
225
+ unappliedMessages = [];
226
+ unappliedBytes = 0;
227
+ pending.set(frame.meta.ackToken, cached);
228
+ maxOutstanding = Math.max(maxOutstanding, pending.size);
229
+ // The entire validated input is now retained independently of the Owner.
230
+ client.acknowledge(frame.meta.ackToken, true);
231
+ bufferedSeq = Math.max(bufferedSeq, Number(frame.meta.sourceSeq));
232
+ enqueue(cached);
121
233
  });
122
234
 
123
235
  const timer = setInterval(() => { reportedProtocolErrors.clear(); telemetry(); }, 5000);
124
236
  timer.unref();
125
237
  port.on('message', (message: IngressCommand) => {
126
238
  if (stopped) return;
127
- if (message.type === 'ack') {
128
- const entry = pending.get(message.token);
239
+ if (message.type === 'consumed') {
240
+ const entry = inFlight.get(message.token);
129
241
  if (!entry) return;
130
- client.acknowledge(message.token, message.immediate);
131
- acceptedSeq = Math.max(acceptedSeq, entry.seq);
132
- maxAckHandoffMs = Math.max(maxAckHandoffMs, Date.now() - entry.receivedAtMs);
133
- for (const [token, item] of pending) if (item.seq <= entry.seq) { pending.delete(token); pendingBytes -= item.bytes; }
242
+ acceptedSeq = Math.max(acceptedSeq, Number(entry.meta.sourceSeq));
243
+ maxSourceConsumptionDelayMs = Math.max(maxSourceConsumptionDelayMs, Date.now() - Date.parse(entry.meta.receivedAt));
244
+ for (const [token, item] of inFlight) {
245
+ inFlight.delete(token); pending.delete(token); pendingBytes -= item.bytes;
246
+ if (token === message.token) break;
247
+ }
248
+ pump();
134
249
  reconnectWhenDrained();
135
250
  } else if (message.type === 'report') {
136
251
  try { client.reportPerceptions(message.perceptions); } finally { post({ type: 'report_done' }); }
@@ -5,9 +5,10 @@ import { gameSyncPerceptionReportMessage, type GameSyncPerceptionReport } from '
5
5
  import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
6
6
  import type { GameSyncResumeState, WsClient, WsClientConfig, WsInputFrame, WsCloseInfo, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
7
7
 
8
- export interface ThreadedWsClientConfig extends Omit<WsClientConfig, 'rawMessageSink' | 'reconnectReady'> {
8
+ export interface ThreadedWsClientConfig extends Omit<WsClientConfig, 'rawMessageSink' | 'reconnectReady' | 'retainInputMessage' | 'discardUnappliedMessages'> {
9
9
  rawLog?: GameSyncIngressConfig['rawLog'];
10
- maxPendingFrames?: number;
10
+ /** Complete-frame delivery credits. Raw reception/ACK continues when these are exhausted. */
11
+ maxInFlightFrames?: number;
11
12
  maxPendingBytes?: number;
12
13
  transportGeneration?: number;
13
14
  }
@@ -32,8 +33,8 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
32
33
  private startupTimer?: ReturnType<typeof setTimeout>;
33
34
 
34
35
  constructor(private readonly config: ThreadedWsClientConfig) {
35
- const frames = config.maxPendingFrames ?? 10;
36
- const bytes = config.maxPendingBytes ?? 8 * 1024 * 1024;
36
+ const frames = config.maxInFlightFrames ?? 10;
37
+ const bytes = config.maxPendingBytes ?? 32 * 1024 * 1024;
37
38
  if (!Number.isSafeInteger(frames) || frames < 1 || frames > 1000) throw new Error('GAME_SYNC_FRAME_LIMIT_INVALID');
38
39
  if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > 32 * 1024 * 1024) throw new Error('GAME_SYNC_BYTE_LIMIT_INVALID');
39
40
  this.committed = config.resumeState ? structuredClone(config.resumeState) : undefined;
@@ -56,8 +57,8 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
56
57
  const config: GameSyncIngressConfig = {
57
58
  url: this.config.url, apiKey: this.config.apiKey, resumeState: this.committed,
58
59
  reconnectMaxMs: this.config.reconnectMaxMs, ackIntervalMs: this.config.ackIntervalMs,
59
- maxPendingFrames: this.config.maxPendingFrames ?? 10,
60
- maxPendingBytes: this.config.maxPendingBytes ?? 8 * 1024 * 1024,
60
+ maxInFlightFrames: this.config.maxInFlightFrames ?? 10,
61
+ maxPendingBytes: this.config.maxPendingBytes ?? 32 * 1024 * 1024,
61
62
  rawLog: this.config.rawLog,
62
63
  };
63
64
  try {
@@ -130,7 +131,7 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
130
131
  }
131
132
  }
132
133
 
133
- acknowledge(token: string, immediate = false): void {
134
+ acknowledge(token: string, _immediate = false): void {
134
135
  const frame = this.pending.get(token);
135
136
  if (this.stopped || !frame || frame.meta.connectionId !== this.connectionIdValue) return;
136
137
  const seq = Number(frame.meta.sourceSeq);
@@ -138,8 +139,15 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
138
139
  const { game_id: _gameId, tick: _tick, ...state } = frame.state;
139
140
  this.committed = { gameId: frame.meta.gameId, seq, tick: frame.meta.domainTick, locale: frame.meta.locale ?? 'zh-CN', state: structuredClone(state) };
140
141
  }
141
- for (const [key, pending] of this.pending) if (Number(pending.meta.sourceSeq) <= seq) this.pending.delete(key);
142
- this.post({ type: 'ack', token, immediate });
142
+ // A snapshot/resume barrier can share a seq with an earlier frame. Only
143
+ // consume the delivered prefix through this token, not later same-seq input.
144
+ for (const key of this.pending.keys()) {
145
+ this.pending.delete(key);
146
+ if (key === token) break;
147
+ }
148
+ // Source consumption releases delivery credits/cache, not the network ACK.
149
+ // Keep this baseline Source-owned for recovery if the ingress Worker is lost.
150
+ this.post({ type: 'consumed', token });
143
151
  }
144
152
 
145
153
  reportPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean {
@@ -34,8 +34,12 @@ export interface WsClientConfig {
34
34
  resumeState?: GameSyncResumeState;
35
35
  maxPayloadBytes?: number;
36
36
  handshakeTimeoutMs?: number;
37
- /** The isolated ingress may wait for already-delivered Source applications before reconnecting. */
37
+ /** Optional reconnect gate for consumers that cannot retain input independently. */
38
38
  reconnectReady?: () => boolean;
39
+ /** Optional ingress-owned raw cache. Reserve before applying/ACKing a valid message. */
40
+ retainInputMessage?: (raw: string) => boolean;
41
+ /** Release only an incomplete replay; already dispatched frames remain owned by the cache. */
42
+ discardUnappliedMessages?: () => void;
39
43
  diagnostic?: (name: string, attributes: Record<string, unknown>, severity?: 'debug' | 'info' | 'warn') => void;
40
44
  }
41
45
 
@@ -133,7 +137,7 @@ export class WsClient {
133
137
  private connectionIdValue = '';
134
138
  private lastPongAtValue: string | null = null;
135
139
  private baseline: GameSyncResumeState | null;
136
- /** Last baseline durably accepted by Source, and therefore safe to resume from. */
140
+ /** Last baseline accepted by the consumer (Source or the ingress memory cache). */
137
141
  private committedBaseline: GameSyncResumeState | null;
138
142
  private recovering = false;
139
143
  private awaitingSnapshot = false;
@@ -191,8 +195,8 @@ export class WsClient {
191
195
  }
192
196
 
193
197
  /**
194
- * Advance the resume/ACK watermark only after Source has durably accepted the
195
- * matching frame. Reading a socket frame is not sufficient authority.
198
+ * Advance the resume/ACK watermark after the consumer has accepted the frame.
199
+ * The threaded consumer retains it in memory before ACK; this is not a disk flush.
196
200
  */
197
201
  acknowledge(ackToken: string, immediate = false): void {
198
202
  if (!ackToken) return;
@@ -236,12 +240,13 @@ export class WsClient {
236
240
 
237
241
  private openSocket(): Promise<void> {
238
242
  return new Promise((resolve, reject) => {
239
- // Discard frames that were read but never committed by Source. The
240
- // server must replay them from the durable watermark.
243
+ // Discard input not accepted by the consumer. The threaded consumer
244
+ // keeps ACKed raw input across socket reconnects in its own memory cache.
241
245
  this.baseline = this.committedBaseline
242
246
  ? structuredClone(this.committedBaseline)
243
247
  : null;
244
248
  this.clearPendingApplication();
249
+ this.config.discardUnappliedMessages?.();
245
250
  this.connectionIdValue = randomUUID();
246
251
  this.recovering = this.baseline !== null;
247
252
  this.awaitingSnapshot = false;
@@ -301,7 +306,7 @@ export class WsClient {
301
306
  return;
302
307
  }
303
308
  try {
304
- this.handleMessage(parsed);
309
+ this.handleMessage(parsed, raw);
305
310
  } catch (error) {
306
311
  this.reportProtocolError('invalid_game_sync_message', {
307
312
  error: error instanceof Error ? error.message : String(error),
@@ -329,9 +334,11 @@ export class WsClient {
329
334
  });
330
335
  }
331
336
 
332
- private handleMessage(raw: unknown): void {
337
+ private handleMessage(raw: unknown, wire = JSON.stringify(raw)): void {
333
338
  const message = parseGameSyncMessage(raw);
334
339
  if (message.type === 'game.sync.snapshot') {
340
+ this.config.discardUnappliedMessages?.();
341
+ if (this.config.retainInputMessage?.(wire) === false) return;
335
342
  const wasRecovering = this.recovering;
336
343
  const previousGameId = this.baseline?.gameId;
337
344
  if (previousGameId !== undefined && previousGameId !== message.data.game_id) {
@@ -387,6 +394,7 @@ export class WsClient {
387
394
  this.requestResync('seq_gap', expectedSeq, message.data.seq);
388
395
  return;
389
396
  }
397
+ if (this.config.retainInputMessage?.(wire) === false) return;
390
398
  this.baseline = {
391
399
  ...baseline,
392
400
  seq: message.data.seq,
@@ -433,6 +441,7 @@ export class WsClient {
433
441
  this.requestResync('invalid_resume', baseline ? baseline.seq + 1 : undefined, message.data.to_seq);
434
442
  return;
435
443
  }
444
+ if (this.config.retainInputMessage?.(wire) === false) return;
436
445
  const events = this.recoveryEvents;
437
446
  const replayedEventCount = events.length;
438
447
  this.recoveryEvents = [];
@@ -473,6 +482,7 @@ export class WsClient {
473
482
 
474
483
  private requestResync(reason: string, expectedSeq?: number, receivedSeq?: number): void {
475
484
  if (this.awaitingSnapshot) return;
485
+ this.config.discardUnappliedMessages?.();
476
486
  this.awaitingSnapshot = true;
477
487
  this.recovering = true;
478
488
  this.recoveryStartSeq = this.baseline?.seq ?? null;
@@ -38,6 +38,8 @@ export type {
38
38
 
39
39
  /** How Runtime schedules pure decision computation. Effect commit is ordered in both modes. */
40
40
  export type BehaviorExecution = 'parallel' | 'serial';
41
+ /** Opt-in inheritance of the highest successfully completed epoch's instance data. */
42
+ export type BehaviorStateMode = 'isolated' | 'snapshot';
41
43
 
42
44
  interface BehaviorInputFieldBase {
43
45
  /** Stable key used in BehaviorInput.input. */
@@ -250,6 +252,7 @@ export interface BehaviorRuntimeDefaults {
250
252
 
251
253
  /** One statically readable author contract for long, short, and reflex Behaviors. */
252
254
  export interface ClawclawBehaviorManifest {
255
+ readonly stateMode?: BehaviorStateMode;
253
256
  readonly apiVersion: typeof BEHAVIOR_PLUGIN_API_VERSION;
254
257
  readonly id: string;
255
258
  readonly name: string;