@myclaw163/clawclaw-cli 0.8.18 → 0.8.20

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 (33) hide show
  1. package/docs/configuration.md +15 -1
  2. package/package.json +1 -1
  3. package/skills/clawclaw/SKILL.md +3 -1
  4. package/skills/clawclaw/references/BEHAVIORS.md +2 -2
  5. package/skills/clawclaw/references/COMMANDS.md +2 -0
  6. package/src/commands/behavior.ts +3 -0
  7. package/src/commands/load.ts +14 -9
  8. package/src/commands/perception.ts +5 -1
  9. package/src/commands/persona.ts +29 -9
  10. package/src/lib/agent-workspace-runtime.ts +33 -4
  11. package/src/lib/capability-cloud-sync.ts +3 -3
  12. package/src/lib/capability-discovery.ts +6 -1
  13. package/src/lib/capability-operation-name.ts +14 -0
  14. package/src/lib/capability-workspace.ts +14 -1
  15. package/src/lib/persona.ts +13 -2
  16. package/src/runtime/clawclaw/owner.ts +1 -0
  17. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +4 -2
  18. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +3 -0
  19. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +1 -1
  20. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +10 -0
  21. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +10 -3
  22. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +1 -1
  23. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +5 -6
  24. package/src/runtime/clawclaw/runtime.ts +8 -0
  25. package/src/runtime/framework/events/memory-event-repository.ts +24 -1
  26. package/src/runtime/framework/events/runtime-resume.ts +20 -0
  27. package/src/runtime/framework/events/sqlite-event-repository.ts +32 -8
  28. package/src/runtime/framework/participation-manager.ts +10 -1
  29. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +20 -1
  30. package/src/runtime/framework/persistence/memory-first-persistence.ts +116 -13
  31. package/src/runtime/framework/plugins/runtime-input-journal.ts +13 -8
  32. package/src/runtime/framework/runtime.ts +7 -7
  33. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +11 -8
@@ -93,6 +93,20 @@ $env:CLAWCLAW_ENABLE_CLAUDE_CHANNELS = '1'
93
93
 
94
94
  `allow_upload: true` 目前只保存未来上传的用户同意,并把本地有效采集级别至少提升到 `telemetry`;当前版本尚未实现网络上传,不会因为打开它而发起请求。本地 JSONL 不是可直接上传的数据集;未来上传器必须另做全局字段白名单和投影,不能直接读取并发送这些文件。
95
95
 
96
+ #### 启动恢复与内存诊断
97
+
98
+ 默认 Runtime 不再将账号三个历史库中的全部业务记录加载进内存。新参与只保留必要的旧会话元数据和数据库全局序号;恢复已有参与时,事件与投递记录按可恢复的当前 session 加载,State History、epoch、插件进度/结果/State 按实际复用的当前 segment 加载。同一房间 session 恢复到新 segment 时,不加载上一个游戏 segment 的 State。旧数据不删除,仍能从 SQLite 导出复盘。
99
+
100
+ 跨 session 的 source Event ID 去重仍有效:提交 Event 时通过索引按需检查冷库中的身份冲突,只将实际命中的记录及其原有投递状态引入内存,不扫描或复制整个旧 Event Ledger。当前活动 segment 的完整恢复历史,以及当前 session 的事件投递记录仍可能随运行增长;本修复不是统一的内存容量上限,也不是“消费过就全部删除”。
101
+
102
+ `telemetry` 和 `full` 记录以下脱敏诊断,不包含 State/Event 正文或数据库路径:
103
+
104
+ - `runtime.persistence.hydration`:`started`、`selected`、`events_loaded`、`history_loaded`、`input_loaded`、`completed`(失败时 `failed`)阶段;包含累计启动耗时、数据库/WAL 文件字节数、恢复选择、已加载记录数,以及采样时的进程 RSS、Owner JS 堆、external、ArrayBuffers、V8 堆限制。阶段内存是离散采样,不能称为真实瞬时峰值;库文件大小也不等于 JS 对象占用。
105
+ - `runtime.persistence.worker_memory`:持久化 Worker 启动后约每 5 秒报告线程 ID、采样时间、已用/已分配 JS 堆、external、ArrayBuffers 和堆限制;没有将进程级 RSS 冒充 Worker 独占内存。
106
+ - `full` 的 `runtime.diagnostics.sample.persistence` 同时提供异步持久化健康状态及最近一次 Worker 内存样本;判断样本新鲜度时检查其 `sampled_at_ms`。原有 `retained_records` 继续报告各内存仓库保留数量。
107
+
108
+ 上述数据用于区分“启动加载旧历史”“Owner 内存增长”“计算/持久化 Worker 内存增长”和“写盘积压”。它们不是完整的对象引用图或 native/SQLite 内存归因;ArrayBuffers 已包含在 external 中,不应重复相加。
109
+
96
110
  开发者可以临时用环境变量覆盖 `level`;若 `allow_upload` 为 `true`,仍至少采集 telemetry。日志按单文件容量滚动并自动删除最旧编号文件,不需要另起清理任务:
97
111
 
98
112
  ```powershell
@@ -207,7 +221,7 @@ CCL 必须能确定音频格式才会上传。优先使用响应 `Content-Type`
207
221
 
208
222
  `ccl load`、资源管理命令或 Owner 启动只要首次读到这些旧字段,就会把迁移结果写回原文件。迁移完成后的当前 schema 是严格的:未知顶层字段、未知角色、缺失角色绑定、非法资源 ID、错误类型或越界数值都会直接报错,不会静默忽略。经常切换不同 CCL 版本时,应先备份 `user-data/gameplay.json`;旧版本若不认识 Behavior/Trigger 当前字段,不应与新版本轮流写同一个 workspace。
209
223
 
210
- 官方、第三方和纯本地能力统一使用账号 `capabilities/<type>/` 工作区,Hub immutable 版本只保存在 revision cache。主目录中的合法本地资源都会自动上传;`drafts` 不扫描、不上传。新资源第一次发现时出现在 `capabilities.selection_required`,用 `ccl capability equip` 或 `ccl capability unequip` 保存一次装配选择;资源上传成功后,同一选择会应用到新建的 Hub Workspace Item。Behavior 仍以 manifest `id` 作为 `list`、`start`、fallback 和 Trigger 绑定的稳定身份。
224
+ 官方、第三方和纯本地能力统一使用账号 `capabilities/<type>/` 工作区,Hub immutable 版本只保存在 revision cache。主目录中的合法本地资源都会自动上传;`drafts` 不扫描、不上传。新资源第一次发现时出现在 `capabilities.selection_required`,用 `ccl capability equip` 或 `ccl capability unequip` 保存一次装配选择;资源上传成功后,同一选择会应用到新建的 Hub Workspace Item。策略、感知和人设按账号、类型分配持久操作名:第一个可用名称为原始 ID,重名时依次寻找空闲的 `_1`、`_2` 后缀。已分配名称不会因取消装配、文件缺失或版本更新而重新分配给另一项。`registry.json` 的 `runtimeId` 是操作名,`declaredId` 是原始声明;Hub 同步和上传仍使用 `hub.resourceId` 及原始文件内容。`list/info/start`、装配、冲突处理、fallback 和 Trigger 配置使用操作名。同一资源本地上传后再由 Hub 装配仍沿用原操作名;不同资源即使原始 ID 相同也能并存。辅助 Skill 本轮不纳入。
211
225
 
212
226
  分角色 `fallback_behaviors` 现在表示“角色确定后立即启动的默认 long Behavior”。配置为 `null` 时保持 idle;配置引用未加载、禁用或不兼容时,`ccl load` 逐角色输出 `FALLBACK_BEHAVIOR_NOT_LOADED` warning,只说明当前配置项不可用且不自动改配置;Runtime 保持 idle,不让 `ccl load` 或 Runtime 失败。
213
227
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.8.18",
3
+ "version": "0.8.20",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: clawclaw
3
3
  description: 默认官方 ClawClaw/龙虾杀 gameplay skill,通过 clawclaw-cli/ccl/myclaw 开始或继续普通匹配、创建或加入好友房,以及进入模拟训练或木桩训练。Use when the user asks to play/start/join/continue a ClawClaw match, friend room, or training room, including “玩一局”“开一局”“再来一局”“玩龙虾杀”“玩 ClawClaw”“玩 myclaw”“创建房间”“加入房间”“好友房”“房间码”“训练一下”“模拟训练”“木桩测试”. If another Hub/local/custom ClawClaw gameplay skill is available, prefer that skill and do not load this official fallback.
4
- version: 4.8.99
4
+ version: 4.8.100
5
5
  ---
6
6
 
7
7
  # 龙虾杀(ClawClaw)
@@ -14,6 +14,8 @@ version: 4.8.99
14
14
 
15
15
  ## 1. 运行方式
16
16
 
17
+ 策略、感知和人设的本地操作名可能带 `_1`、`_2` 后缀,用于区分原始 ID 相同的不同资源。执行 list/info/start、装配、冲突选择和配置时,使用 CCL 返回的完整操作名,不自行去掉后缀、不按显示名称猜测。操作名按账号保存,取消装配后不重新编号;它不改变脚本内容或 Hub 身份。策略详情的 `declared_id` 是脚本原始 ID,`working_copy_path` 是编辑入口,`resource_id` 是 Hub 身份。辅助 Skill 暂不使用这套重名处理。
18
+
17
19
  ### 1.1 默认使用 Monitor 直推 + `ccl events` 详情
18
20
 
19
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。
@@ -46,12 +46,12 @@ Runtime 另外允许 `duration_ms` 或 `timeout_ms`,两者只能选一个,
46
46
 
47
47
  ### 修改已安装策略的源码
48
48
 
49
- 先用 `ccl behavior list` / `ccl behavior info <id>` 确认有效策略与来源;这些输出不提供编辑绝对路径。再用 `ccl behavior --help` 查看当前账号的 Behavior 主目录,用 `ccl capability list` 找到对应 `type=behavior`、`runtimeId` 的 registry 条目;Hub 来源还须匹配 `hub.resourceId` 与 `info.resource_id`。条目的 `relativePath` 相对于当前账号的 `capabilities/`,据此定位文件,不凭账号名、文件名或目录名猜测。
49
+ 先用 `ccl behavior list` / `ccl behavior info <id>` 确认有效策略与来源。`id` 是当前账号的本地操作名,重名时可能为 `xx_1`、`xx_2`;`declared_id` 保留脚本原始 ID。使用 `working_copy_path` 定位可编辑文件;`runtime_source_path` 是运行副本位置,不作为编辑入口。也可用 `ccl capability list` 查询对应 `runtimeId`、`declaredId` 和 `hub.resourceId`。不要从相同显示名称推断两项是同一资源,不要去掉后缀后再执行指令。
50
50
 
51
51
  | 账号内路径 | 用途 |
52
52
  |---|---|
53
53
  | `capabilities/behaviors/<资源目录>/xxx.ts` | Hub 策略的可编辑工作副本;准确位置以 registry 为准,fork 后目录名不一定等于当前资源 ID |
54
- | `capabilities/behaviors/xxx.ts` | 纯本地策略;已装配且同 ID 时优先于 Hub 策略 |
54
+ | `capabilities/behaviors/xxx.ts` | 本地主目录策略;与其他同原始 ID 资源通过独立操作名并存,不覆盖 Hub 条目 |
55
55
  | `hub-loadout/revisions/.../runtime/behaviors/<id>.ts` | CCL 生成的运行副本,不直接编辑 |
56
56
  | 旧 `behaviors/local/`、`local/behaviors/` 或主目录内另建的 `local/` 子目录 | 当前发现流程不扫描,不作为修改入口 |
57
57
 
@@ -6,6 +6,8 @@
6
6
 
7
7
  ## 赛前(设置)
8
8
 
9
+ 策略、感知和人设的命令参数使用 CCL 返回的本地操作名,如 `xx`、`xx_1`;不同资源同名时均可存在,名称按账号持久保存,取消装配或更新版本不重新编号。`behavior list/info` 和 `perception --list` 返回 `declared_id`、`working_copy_path`、`runtime_source_path`;`persona list` 返回操作名、原名、路径和可用的 Hub 身份。后缀不写入原脚本或 Hub。辅助 Skill 的重名规则本轮不变。
10
+
9
11
  ```bash
10
12
  ccl account register --check # 先探:本服务器是否需要邀请码 + 该用哪段固定话术;绝不建号
11
13
  ccl account register [--name <名称>] [--invite-code <邀请码>] # 邀请码是否必填由服务器决定
@@ -108,6 +108,9 @@ function sourceEntry(
108
108
  const loadable = versionCompatible && compatibilityError === undefined;
109
109
  return {
110
110
  id: source.id,
111
+ declared_id: source.declaredId ?? source.id,
112
+ working_copy_path: source.workingCopyPath ?? source.sourcePath,
113
+ runtime_source_path: source.sourcePath,
111
114
  name: source.name,
112
115
  description: source.description,
113
116
  api_version: source.apiVersion ?? null,
@@ -59,6 +59,7 @@ import {
59
59
  classifyStrategyLifecycle,
60
60
  pendingCapabilitySelections,
61
61
  registerDiscoveredCapability,
62
+ capabilityEntryForPath,
62
63
  } from '../lib/capability-workspace.js';
63
64
  import { syncCapabilitiesToCloud } from '../lib/capability-cloud-sync.js';
64
65
  import {
@@ -349,7 +350,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
349
350
  registerDiscoveredCapability(workspaceDir, profile, {
350
351
  type: 'behavior',
351
352
  path: workingPath,
352
- runtimeId: source.id,
353
+ runtimeId: source.declaredId ?? source.id,
353
354
  title: source.name,
354
355
  description: source.description,
355
356
  strategyLifecycle: classifyStrategyLifecycle(readFileSync(workingPath, 'utf8')),
@@ -380,9 +381,11 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
380
381
  for (const path of listCapabilityModuleCandidates(localBehaviorDir)) {
381
382
  if (localBehaviorSourcePaths.has(resolve(path))) continue;
382
383
  const diagnostic = diagnoseRejectedCapabilityModule('behavior', path);
383
- if (diagnostic.declaredId && disabledBehaviors.has(diagnostic.declaredId)) continue;
384
+ const operationName = capabilityEntryForPath(workspaceDir, profile, 'behavior', path)?.runtimeId ?? diagnostic.declaredId;
385
+ if (operationName && disabledBehaviors.has(operationName)) continue;
384
386
  expectedLocalBehaviors += 1;
385
- capabilityWarnings.push(warningFromStaticDiagnostic('behavior', 'local', diagnostic));
387
+ capabilityWarnings.push({ ...warningFromStaticDiagnostic('behavior', 'local', diagnostic),
388
+ ...(operationName ? { id: operationName } : {}) });
386
389
  }
387
390
  if (activeWorkspace) {
388
391
  const discoveredPaths = new Set(hubBehaviors.map(({ sourcePath }) => resolve(sourcePath)));
@@ -511,7 +514,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
511
514
  registerDiscoveredCapability(workspaceDir, profile, {
512
515
  type: 'perception',
513
516
  path: workingPath,
514
- runtimeId: source.id,
517
+ runtimeId: source.declaredId ?? source.id,
515
518
  title: source.name,
516
519
  description: source.description,
517
520
  selectedByHub: true,
@@ -544,9 +547,11 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
544
547
  for (const path of listCapabilityModuleCandidates(localPerceptionDir)) {
545
548
  if (localPerceptionSourcePaths.has(resolve(path))) continue;
546
549
  const diagnostic = diagnoseRejectedCapabilityModule('perception', path);
547
- if (diagnostic.declaredId && disabledPerceptions.has(diagnostic.declaredId)) continue;
550
+ const operationName = capabilityEntryForPath(workspaceDir, profile, 'perception', path)?.runtimeId ?? diagnostic.declaredId;
551
+ if (operationName && disabledPerceptions.has(operationName)) continue;
548
552
  expectedLocalPerceptions += 1;
549
- capabilityWarnings.push(warningFromStaticDiagnostic('perception', 'local', diagnostic));
553
+ capabilityWarnings.push({ ...warningFromStaticDiagnostic('perception', 'local', diagnostic),
554
+ ...(operationName ? { id: operationName } : {}) });
550
555
  }
551
556
  if (activeWorkspace) {
552
557
  const discoveredPaths = new Set(hubPerceptions.map(({ sourcePath }) => resolve(sourcePath)));
@@ -702,9 +707,9 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
702
707
  registerDiscoveredCapability(workspaceDir, profile, {
703
708
  type: 'persona',
704
709
  path: snapshot.persona.path,
705
- runtimeId: snapshot.persona.id ?? basename(snapshot.persona.path, extname(snapshot.persona.path)),
706
- title: snapshot.persona.id ?? basename(snapshot.persona.path, extname(snapshot.persona.path)),
707
- description: `Persona ${snapshot.persona.id ?? basename(snapshot.persona.path)}`,
710
+ runtimeId: basename(snapshot.persona.path, extname(snapshot.persona.path)),
711
+ title: basename(snapshot.persona.path, extname(snapshot.persona.path)),
712
+ description: `Persona ${basename(snapshot.persona.path)}`,
708
713
  selectedByHub: true,
709
714
  hub: {
710
715
  resourceId: hubPersonaItem.resourceId,
@@ -58,6 +58,7 @@ Perception modules:
58
58
  const workspaceDir = getWorkspaceDir();
59
59
  const profile = activeProfile(dependencies);
60
60
  ensureAccountUserDataLayout(workspaceDir, profile);
61
+ const localCapabilities = discoverLocalCapabilities(workspaceDir, profile).perceptions;
61
62
  const snapshot = filterInactiveAgentWorkspaceSnapshot(
62
63
  workspaceDir,
63
64
  profile,
@@ -67,7 +68,7 @@ Perception modules:
67
68
  ? listAgentWorkspacePerceptionSources(workspaceDir, profile, snapshot)
68
69
  : [];
69
70
  const hubIds = new Set(hub.map(({ id }) => id));
70
- const local = discoverLocalCapabilities(workspaceDir, profile).perceptions
71
+ const local = localCapabilities
71
72
  .filter(({ entry }) => !snapshot?.items.perception.some(item => item.resourceId === entry.hub?.resourceId))
72
73
  .map(({ source }) => source);
73
74
  const registered = (id: string) => Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
@@ -105,6 +106,9 @@ Perception modules:
105
106
  const disabled = new Set(config.disabled_perception_modules);
106
107
  const installed = mergeAgentWorkspacePerceptionSources(local, hub).map((source) => ({
107
108
  id: source.id,
109
+ declared_id: source.declaredId ?? source.id,
110
+ working_copy_path: source.workingCopyPath ?? source.sourcePath,
111
+ runtime_source_path: source.sourcePath,
108
112
  name: source.name,
109
113
  description: source.description,
110
114
  source: hubIds.has(source.id) ? 'hub' : 'local',
@@ -1,4 +1,5 @@
1
1
  import { Command } from 'commander';
2
+ import { existsSync } from 'node:fs';
2
3
  import { AuthStore } from '../lib/auth.js';
3
4
  import { getWorkspaceDir } from '../lib/init-command.js';
4
5
  import {
@@ -15,7 +16,7 @@ import {
15
16
  import { loadPersonaSnapshot } from '../lib/load-context.js';
16
17
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
17
18
  import { setCapabilitySelection } from '../lib/capability-workspace.js';
18
- import { readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry } from '../lib/capability-workspace.js';
19
+ import { readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry, capabilityEntryForPath, capabilityWorkspacePath } from '../lib/capability-workspace.js';
19
20
  import { selectCapability } from '../lib/capability-selection.js';
20
21
  import { HubClient } from '../lib/hub-client.js';
21
22
  import { readLocalAgentWorkspaceSnapshot } from '../lib/agent-workspace-sync.js';
@@ -42,8 +43,14 @@ export function createPersonaCommand(): Command {
42
43
  .command('list')
43
44
  .description('List local persona presets for the active account')
44
45
  .action(() => {
45
- const { directory } = context();
46
- const presets = listPersonaPresets(directory).map(({ id, name }) => ({ id, name, source: 'local' }));
46
+ const { workspaceDir, profile } = context();
47
+ discoverLocalCapabilities(workspaceDir, profile);
48
+ resolveActivePersonaFile();
49
+ const presets = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
50
+ .filter(entry => entry.type === 'persona' && existsSync(capabilityWorkspacePath(workspaceDir, profile, entry)))
51
+ .map(entry => ({ id: entry.runtimeId, name: entry.title, declared_id: entry.declaredId ?? entry.runtimeId,
52
+ source: entry.hub ? 'hub' : 'local', resource_id: entry.hub?.resourceId,
53
+ path: capabilityWorkspacePath(workspaceDir, profile, entry), selection: entry.selection }));
47
54
  console.log(JSON.stringify({ presets }, null, 2));
48
55
  });
49
56
 
@@ -68,11 +75,12 @@ export function createPersonaCommand(): Command {
68
75
  const { directory, workspaceDir, profile } = context();
69
76
  const created = createPersonaPreset(name, directory);
70
77
  discoverLocalCapabilities(workspaceDir, profile);
71
- await selectCapability(workspaceDir, profile, 'persona', created.id, true);
72
- writePersonaSelection(workspaceDir, profile, { source: 'local', id: created.id });
78
+ const operationName = capabilityEntryForPath(workspaceDir, profile, 'persona', created.path)!.runtimeId;
79
+ await selectCapability(workspaceDir, profile, 'persona', operationName, true);
80
+ writePersonaSelection(workspaceDir, profile, { source: 'local', id: operationName });
73
81
  console.log(JSON.stringify({
74
82
  path: created.path,
75
- preset: { id: created.id, name: created.name, source: 'local' },
83
+ preset: { id: operationName, name: created.name, source: 'local' },
76
84
  }, null, 2));
77
85
  });
78
86
 
@@ -81,17 +89,29 @@ export function createPersonaCommand(): Command {
81
89
  .description('Select an account-local Persona preset')
82
90
  .action(async (presetName: string) => {
83
91
  const { directory, workspaceDir, profile } = context();
92
+ discoverLocalCapabilities(workspaceDir, profile);
93
+ resolveActivePersonaFile();
94
+ const named = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
95
+ .find(entry => entry.type === 'persona' && entry.runtimeId === presetName);
96
+ if (named) {
97
+ const entry = await selectCapability(workspaceDir, profile, 'persona', named.runtimeId, true);
98
+ writePersonaSelection(workspaceDir, profile, entry.hub ? { source: 'hub' } : { source: 'local', id: entry.runtimeId });
99
+ console.log(JSON.stringify({ path: capabilityWorkspacePath(workspaceDir, profile, entry),
100
+ preset: { id: entry.runtimeId, name: entry.title, source: entry.hub ? 'hub' : 'local' } }, null, 2));
101
+ return;
102
+ }
84
103
  const found = findPersonaPreset(presetName, directory);
85
104
  if (!found) {
86
105
  const available = listPersonaPresets(directory).map(p => p.name).join(', ') || 'none';
87
106
  throw new Error(`Persona preset "${presetName}" not found. Available: ${available}`);
88
107
  }
89
108
  discoverLocalCapabilities(workspaceDir, profile);
90
- const entry = await selectCapability(workspaceDir, profile, 'persona', found.id, true);
91
- writePersonaSelection(workspaceDir, profile, entry.hub ? { source: 'hub' } : { source: 'local', id: found.id });
109
+ const operationName = capabilityEntryForPath(workspaceDir, profile, 'persona', found.path)!.runtimeId;
110
+ const entry = await selectCapability(workspaceDir, profile, 'persona', operationName, true);
111
+ writePersonaSelection(workspaceDir, profile, entry.hub ? { source: 'hub' } : { source: 'local', id: entry.runtimeId });
92
112
  console.log(JSON.stringify({
93
113
  path: found.path,
94
- preset: { id: found.id, name: found.name, source: 'local' },
114
+ preset: { id: entry.runtimeId, name: found.name, source: 'local' },
95
115
  message: `Persona "${found.name}" (local) selected for the active account.`,
96
116
  }, null, 2));
97
117
  });
@@ -1,12 +1,16 @@
1
1
  import { existsSync, realpathSync } from 'node:fs';
2
- import { join, resolve } from 'node:path';
2
+ import { join, resolve, basename } from 'node:path';
3
3
  import type { AuthProfile } from './auth.js';
4
4
  import {
5
5
  localAgentWorkspaceSnapshotRoot,
6
6
  readLocalAgentWorkspaceSnapshot,
7
7
  resolveLocalAgentWorkspacePath,
8
+ resolveLocalAgentWorkspaceWorkingCopyPath,
8
9
  type LocalAgentWorkspaceSnapshot,
9
10
  } from './agent-workspace-sync.js';
11
+ import { registerDiscoveredCapability } from './capability-workspace.js';
12
+ import { behaviorOperationName, perceptionOperationName } from './capability-operation-name.js';
13
+ import { getUserDataAccountCapabilitiesDir } from './user-data.js';
10
14
  import {
11
15
  listClawclawBehaviorSources,
12
16
  type ResolvedClawclawBehaviorSource,
@@ -84,7 +88,7 @@ export function listAgentWorkspaceBehaviorSources(
84
88
  && item.resolution !== 'local_modified'
85
89
  && item.resolution !== 'concurrent_difference'
86
90
  && item.resolution !== 'local_origin_unrecognized';
87
- return {
91
+ const managed = {
88
92
  ...source,
89
93
  ...(trusted ? { trustedSourceSha256: item.sourceFiles[0]!.sha256 } : {}),
90
94
  management: {
@@ -101,6 +105,17 @@ export function listAgentWorkspaceBehaviorSources(
101
105
  ...(item.hub ? { ownerName: item.hub.ownerName } : {}),
102
106
  },
103
107
  } satisfies ManagedClawclawBehaviorSource;
108
+ const workingCopyPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item)
109
+ ?? join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'behaviors', item.resourceId,
110
+ item.sourceFiles[0]?.relativePath ?? basename(source.sourcePath));
111
+ const entry = registerDiscoveredCapability(workspaceDir, profile, {
112
+ type: 'behavior', path: workingCopyPath, runtimeId: source.id,
113
+ title: source.name, description: source.description, selectedByHub: true,
114
+ hub: { resourceId: item.resourceId, versionId: item.versionId,
115
+ workspaceItemId: item.workspaceItemId, publisher: item.hub?.publisher ?? 'community',
116
+ baseSha256: item.sourceFiles[0]?.sha256 },
117
+ });
118
+ return behaviorOperationName({ ...managed, workingCopyPath }, entry);
104
119
  });
105
120
  assertUniqueBehaviorIds(sources, 'hub');
106
121
  return sources;
@@ -118,12 +133,26 @@ export function listAgentWorkspacePerceptionSources(
118
133
  .map(item => resolveLocalAgentWorkspacePath(workspaceDir, profile, active, item.runtimeEntryPath!)));
119
134
  const sources = existsSync(root) ? listClawclawPerceptionSourcesInDirectory(root)
120
135
  .filter(source => selectedPaths.has(source.sourcePath)) : [];
136
+ const namedSources = sources.map(source => {
137
+ const item = active.items.perception.find(item => item.runtimeEntryPath
138
+ && resolveLocalAgentWorkspacePath(workspaceDir, profile, active, item.runtimeEntryPath) === source.sourcePath)!;
139
+ const workingCopyPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item)
140
+ ?? join(getUserDataAccountCapabilitiesDir(workspaceDir, profile), 'perceptions', item.resourceId,
141
+ item.sourceFiles[0]?.relativePath ?? basename(source.sourcePath));
142
+ const entry = registerDiscoveredCapability(workspaceDir, profile, {
143
+ type: 'perception', path: workingCopyPath, runtimeId: source.id, title: source.name,
144
+ description: source.description, selectedByHub: true,
145
+ hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId,
146
+ publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256 },
147
+ });
148
+ return perceptionOperationName({ ...source, workingCopyPath }, entry);
149
+ });
121
150
  const ids = new Set<string>();
122
- for (const source of sources) {
151
+ for (const source of namedSources) {
123
152
  if (ids.has(source.id)) throw new Error(`AGENT_RESOURCE_ID_CONFLICT:perception:${source.id}`);
124
153
  ids.add(source.id);
125
154
  }
126
- return sources;
155
+ return namedSources;
127
156
  }
128
157
 
129
158
  export function mergeAgentWorkspaceBehaviorSources(
@@ -201,7 +201,7 @@ function validateUploadPayload(
201
201
  }
202
202
  if (entry.type === 'behavior') {
203
203
  const source = inspectClawclawBehaviorSource(path, dirname(path));
204
- if (!source || source.id !== entry.runtimeId) {
204
+ if (!source || source.id !== (entry.declaredId ?? entry.runtimeId)) {
205
205
  throw new Error('capability_validation_failed:behavior_invalid');
206
206
  }
207
207
  return;
@@ -210,7 +210,7 @@ function validateUploadPayload(
210
210
  const resolvedPath = realpathSync(path);
211
211
  const source = listClawclawPerceptionSourcesInDirectory(dirname(path))
212
212
  .find((candidate) => realpathSync(candidate.sourcePath) === resolvedPath);
213
- if (!source || source.id !== entry.runtimeId) {
213
+ if (!source || source.id !== (entry.declaredId ?? entry.runtimeId)) {
214
214
  throw new Error('capability_validation_failed:perception_invalid');
215
215
  }
216
216
  return;
@@ -221,7 +221,7 @@ function validateUploadPayload(
221
221
  }
222
222
  return;
223
223
  }
224
- if (readSkillName(path) !== entry.runtimeId) {
224
+ if (readSkillName(path) !== (entry.declaredId ?? entry.runtimeId)) {
225
225
  throw new Error('capability_validation_failed:skill_invalid');
226
226
  }
227
227
  }
@@ -8,6 +8,7 @@ import {
8
8
  } from './capability-workspace.js';
9
9
  import { listPersonaPresets } from './persona.js';
10
10
  import { readSkillName } from './skill-host.js';
11
+ import { behaviorOperationName, perceptionOperationName } from './capability-operation-name.js';
11
12
  import {
12
13
  ensureAccountUserDataLayout,
13
14
  getUserDataAccountBehaviorsDir,
@@ -90,5 +91,9 @@ export function discoverLocalCapabilities(
90
91
  })] : [];
91
92
  })
92
93
  : [];
93
- return { behaviors, perceptions, personas, skills };
94
+ return {
95
+ behaviors: behaviors.map(({ source, entry }) => ({ source: behaviorOperationName(source, entry), entry })),
96
+ perceptions: perceptions.map(({ source, entry }) => ({ source: perceptionOperationName(source, entry), entry })),
97
+ personas, skills,
98
+ };
94
99
  }
@@ -0,0 +1,14 @@
1
+ import type { CapabilityWorkspaceEntry } from './capability-workspace.js';
2
+ import type { ResolvedClawclawBehaviorSource } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
3
+ import type { ResolvedClawclawPerceptionSource } from '../runtime/clawclaw/plugins/perception/perception-source.js';
4
+
5
+ export function behaviorOperationName<T extends ResolvedClawclawBehaviorSource>(source: T, entry: CapabilityWorkspaceEntry): T {
6
+ return { ...source, id: entry.runtimeId, declaredId: source.declaredId ?? source.id,
7
+ workingCopyPath: source.workingCopyPath ?? source.sourcePath };
8
+ }
9
+
10
+ export function perceptionOperationName<T extends ResolvedClawclawPerceptionSource>(source: T, entry: CapabilityWorkspaceEntry): T {
11
+ return { ...source, id: entry.runtimeId, declaredId: source.declaredId ?? source.id,
12
+ workingCopyPath: source.workingCopyPath ?? source.sourcePath,
13
+ manifest: { ...source.manifest, id: entry.runtimeId } };
14
+ }
@@ -43,6 +43,8 @@ export interface CapabilityWorkspaceEntry {
43
43
  origin: 'local' | 'hub';
44
44
  relativePath: string;
45
45
  runtimeId: string;
46
+ /** Original source identity. runtimeId is the account-local operation name. */
47
+ declaredId?: string;
46
48
  title: string;
47
49
  description: string;
48
50
  selection: CapabilitySelection;
@@ -141,12 +143,23 @@ export function registerDiscoveredCapability(
141
143
  const key = existingByResource?.key ?? registryKey(input.type, relativePath);
142
144
  const now = new Date().toISOString();
143
145
  const previous = registry.entries[key];
146
+ const declaredId = input.runtimeId;
147
+ const occupied = new Set(Object.values(registry.entries)
148
+ .filter(entry => entry.type === input.type && entry.key !== key).map(entry => entry.runtimeId));
149
+ let runtimeId = previous?.runtimeId ?? declaredId;
150
+ // Keep retired/unselected entries in the registry: their operation names must
151
+ // never silently point to a different script after the next load.
152
+ for (let suffix = 1; input.type !== 'skill' && occupied.has(runtimeId); suffix++) {
153
+ const tail = `_${suffix}`;
154
+ runtimeId = `${declaredId.slice(0, 255 - tail.length)}${tail}`;
155
+ }
144
156
  const entry: CapabilityWorkspaceEntry = {
145
157
  key,
146
158
  type: input.type,
147
159
  origin: previous?.origin ?? (input.selectedByHub ? 'hub' : 'local'),
148
160
  relativePath,
149
- runtimeId: input.runtimeId,
161
+ runtimeId,
162
+ declaredId,
150
163
  title: input.title?.trim() || previous?.title || input.runtimeId,
151
164
  description: input.description?.trim() || previous?.description || `${input.type} ${input.runtimeId}`,
152
165
  selection: input.selectedByHub
@@ -16,7 +16,7 @@ import {
16
16
  type LocalAgentWorkspaceSnapshot,
17
17
  } from './agent-workspace-sync.js';
18
18
  import { filterInactiveAgentWorkspaceSnapshot } from './capability-cloud-presence.js';
19
- import { capabilityEntryForPath, readCapabilityWorkspaceRegistry, capabilityWorkspacePath } from './capability-workspace.js';
19
+ import { capabilityEntryForPath, readCapabilityWorkspaceRegistry, capabilityWorkspacePath, registerDiscoveredCapability } from './capability-workspace.js';
20
20
 
21
21
  export interface PersonaPreset {
22
22
  id: string;
@@ -136,7 +136,12 @@ function hubPersona(
136
136
  working = join(getUserDataAccountHubPersonasDir(workspaceDir, profile), item.resourceId, sourcePath);
137
137
  }
138
138
  if (working && existsSync(working)) {
139
- return { path: working, source: 'hub', resourceId: item.resourceId };
139
+ const entry = registerDiscoveredCapability(workspaceDir, profile, {
140
+ type: 'persona', path: working, runtimeId: basename(working, '.md'), selectedByHub: true,
141
+ hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId,
142
+ publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256 },
143
+ });
144
+ return { path: working, source: 'hub', resourceId: item.resourceId, id: entry.runtimeId };
140
145
  }
141
146
  if (item.runtimeEntryPath) {
142
147
  const runtime = resolveLocalAgentWorkspacePath(workspaceDir, profile, snapshot!, item.runtimeEntryPath);
@@ -159,6 +164,12 @@ export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedP
159
164
  const selection = readPersonaSelection(workspaceDir, profile)
160
165
  ?? (selectedHub ? { source: 'hub' as const } : { source: 'none' as const });
161
166
  if (selection?.source === 'local') {
167
+ const selectedEntry = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
168
+ .find(entry => entry.type === 'persona' && entry.runtimeId === selection.id);
169
+ if (selectedEntry) {
170
+ if (selectedEntry.hub || selectedEntry.selection !== 'equipped') return selectedHub ?? { path: null, source: 'none' };
171
+ return { path: capabilityWorkspacePath(workspaceDir, profile, selectedEntry), source: 'local', id: selectedEntry.runtimeId };
172
+ }
162
173
  const preset = findPersonaPreset(selection.id, getUserDataAccountPersonasDir(workspaceDir, profile));
163
174
  const entry = preset ? capabilityEntryForPath(workspaceDir, profile, 'persona', preset.path) : undefined;
164
175
  if (entry?.hub) return selectedHub ?? { path: null, source: 'none' };
@@ -861,6 +861,7 @@ export async function runClawclawOwner(
861
861
  },
862
862
  scheduler: runtime?.runtimeEpochDiagnosticSnapshot(),
863
863
  retained_records: runtime?.runtimeRetainedRecordCounts(),
864
+ persistence: runtime?.runtimePersistenceDiagnostics(),
864
865
  behavior: {
865
866
  ...assembly.behavior.diagnosticSnapshot(),
866
867
  effective_source: effectiveBehavior
@@ -95,7 +95,7 @@ function assertSourceParity(
95
95
  manifest: Readonly<ClawclawBehaviorManifest>,
96
96
  source: ResolvedClawclawBehaviorSource,
97
97
  ): void {
98
- if (manifest.id !== source.id) throw new Error('behavior_id_source_mismatch');
98
+ if (manifest.id !== (source.declaredId ?? source.id)) throw new Error('behavior_id_source_mismatch');
99
99
  if (manifest.name !== source.name) throw new Error('behavior_name_source_mismatch');
100
100
  if (manifest.description !== source.description) {
101
101
  throw new Error('behavior_description_source_mismatch');
@@ -143,9 +143,11 @@ export function validateClawclawBehaviorModule(
143
143
  allowReservedProduces: source?.allowReservedProduces,
144
144
  });
145
145
  if (source) assertSourceParity(manifest, source);
146
+ const effectiveManifest = source && source.id !== manifest.id
147
+ ? Object.freeze({ ...manifest, id: source.id }) : manifest;
146
148
  return Object.freeze({
147
149
  BehaviorClass,
148
- manifest,
150
+ manifest: effectiveManifest,
149
151
  ...(source === undefined ? {} : { source }),
150
152
  });
151
153
  }
@@ -60,6 +60,9 @@ export interface ResolvedClawclawBehaviorSource {
60
60
  /** Optional so a statically identifiable legacy module remains reportable. */
61
61
  readonly apiVersion?: number;
62
62
  readonly id: string;
63
+ /** Host-assigned operation names never change the ID in the source file. */
64
+ readonly declaredId?: string;
65
+ readonly workingCopyPath?: string;
63
66
  readonly name: string;
64
67
  readonly description: string;
65
68
  readonly localizations?: ClawclawResourceLocalizations;
@@ -164,7 +164,7 @@ for (const spec of data.modules) {
164
164
  const manifest = (ModuleClass as any).manifest;
165
165
  if (
166
166
  manifest?.apiVersion !== PERCEPTION_PLUGIN_API_VERSION
167
- || manifest.id !== moduleId
167
+ || manifest.id !== (spec.declaredId ?? moduleId)
168
168
  || manifest.execution !== 'parallel_analysis'
169
169
  ) {
170
170
  throw new Error('perception_analysis_worker_manifest_mismatch');
@@ -14,6 +14,7 @@ import { assertPluginApiVersion } from '../plugin-api-version.js';
14
14
 
15
15
  export interface PerceptionThreadModuleSpec {
16
16
  readonly moduleId: string;
17
+ readonly declaredId?: string;
17
18
  readonly sourceUrl: string;
18
19
  readonly manifest: ResolvedClawclawPerceptionSource['manifest'];
19
20
  }
@@ -40,6 +41,7 @@ export class PerceptionModuleLoader {
40
41
  );
41
42
  return {
42
43
  moduleId: source.id,
44
+ declaredId: source.declaredId,
43
45
  sourceUrl: this.sourceUrl(source),
44
46
  manifest: structuredClone(source.manifest),
45
47
  };
@@ -67,6 +69,14 @@ export class PerceptionModuleLoader {
67
69
  PERCEPTION_PLUGIN_API_VERSION,
68
70
  ModuleClass.manifest?.apiVersion,
69
71
  );
72
+ if (ModuleClass.manifest?.id !== (source.declaredId ?? source.id)) {
73
+ throw new Error('perception_id_source_mismatch');
74
+ }
75
+ if (source.id !== ModuleClass.manifest!.id) {
76
+ const Aliased = class extends (ModuleClass as any) {};
77
+ Object.defineProperty(Aliased, 'manifest', { value: { ...ModuleClass.manifest, id: source.id } });
78
+ return Aliased as unknown as ClawclawPerceptionClass;
79
+ }
70
80
  return ModuleClass;
71
81
  });
72
82
  this.loaded.set(source.id, pending);
@@ -1423,9 +1423,16 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1423
1423
  this.recordModuleTimings(operation, timings);
1424
1424
  this.flushModuleTimingWindows(diagnostic);
1425
1425
  }
1426
- return results.flatMap((result) => (
1427
- result.status === 'fulfilled' ? proposals(result.value) : []
1428
- ));
1426
+ return results.flatMap((result, index) => {
1427
+ if (result.status !== 'fulfilled') return [];
1428
+ const module = modules[index]!;
1429
+ const values = proposals(result.value);
1430
+ // Aliased copies may emit the same source-level dedupe key. Keep their
1431
+ // outputs separate without renaming any public Event type or payload.
1432
+ return module.source?.declaredId && module.source.declaredId !== module.manifest.id
1433
+ ? values.map(value => ({ ...value, dedupeKey: `ccl-alias:${JSON.stringify([module.manifest.id, value.dedupeKey])}` }))
1434
+ : values;
1435
+ });
1429
1436
  }
1430
1437
 
1431
1438
  private recordModuleTimings(
@@ -95,7 +95,7 @@ function validateClass(
95
95
  if (
96
96
  !manifest
97
97
  || manifest.apiVersion !== PERCEPTION_PLUGIN_API_VERSION
98
- || manifest.id !== spec.moduleId
98
+ || manifest.id !== (spec.declaredId ?? spec.moduleId)
99
99
  || (manifest.execution ?? 'ordered_update')
100
100
  !== (spec.manifest.execution ?? 'ordered_update')
101
101
  || JSON.stringify(manifest.produces) !== JSON.stringify(spec.manifest.produces)
@@ -33,6 +33,8 @@ export interface ResolvedClawclawPerceptionSource {
33
33
  /** Literal source declaration; retained so the loader can diagnose unsupported modules. */
34
34
  readonly apiVersion?: number;
35
35
  readonly id: string;
36
+ readonly declaredId?: string;
37
+ readonly workingCopyPath?: string;
36
38
  readonly name: string;
37
39
  readonly description: string;
38
40
  readonly manifest: ClawclawPerceptionManifest;
@@ -425,20 +427,17 @@ export function listClawclawPerceptionSourcesInDirectory(
425
427
  return [];
426
428
  }
427
429
 
428
- const sources = new Map<string, ResolvedClawclawPerceptionSource>();
430
+ const sources: ResolvedClawclawPerceptionSource[] = [];
429
431
  for (const file of files) {
430
432
  try {
431
433
  const sourcePath = realpathSync(join(root, file));
432
434
  if (!pathInside(root, sourcePath) || dirname(sourcePath) !== root) continue;
433
435
  const source = parseSource(sourcePath, root);
434
436
  if (!source) continue;
435
- // Match Strategy discovery: sorted filenames are deterministic and the
436
- // last declaration wins. Duplicate entries stay recoverable and never
437
- // make Owner terminal.
438
- sources.set(source.id, source);
437
+ sources.push(source);
439
438
  } catch {}
440
439
  }
441
- return [...sources.values()];
440
+ return sources;
442
441
  }
443
442
 
444
443
  /** Lists installed workspace perception classes by reading static manifests only. */
@@ -117,6 +117,14 @@ export function createClawclawRuntime(
117
117
  eventLedgerPath: getProfileEventLedgerPath(profile),
118
118
  stateHistoryPath: getProfileStateHistoryPath(profile),
119
119
  inputJournalPath: getProfileInputJournalPath(profile),
120
+ recovery: {
121
+ account: { adapterId: CLAWCLAW_ADAPTER_ID, accountId: getRuntimeAccountId(profile) },
122
+ resume: runtimeOptions.resume, resumeKey: runtimeOptions.resumeKey,
123
+ initialSegment: runtimeOptions.initialSegment,
124
+ },
125
+ onDiagnostic: runtimeOptions.observability
126
+ ? (name, attributes) => runtimeOptions.observability?.log('info', name, { ...attributes }, { component: 'runtime.persistence' })
127
+ : undefined,
120
128
  onDegraded: (error, health) => runtimeOptions.observability?.error(
121
129
  'runtime.persistence.async_degraded',
122
130
  error,
@@ -107,7 +107,12 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
107
107
  }
108
108
  private nextCommitSeq = 1;
109
109
 
110
- constructor(snapshot?: EventRepositorySnapshot) {
110
+ constructor(
111
+ snapshot?: EventRepositorySnapshot,
112
+ private readonly archivedIdentities?: (event: CommitEventRequest['event']) => Array<{
113
+ event: CanonicalEvent; deliveries: EventDeliveryRecord[];
114
+ }>,
115
+ ) {
111
116
  if (snapshot) this.restore(snapshot);
112
117
  }
113
118
 
@@ -297,6 +302,24 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
297
302
  throw new Error(`Unknown event segment ${draft.segmentId} in session ${draft.sessionId}`);
298
303
  }
299
304
 
305
+ // Source event IDs are global to their source, unlike epoch recovery scope.
306
+ // A replay of an archived fact must not consume a new in-memory sequence
307
+ // while the SQLite mirror deduplicates it against an older record.
308
+ for (const { event: archived, deliveries } of this.archivedIdentities?.(draft) ?? []) {
309
+ if (this.events.has(archived.eventId)) continue;
310
+ this.events.set(archived.eventId, archived);
311
+ this.eventOrder.push(archived.eventId);
312
+ this.eventOrder.sort((a, b) => this.events.get(a)!.commitSeq - this.events.get(b)!.commitSeq);
313
+ if (archived.sourceEventId) {
314
+ this.remoteEventIds.set(sourceEventKey(archived.sourceId, archived.sourceEventId), archived.eventId);
315
+ }
316
+ if (archived.sourceSequence) {
317
+ this.remoteSequences.set(sourceSequenceKey(archived.sourceId, archived.sessionId,
318
+ archived.segmentId, archived.sourceSequence), archived.eventId);
319
+ }
320
+ for (const delivery of deliveries) this.deliveries.set(deliveryKey(delivery.eventId, delivery.consumerId), delivery);
321
+ }
322
+
300
323
  const duplicateId = draft.sourceEventId
301
324
  ? this.remoteEventIds.get(sourceEventKey(draft.sourceId, draft.sourceEventId))
302
325
  : undefined;
@@ -0,0 +1,20 @@
1
+ import type { CurrentEventScope } from './types.js';
2
+
3
+ export interface RuntimeResumeSelection {
4
+ resume?: boolean;
5
+ resumeKey?: string;
6
+ initialSegment: { kind: string; identity?: string };
7
+ }
8
+
9
+ /** Shared by startup hydration and Runtime; never hydrate a scope Runtime will reject. */
10
+ export function canResumeRuntimeScope(
11
+ current: CurrentEventScope | null,
12
+ options: RuntimeResumeSelection,
13
+ ): boolean {
14
+ return !!options.resume && !!current && current.session.status === 'open' && (
15
+ (options.resumeKey !== undefined && current.session.resumeKey === options.resumeKey)
16
+ || (options.initialSegment.identity !== undefined
17
+ && current.segment.kind === options.initialSegment.kind
18
+ && current.segment.scopeRef === options.initialSegment.identity)
19
+ );
20
+ }
@@ -296,14 +296,18 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
296
296
  }
297
297
 
298
298
  /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
299
- snapshot(): EventRepositorySnapshot {
300
- const events = this.db.prepare('SELECT * FROM events ORDER BY commit_seq ASC')
301
- .all().map(eventFromRow);
299
+ snapshot(sessionId?: string | null): EventRepositorySnapshot {
300
+ // undefined retains the explicit full-export API; null loads no historical payloads.
301
+ const where = sessionId === undefined ? '' : sessionId === null ? ' WHERE 0' : ' WHERE session_id = ?';
302
+ const params = typeof sessionId === 'string' ? [sessionId] : [];
303
+ const events = this.db.prepare(`SELECT * FROM events${where} ORDER BY commit_seq ASC`)
304
+ .all(...params).map(eventFromRow);
302
305
  return {
303
- sessions: this.db.prepare('SELECT * FROM play_sessions').all().map(sessionFromRow),
304
- segments: this.db.prepare('SELECT * FROM event_segments').all().map(segmentFromRow),
306
+ sessions: this.db.prepare(`SELECT * FROM play_sessions${where}`).all(...params).map(sessionFromRow),
307
+ segments: this.db.prepare(`SELECT * FROM event_segments${where}`).all(...params).map(segmentFromRow),
305
308
  events,
306
- deliveries: this.db.prepare('SELECT * FROM event_deliveries').all().map(deliveryFromRow),
309
+ deliveries: this.db.prepare(`SELECT * FROM event_deliveries WHERE event_id IN (SELECT event_id FROM events${where})`)
310
+ .all(...params).map(deliveryFromRow),
307
311
  checkpoints: this.db.prepare('SELECT * FROM source_checkpoints').all().map(checkpointFromRow),
308
312
  leases: this.db.prepare('SELECT * FROM consumer_leases').all().map((row) => ({
309
313
  consumerId: String(row.consumer_id),
@@ -311,8 +315,9 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
311
315
  ownerId: String(row.owner_id),
312
316
  expiresAt: numberValue(row.expires_at),
313
317
  })),
314
- mailboxItems: this.db.prepare('SELECT * FROM mailbox_items').all().map(mailboxItemFromRow),
315
- nextCommitSeq: (events.at(-1)?.commitSeq ?? 0) + 1,
318
+ mailboxItems: this.db.prepare(`SELECT * FROM mailbox_items${where}`).all(...params).map(mailboxItemFromRow),
319
+ // The mirror uses SQLite's global sequence, not the selected session's last row.
320
+ nextCommitSeq: numberValue(this.db.prepare('SELECT MAX(commit_seq) AS seq FROM events').get()?.seq) + 1,
316
321
  };
317
322
  }
318
323
 
@@ -600,6 +605,25 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
600
605
  });
601
606
  }
602
607
 
608
+ /** Indexed cold-archive identity check; never materializes the historical ledger. */
609
+ archivedEventIdentities(
610
+ event: CommitEventRequest['event'],
611
+ loadedSessionId: string | null,
612
+ throughCommitSeq: number,
613
+ ): Array<{ event: CanonicalEvent; deliveries: EventDeliveryRecord[] }> {
614
+ if (throughCommitSeq === 0) return [];
615
+ const rows = this.db.prepare(`SELECT * FROM events
616
+ WHERE (event_id = ? OR (source_id = ? AND source_event_id = ?))
617
+ AND commit_seq <= ? AND (? IS NULL OR session_id <> ?)
618
+ LIMIT 2`).all(event.eventId, event.sourceId, event.sourceEventId ?? null,
619
+ throughCommitSeq, loadedSessionId, loadedSessionId);
620
+ return rows.map((row) => {
621
+ const event = eventFromRow(row);
622
+ return { event, deliveries: this.db.prepare('SELECT * FROM event_deliveries WHERE event_id = ?')
623
+ .all(event.eventId).map(deliveryFromRow) };
624
+ });
625
+ }
626
+
603
627
  eventById(eventId: string): CanonicalEvent | null {
604
628
  const row = this.db.prepare('SELECT * FROM events WHERE event_id = ?').get(eventId);
605
629
  return row ? eventFromRow(row) : null;
@@ -21,6 +21,15 @@ export interface ParticipationSegment {
21
21
  endedAt?: string;
22
22
  }
23
23
 
24
+ export function canReuseParticipationSegment(
25
+ current: Pick<ParticipationSegment, 'kind' | 'identity' | 'endedAt'>,
26
+ kind: string,
27
+ identity?: string,
28
+ ): boolean {
29
+ return !current.endedAt && current.kind === kind
30
+ && (identity === undefined || current.identity === undefined || current.identity === identity);
31
+ }
32
+
24
33
  export interface ParticipationSnapshot {
25
34
  session: ParticipationSession;
26
35
  segment: ParticipationSegment;
@@ -146,7 +155,7 @@ export class ParticipationManager {
146
155
  throw new Error('Cannot activate a segment without an active session.');
147
156
  }
148
157
  const current = this.currentValue.segment;
149
- if (!current.endedAt && current.kind === kind) {
158
+ if (canReuseParticipationSegment(current, kind, identity)) {
150
159
  // An omitted identity means "keep the currently known identity". This
151
160
  // matters for room reconnect loops, where a caller may only know that it
152
161
  // is returning to the lobby while the durable room code is already set.
@@ -1,4 +1,5 @@
1
- import { parentPort, workerData } from 'worker_threads';
1
+ import { parentPort, workerData, threadId } from 'worker_threads';
2
+ import { getHeapStatistics } from 'v8';
2
3
  import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
3
4
  import { SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
4
5
  import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
@@ -7,6 +8,7 @@ interface WorkerPaths {
7
8
  eventLedgerPath: string;
8
9
  stateHistoryPath: string;
9
10
  inputJournalPath: string;
11
+ diagnostics?: boolean;
10
12
  }
11
13
 
12
14
  interface PersistenceOperation {
@@ -24,6 +26,21 @@ const stores = {
24
26
  input: new SqliteRuntimeInputJournal(paths.inputJournalPath),
25
27
  };
26
28
 
29
+ function reportMemory(): void {
30
+ if (!paths.diagnostics) return;
31
+ const memory = process.memoryUsage();
32
+ parentPort?.postMessage({ type: 'diagnostics', memory: {
33
+ sampled_at_ms: Date.now(), thread_id: threadId,
34
+ heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
35
+ external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
36
+ heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
37
+ // RSS is process-wide; never present it as this Worker's private memory.
38
+ } });
39
+ }
40
+ reportMemory();
41
+ const memoryTimer = paths.diagnostics ? setInterval(reportMemory, 5_000) : undefined;
42
+ memoryTimer?.unref();
43
+
27
44
  parentPort?.on('message', (message: {
28
45
  type: 'batch' | 'barrier' | 'close';
29
46
  id: number;
@@ -44,6 +61,8 @@ parentPort?.on('message', (message: {
44
61
  parentPort?.postMessage({ type: 'barrier', id: message.id });
45
62
  return;
46
63
  }
64
+ if (memoryTimer) clearInterval(memoryTimer);
65
+ reportMemory();
47
66
  stores.history.close();
48
67
  stores.input.close();
49
68
  stores.events.close();
@@ -1,4 +1,7 @@
1
1
  import { randomUUID } from 'crypto';
2
+ import { statSync } from 'fs';
3
+ import { getHeapStatistics } from 'v8';
4
+ import { canReuseParticipationSegment } from '../participation-manager.js';
2
5
  import { createRequire } from 'module';
3
6
  import { pathToFileURL } from 'url';
4
7
  import { Worker } from 'worker_threads';
@@ -13,6 +16,7 @@ import type {
13
16
  } from '../mailbox/types.js';
14
17
  import { MemoryEventRepository } from '../events/memory-event-repository.js';
15
18
  import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
19
+ import { canResumeRuntimeScope, type RuntimeResumeSelection } from '../events/runtime-resume.js';
16
20
  import type { EventRepository } from '../events/event-repository.js';
17
21
  import type {
18
22
  AcquireLeaseRequest,
@@ -58,6 +62,8 @@ export interface MemoryFirstPersistenceOptions {
58
62
  maxPendingOperations?: number;
59
63
  batchSize?: number;
60
64
  flushIntervalMs?: number;
65
+ recovery?: RuntimeResumeSelection & { account: EventAccountScope };
66
+ onDiagnostic?: (name: string, attributes: Readonly<Record<string, unknown>>) => void;
61
67
  onDegraded?: (error: Error, health: AsyncPersistenceHealth) => void;
62
68
  }
63
69
 
@@ -69,6 +75,7 @@ interface ResolvedMemoryFirstPersistenceOptions {
69
75
  batchSize: number;
70
76
  flushIntervalMs: number;
71
77
  onDegraded?: MemoryFirstPersistenceOptions['onDegraded'];
78
+ onDiagnostic?: MemoryFirstPersistenceOptions['onDiagnostic'];
72
79
  }
73
80
 
74
81
  export interface AsyncPersistenceHealth {
@@ -77,6 +84,21 @@ export interface AsyncPersistenceHealth {
77
84
  droppedOperations: number;
78
85
  degraded: boolean;
79
86
  error?: string;
87
+ workerMemory?: Readonly<Record<string, number>>;
88
+ }
89
+
90
+ function memorySample(): Readonly<Record<string, number>> {
91
+ const memory = process.memoryUsage();
92
+ return {
93
+ sampled_at_ms: Date.now(), rss_bytes: memory.rss,
94
+ heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
95
+ external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
96
+ heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
97
+ };
98
+ }
99
+
100
+ function databaseBytes(path: string): number {
101
+ try { return statSync(path).size; } catch { return 0; }
80
102
  }
81
103
 
82
104
  class AsyncSqliteMirror {
@@ -92,6 +114,7 @@ class AsyncSqliteMirror {
92
114
  private degradedError?: Error;
93
115
  private closing?: Promise<void>;
94
116
  private references = 3;
117
+ private workerMemory?: Readonly<Record<string, number>>;
95
118
 
96
119
  constructor(private readonly options: ResolvedMemoryFirstPersistenceOptions) {
97
120
  const workerUrl = new URL('./async-sqlite-persistence-worker.ts', import.meta.url).href;
@@ -109,9 +132,15 @@ class AsyncSqliteMirror {
109
132
  eventLedgerPath: options.eventLedgerPath,
110
133
  stateHistoryPath: options.stateHistoryPath,
111
134
  inputJournalPath: options.inputJournalPath,
135
+ diagnostics: !!options.onDiagnostic,
112
136
  },
113
137
  });
114
- this.worker.on('message', (message: { type: string; id: number; error?: string }) => {
138
+ this.worker.on('message', (message: { type: string; id: number; error?: string; memory?: Readonly<Record<string, number>> }) => {
139
+ if (message.type === 'diagnostics') {
140
+ this.workerMemory = message.memory;
141
+ try { this.options.onDiagnostic?.('runtime.persistence.worker_memory', { worker_memory: message.memory }); } catch { /* observational */ }
142
+ return;
143
+ }
115
144
  if (message.type === 'ack') {
116
145
  this.acknowledgedOperations += this.batchSizes.get(message.id) ?? 0;
117
146
  this.batchSizes.delete(message.id);
@@ -155,6 +184,7 @@ class AsyncSqliteMirror {
155
184
  droppedOperations: this.droppedOperations,
156
185
  degraded: !!this.degradedError,
157
186
  ...(this.degradedError ? { error: this.degradedError.message } : {}),
187
+ ...(this.workerMemory ? { workerMemory: this.workerMemory } : {}),
158
188
  };
159
189
  }
160
190
 
@@ -231,7 +261,11 @@ abstract class MirroredStore {
231
261
  }
232
262
 
233
263
  class MemoryFirstEventRepository extends MirroredStore implements EventRepository, MailboxRepository {
234
- constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository) { super(mirror); }
264
+ constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository,
265
+ private readonly closeArchive: () => void) { super(mirror); }
266
+ override async close(): Promise<void> {
267
+ try { await super.close(); } finally { this.closeArchive(); }
268
+ }
235
269
  diagnosticCounts() { return this.memory.diagnosticCounts(); }
236
270
  saveSession(value: PlaySessionRecord): void { this.memory.saveSession(value); this.persist('events', 'saveSession', value); }
237
271
  saveSegment(value: EventSegmentRecord): void { this.memory.saveSegment(value); this.persist('events', 'saveSegment', value); }
@@ -351,21 +385,79 @@ export function createMemoryFirstPersistence<
351
385
  TState extends Record<string, unknown> = Record<string, unknown>,
352
386
  TEvent extends Record<string, unknown> = Record<string, unknown>,
353
387
  >(options: MemoryFirstPersistenceOptions): MemoryFirstPersistence<TPosition, TState, TEvent> {
388
+ const startedAt = performance.now();
389
+ const diagnostic = (stage: string, attributes: Record<string, unknown> = {}): void => {
390
+ if (!options.onDiagnostic) return;
391
+ try {
392
+ options.onDiagnostic('runtime.persistence.hydration', {
393
+ stage, elapsed_ms: performance.now() - startedAt,
394
+ process_memory: memorySample(), ...attributes,
395
+ });
396
+ } catch { /* Diagnostics must not prevent startup. */ }
397
+ };
398
+ diagnostic('started', {
399
+ event_db_bytes: databaseBytes(options.eventLedgerPath),
400
+ event_wal_bytes: databaseBytes(`${options.eventLedgerPath}-wal`),
401
+ history_db_bytes: databaseBytes(options.stateHistoryPath),
402
+ history_wal_bytes: databaseBytes(`${options.stateHistoryPath}-wal`),
403
+ input_db_bytes: databaseBytes(options.inputJournalPath),
404
+ input_wal_bytes: databaseBytes(`${options.inputJournalPath}-wal`),
405
+ });
354
406
  const eventSqlite = SqliteEventRepository.open(options.eventLedgerPath);
355
- if (!eventSqlite.ok) throw new Error(`${eventSqlite.unavailable.code}: ${eventSqlite.unavailable.message}`);
356
- const historySqlite = new SqliteStateHistoryRepository<TPosition, TState>(options.stateHistoryPath);
357
- const inputSqlite = new SqliteRuntimeInputJournal<TState, TEvent>(options.inputJournalPath);
407
+ if (!eventSqlite.ok) {
408
+ diagnostic('failed', { error_name: eventSqlite.unavailable.code });
409
+ throw new Error(`${eventSqlite.unavailable.code}: ${eventSqlite.unavailable.message}`);
410
+ }
411
+ let historySqlite: SqliteStateHistoryRepository<TPosition, TState> | undefined;
412
+ let inputSqlite: SqliteRuntimeInputJournal<TState, TEvent> | undefined;
358
413
  let eventMemory: MemoryEventRepository;
359
414
  let historyMemory: MemoryStateHistoryRepository<TPosition, TState>;
360
415
  let inputMemory: MemoryRuntimeInputJournal<TState, TEvent>;
416
+ let hydrated = false;
361
417
  try {
362
- eventMemory = new MemoryEventRepository(eventSqlite.repository.snapshot());
363
- historyMemory = new MemoryStateHistoryRepository(historySqlite.snapshot());
364
- inputMemory = new MemoryRuntimeInputJournal(inputSqlite.snapshot());
418
+ historySqlite = new SqliteStateHistoryRepository<TPosition, TState>(options.stateHistoryPath);
419
+ inputSqlite = new SqliteRuntimeInputJournal<TState, TEvent>(options.inputJournalPath);
420
+ const current = eventSqlite.repository.currentScope(options.recovery?.account);
421
+ const restore = options.recovery
422
+ ? canResumeRuntimeScope(current, options.recovery)
423
+ : current?.session.status === 'open';
424
+ const sessionId = restore && current ? current.session.sessionId : null;
425
+ const reuseSegment = !options.recovery || (current && current.segment.status === 'open'
426
+ && canReuseParticipationSegment({ kind: current.segment.kind, identity: current.segment.scopeRef },
427
+ options.recovery.initialSegment.kind, options.recovery.initialSegment.identity));
428
+ const scope: RuntimeScope | null = restore && current && reuseSegment ? {
429
+ adapterId: current.session.adapterId, accountId: current.session.accountId,
430
+ sessionId: current.session.sessionId, segmentId: current.segment.segmentId,
431
+ segmentSeq: current.segment.sequence,
432
+ } : null;
433
+ diagnostic('selected', {
434
+ restore_session: !!sessionId, event_selection: sessionId ? 'current_session' : 'metadata_only',
435
+ state_selection: scope ? 'current_segment' : 'none',
436
+ });
437
+ // Event consumers can still own pending deliveries in earlier segments of
438
+ // the same session. State/plugin recovery, however, reads the active scope only.
439
+ const events = eventSqlite.repository.snapshot(sessionId);
440
+ if (!sessionId && current) {
441
+ // Runtime must still seal the previous durable scope on a fresh start.
442
+ events.sessions = [current.session];
443
+ events.segments = [current.segment];
444
+ }
445
+ const archiveThrough = events.nextCommitSeq - 1;
446
+ eventMemory = new MemoryEventRepository(events, (event) =>
447
+ eventSqlite.repository.archivedEventIdentities(event, sessionId, archiveThrough));
448
+ diagnostic('events_loaded', { loaded_records: eventMemory.diagnosticCounts() });
449
+ historyMemory = new MemoryStateHistoryRepository(historySqlite.snapshot(scope));
450
+ diagnostic('history_loaded', { loaded_records: historyMemory.diagnosticCounts() });
451
+ inputMemory = new MemoryRuntimeInputJournal(inputSqlite.snapshot(scope));
452
+ diagnostic('input_loaded', { loaded_records: inputMemory.diagnosticCounts() });
453
+ hydrated = true;
454
+ } catch (error) {
455
+ diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
456
+ throw error;
365
457
  } finally {
366
- eventSqlite.repository.close();
367
- historySqlite.close();
368
- inputSqlite.close();
458
+ if (!hydrated) eventSqlite.repository.close();
459
+ historySqlite?.close();
460
+ inputSqlite?.close();
369
461
  }
370
462
  const required: ResolvedMemoryFirstPersistenceOptions = {
371
463
  ...options,
@@ -373,9 +465,20 @@ export function createMemoryFirstPersistence<
373
465
  batchSize: options.batchSize ?? 128,
374
466
  flushIntervalMs: options.flushIntervalMs ?? 8,
375
467
  };
376
- const mirror = new AsyncSqliteMirror(required);
468
+ let mirror: AsyncSqliteMirror;
469
+ try { mirror = new AsyncSqliteMirror(required); }
470
+ catch (error) {
471
+ eventSqlite.repository.close();
472
+ diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
473
+ throw error;
474
+ }
475
+ diagnostic('completed', {
476
+ loaded_records: {
477
+ events: eventMemory.diagnosticCounts(), history: historyMemory.diagnosticCounts(), input: inputMemory.diagnosticCounts(),
478
+ },
479
+ });
377
480
  return {
378
- eventRepository: new MemoryFirstEventRepository(mirror, eventMemory),
481
+ eventRepository: new MemoryFirstEventRepository(mirror, eventMemory, () => eventSqlite.repository.close()),
379
482
  stateHistoryRepository: new MemoryFirstStateHistory(mirror, historyMemory),
380
483
  inputJournal: new MemoryFirstInputJournal(mirror, inputMemory),
381
484
  health: () => mirror.health(),
@@ -668,15 +668,18 @@ implements RuntimePersistenceStore<TState, TEvent> {
668
668
  }
669
669
 
670
670
  /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
671
- snapshot(): RuntimeInputJournalSnapshot<TState, TEvent> {
672
- const epochRows = this.db.prepare('SELECT * FROM runtime_epochs ORDER BY epoch_seq ASC').all();
671
+ snapshot(scope?: RuntimeScope | null): RuntimeInputJournalSnapshot<TState, TEvent> {
672
+ const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
673
+ : ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
674
+ const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
675
+ const epochRows = this.db.prepare(`SELECT * FROM runtime_epochs${where} ORDER BY epoch_seq ASC`).all(...params);
673
676
  const epochs = epochRows.map((row) => ({
674
677
  epoch: this.fromRow(row),
675
678
  closed: row.status === 'closed',
676
679
  inputEventsCommitted: typeof row.input_events_committed_at === 'string',
677
680
  eventWatermark: numberValue(row.event_commit_watermark),
678
681
  }));
679
- const pluginProgress = this.db.prepare('SELECT * FROM runtime_plugin_progress').all().map((row) => ({
682
+ const pluginProgress = this.db.prepare(`SELECT * FROM runtime_plugin_progress${where}`).all(...params).map((row) => ({
680
683
  scope: {
681
684
  adapterId: String(row.adapter_id),
682
685
  accountId: String(row.account_id),
@@ -691,8 +694,9 @@ implements RuntimePersistenceStore<TState, TEvent> {
691
694
  updatedAt: String(row.updated_at),
692
695
  },
693
696
  }));
694
- const pluginRecords = this.db.prepare('SELECT * FROM runtime_plugin_outcomes ORDER BY epoch_seq, plugin_id')
695
- .all().map((row) => ({
697
+ const pluginRecords = this.db.prepare(`SELECT * FROM runtime_plugin_outcomes
698
+ WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id`)
699
+ .all(...params).map((row) => ({
696
700
  epochSeq: numberValue(row.epoch_seq),
697
701
  pluginId: String(row.plugin_id),
698
702
  invocationId: String(row.invocation_id),
@@ -705,8 +709,9 @@ implements RuntimePersistenceStore<TState, TEvent> {
705
709
  eventCursorAfter: numberValue(row.event_cursor_after),
706
710
  recordedAt: String(row.recorded_at),
707
711
  }));
708
- const states = this.db.prepare('SELECT * FROM runtime_plugin_states ORDER BY epoch_seq, plugin_id, topic')
709
- .all().map((row) => ({
712
+ const states = this.db.prepare(`SELECT * FROM runtime_plugin_states
713
+ WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id, topic`)
714
+ .all(...params).map((row) => ({
710
715
  epochSeq: numberValue(row.epoch_seq),
711
716
  pluginId: String(row.plugin_id),
712
717
  topic: String(row.topic),
@@ -717,7 +722,7 @@ implements RuntimePersistenceStore<TState, TEvent> {
717
722
  pluginProgress,
718
723
  pluginRecords,
719
724
  states,
720
- nextEpochSeq: (epochs.at(-1)?.epoch.epochSeq ?? 0) + 1,
725
+ nextEpochSeq: numberValue(this.db.prepare('SELECT MAX(epoch_seq) AS seq FROM runtime_epochs').get()?.seq) + 1,
721
726
  };
722
727
  }
723
728
 
@@ -1,3 +1,4 @@
1
+ import { canResumeRuntimeScope } from './events/runtime-resume.js';
1
2
  import {
2
3
  ActionRegistry,
3
4
  ObservationRegistry,
@@ -502,13 +503,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
502
503
  const durableCurrent = this.repository.currentScope(accountScope);
503
504
  const resumesBySessionKey = options.resumeKey !== undefined
504
505
  && durableCurrent?.session.resumeKey === options.resumeKey;
505
- const resumesByCurrentSegment = options.initialSegment.identity !== undefined
506
- && durableCurrent?.segment.kind === options.initialSegment.kind
507
- && durableCurrent.segment.scopeRef === options.initialSegment.identity;
508
- const canResume = !!options.resume
509
- && !!durableCurrent
510
- && durableCurrent.session.status === 'open'
511
- && (resumesBySessionKey || resumesByCurrentSegment);
506
+ const canResume = canResumeRuntimeScope(durableCurrent, options);
512
507
  if (!canResume && durableCurrent) this.sealDurableScope(durableCurrent);
513
508
 
514
509
  this.participation = new ParticipationManager({
@@ -626,6 +621,11 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
626
621
  };
627
622
  }
628
623
 
624
+ runtimePersistenceDiagnostics(): Readonly<Record<string, unknown>> {
625
+ return (this.repository as { persistenceHealth?: () => Readonly<Record<string, unknown>> })
626
+ .persistenceHealth?.() ?? {};
627
+ }
628
+
629
629
  runtimePluginDescriptors(): RuntimePluginDescriptor[] {
630
630
  return [
631
631
  ...[...this.sourcePlugins.values()].map(({ plugin }) => ({
@@ -357,17 +357,20 @@ export class SqliteStateHistoryRepository<
357
357
  }
358
358
 
359
359
  /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
360
- snapshot(): StateHistorySnapshot<TPosition, TState> {
361
- const stateFrames = this.db.prepare('SELECT * FROM state_frames ORDER BY frame_seq ASC')
362
- .all().map((row) => this.stateFrameFromRow(row));
363
- const records = this.db.prepare('SELECT * FROM trajectory_records ORDER BY record_seq ASC')
364
- .all().map((row) => this.recordFromRow(row));
360
+ snapshot(scope?: RuntimeScope | null): StateHistorySnapshot<TPosition, TState> {
361
+ const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
362
+ : ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
363
+ const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
364
+ const stateFrames = this.db.prepare(`SELECT * FROM state_frames${where} ORDER BY frame_seq ASC`)
365
+ .all(...params).map((row) => this.stateFrameFromRow(row));
366
+ const records = this.db.prepare(`SELECT * FROM trajectory_records${where} ORDER BY record_seq ASC`)
367
+ .all(...params).map((row) => this.recordFromRow(row));
365
368
  return {
366
- scopes: this.db.prepare('SELECT * FROM history_scopes').all().map((row) => this.scopeFromRow(row)),
369
+ scopes: this.db.prepare(`SELECT * FROM history_scopes${where}`).all(...params).map((row) => this.scopeFromRow(row)),
367
370
  stateFrames,
368
371
  records,
369
- nextFrameSeq: (stateFrames.at(-1)?.frameSeq ?? 0) + 1,
370
- nextRecordSeq: (records.at(-1)?.recordSeq ?? 0) + 1,
372
+ nextFrameSeq: Number(this.db.prepare('SELECT MAX(frame_seq) AS seq FROM state_frames').get()?.seq ?? 0) + 1,
373
+ nextRecordSeq: Number(this.db.prepare('SELECT MAX(record_seq) AS seq FROM trajectory_records').get()?.seq ?? 0) + 1,
371
374
  };
372
375
  }
373
376