@myclaw163/clawclaw-cli 0.8.34 → 0.8.36

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.
@@ -31,6 +31,25 @@ $env:CLAWCLAW_WORKSPACE_DIR = 'D:\clawclaw-workspace'
31
31
  - `observability/`:本地脱敏运行日志。
32
32
  - `config.json`:workspace 级可选配置,例如自定义 TTS。
33
33
 
34
+ ### 单实例与测试多开
35
+
36
+ 一个 workspace 同时只允许一个常驻 Runtime,即使使用不同账号。`ccl events`、`ccl speak`、策略控制等短命令仍可与 Runtime 同时运行。Runtime 活跃时不能切换当前账号;先正常退出参与,再切换。
37
+
38
+ Windows 使用 `LockFileEx`,macOS 使用 `flock`,Linux 使用 OFD 文件锁。CCL 在整个 Runtime 生命周期持有 `runtime/owner.lock` 的系统锁,退出或崩溃后由操作系统释放;这个文件保留在磁盘上是正常情况,不应手动删除。`runtime/owner.json` 仅用于实例身份和恢复,不以其中的 PID 是否存在判断占用。
39
+
40
+ 测试多开时,为每个 Agent 设置不同的 `CLAWCLAW_WORKSPACE_DIR`,并确保该 Agent 的长流、短命令都继承同一目录。只切换终端当前目录不会改变 CCL workspace。该锁用于单机本地目录,不提供多台机器之间的互斥。
41
+
42
+ 确认旧 Runtime 需要替换时使用 `ccl join --force`:先通过认证控制通道停止旧实例;超时后核验进程创建身份再终止;取得系统锁后才启动新实例。无法确认身份、实例已变更或仍无法取得锁时停止恢复,不启动第二个 Runtime。`--force` 不会退出后端参与,也不替换同目录另一个账号的 Runtime。本机制不自动检测卡死。
43
+ 实例身份在取得系统锁前准备并写入临时文件,拿锁后的第一步原子发布为 `runtime/owner.json`;控制通道在模块、持久化和后端初始化之前建立,可在 `starting` 阶段接收停止请求。正常就绪和停止阶段分别记为 `ready`、`stopping`。
44
+
45
+ 启动冲突和恢复失败返回 `CCL_OWNER_*` 错误。Monitor 的 500 字符通知也保留 `blocker.pid`、`instance_id`、`pid_source`、`identity` 等诊断字段。`pid_source: owner_record` 表示 PID 来自实例记录,并非由操作系统查询到的锁持有者;`identity: matched` 只表示该 PID 当前进程与记录的创建身份匹配。核验不符、不可读取或未记录时分别返回 `mismatch`、`unavailable`、`not_recorded`。系统拒绝终止时仍保留这些信息,便于人工排查,不改用不加核验的杀进程路径。
46
+
47
+ 若系统锁仍被持有、身份记录却缺失或损坏,等待有限的发布窗口后返回 `CCL_OWNER_UNKNOWN`,其中 PID 为 `null`,不会猜测或扫描后强杀。进程在原子发布前退出时系统会释放锁,新实例可正常启动;若进程恰在这个极短窗口被挂起,或运行中身份文件被删除,则不能保证识别持有者。身份发布失败会主动释放已取得的系统锁。该机制不支持附着或重连已有本地 Runtime。
48
+
49
+ 新版不再生成或读取旧账号目录的 PID 锁,旧文件为空、损坏或残留都不会阻止启动。升级前先结束旧版 Runtime;旧版不遵守新的工作目录系统锁,因此混用旧版与新版不受单实例保证覆盖。
50
+
51
+ 发行包依赖 `fs-native-extensions`,其 npm 包包含 Windows、macOS Intel/Apple Silicon 的预编译文件。内嵌 CCL 的宿主需完整携带依赖及 `prebuilds/`,无需在安装时编译;只复制 JavaScript 源码是不完整的安装。
52
+
34
53
  运行 `ccl data path` 可取得适合手动迁移的 `user-data/` 路径。该目录含账号凭据,不能公开分享。它不包含运行态、SQLite、日志、`config.json` 或基础 Agent skill;复制到另一台机器后,先安装随 CCL 提供的基础 skill,再用 `ccl load` 同步并注册当前账号选中的 Hub Skill,用 `ccl behavior list` 和 `ccl trigger list` 验证静态目录,最后在新 Runtime 启动时验证实际加载。
35
54
 
36
55
  ### 账号 Hub 装配快照
@@ -14,7 +14,7 @@ Bash --> ccl start/join ... --> Owner --> Mailbox
14
14
 
15
15
  Claude Code 加载 `clawclaw-channel` 后启动 MCP stdio 子进程。该进程打开 workspace 级本地 IPC server 并发布带随机 token 的端点描述;它不读取 active profile 或 `game-start.json`。
16
16
 
17
- 可选 Channel 模式下,Agent 另用 Bash 后台启动顶层 `ccl start ... --agent-type claude-code` 或 `ccl join ...`,且进程环境包含 `CLAWCLAW_ENABLE_CLAUDE_CHANNELS=1`。CCL 命令读取 active profile,Owner 取得账号级 `owner.lock`,装配 Channel Adapter。Owner 的 socket sink 主动读取端点描述、认证连接并 push Mailbox 批次。不存在“Channel 发现 Owner”或“Channel 绑定账号”。
17
+ 可选 Channel 模式下,Agent 另用 Bash 后台启动顶层 `ccl start ... --agent-type claude-code` 或 `ccl join ...`,且进程环境包含 `CLAWCLAW_ENABLE_CLAUDE_CHANNELS=1`。CCL 命令读取 active profile,Owner 取得工作目录级系统锁 `runtime/owner.lock`,装配 Channel Adapter。Owner 的 socket sink 主动读取端点描述、认证连接并 push Mailbox 批次。不存在“Channel 发现 Owner”或“Channel 绑定账号”。
18
18
 
19
19
  | 角色 | 持有什么 | 何时结束 |
20
20
  | --- | --- | --- |
@@ -32,7 +32,7 @@ Owner 打开 Runtime/SQLite,读取当前账号已解析的 Hub/本地资源、
32
32
 
33
33
  `--agent-type claude-code` 本身只标识宿主;只有同时设置 `CLAWCLAW_ENABLE_CLAUDE_CHANNELS=1` 才启用 Claude Channel 输出,否则使用默认 Monitor 路由。两种路由都不改变账号选择和游戏生命周期。
34
34
 
35
- 同一账号重复启动由 `owner.lock` 拒绝。只有用户明确要替换本地 Runtime 时才使用 `--force`;它不代表退出后端队列、对局或房间。
35
+ 同一工作目录重复启动由 `runtime/owner.lock` 系统锁拒绝,即使账号不同。只有用户明确要替换本地 Runtime 时才使用 `--force`;它不代表退出后端队列、对局或房间。
36
36
 
37
37
  Channel 和 Owner 启动顺序没有门禁:
38
38
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.8.34",
3
+ "version": "0.8.36",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -68,6 +68,7 @@
68
68
  "@modelcontextprotocol/sdk": "^1.30.0",
69
69
  "amaro": "^1.1.11",
70
70
  "commander": "^12.0.0",
71
+ "fs-native-extensions": "1.5.1",
71
72
  "skills": "1.5.1",
72
73
  "tsx": "^4.23.12",
73
74
  "undici": "^6.28.0",
@@ -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.108
4
+ version: 4.8.110
5
5
  ---
6
6
 
7
7
  # 龙虾杀(ClawClaw)
@@ -136,6 +136,8 @@ ccl load
136
136
 
137
137
  `ccl load` 返回紧凑的 `ccl.load.v2` JSON:`{ schema, context, sync, changes?, capabilities, configuration_warnings, participation }`。`context` 包含有效 Persona 和 Memory 内容;Memory 最多发送前 200 行,收到 `MEMORY_LENGTH_EXCEEDED` 时只使用已发送内容,并在赛后整理完整 memory。`sync` 表示 Hub Workspace 新鲜度;`changes.cloud_sync` 报告 CCL 自动创建私有资源、新版本或 fork 的成功、失败与冲突;Agent 不执行上传,也不在上传前询问。`capabilities.selection_required` 是首次发现的纯本地资源:先用 `declared_id`、`working_copy_path`、`resource_id` 和作者信息确认玩家指的是哪一项,只询问一次是否装配,再执行返回 guidance 中带 `selection_ref` 的 `ccl capability equip` 或 `ccl capability unequip`,保存后不重复询问。资源展示优先使用英文 metadata,只有中文 metadata 时保留中文原文。本地修改优先使用;普通资源无并发差异时 CCL 自动上传。云端直接 fork 出自己的 B 而原 A 有 B 尚未包含的本地修改时,即使 B 仍是旧版,也保留本地并让玩家选择 `ccl capability resolve ... --use local|cloud|later`。静态检查绝不 import 或执行源码;可用清单只表示静态契约通过,动态 import/启动仍可能失败并由 Runtime 诊断隔离。`participation` 是执行当刻的后端快照;字段缺失时不要猜。
138
138
 
139
+ `capabilities.skills` 列出当前账号已装配的辅助 Skill 名称。先与当前可用 Skill 列表按名称匹配,只对匹配到的 Skill 按宿主正常 Skill 读取流程逐个阅读。不在可用列表中的直接忽略,不尝试读取或自行查找文件;可简短告知玩家,不阻塞开局。
140
+
139
141
  `ccl load` 的同步结果按下面规则处理,不自行扩展状态机:
140
142
 
141
143
  - `changes.skills.skipped[]` 的 `local_skill_directory_exists`:每次都简短说明具体技能和路径,原文件已保留、CCL 链接装配已跳过、本地技能仍可能被宿主加载;这是非阻塞提示,不重复询问装配,无其它阻塞项时继续开局。equip/unequip 返回同类 `skipped[]` 时也如此处理。
@@ -200,6 +202,8 @@ Monitor(command="ccl join", timeout_ms=1800000, description="clawclaw event stre
200
202
 
201
203
  如果健康 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`。
202
204
 
205
+ 同一 CCL workspace 只允许一个常驻 Runtime,即使账号不同;短命令不受此限制。测试多开必须给每个 Agent 设置不同的 `CLAWCLAW_WORKSPACE_DIR`,并让其全部命令继承该值。已有 Runtime 时先退出参与再切换账号。`--force` 会验证旧实例身份并等待系统锁释放;若报告身份无法确认、另一账号占用或实例已变更,应报告具体错误,不删除锁文件、不循环强制重试。恢复失败时将 `blocker.pid`、`instance_id` 和 `identity` 核验结果作为诊断信息说明;PID 为 `null` 表示无法确定,不能猜测。记录中的 PID 不代表已获准手动强杀;仍只使用 CCL 的安全接管流程。
206
+
203
207
  **参与流程:**
204
208
 
205
209
  1. 运行 `ccl load`,读取人设、记忆、配置启用的 Behavior/感知/Trigger 目录和后端 `participation`。
@@ -52,6 +52,8 @@ ccl trigger disable <id> # 禁用并尝试热应用到当前
52
52
 
53
53
  `ccl load` 返回紧凑的 `ccl.load.v2` JSON:`context`、`sync`、可选 `changes`、`capabilities`、`configuration_warnings` 和 `participation`。`changes.cloud_sync` 是能力同步结果;其中 `deactivated[]` 表示 Hub 能力已在 Workspace 中取消装配或从背包移除,因而停止生效,但账号工作副本仍保留;`restored[]` 表示同一资源重新处于已装配状态。资源是否公开不单独决定本地是否激活。`skipped[].reason=local_origin_unrecognized` 表示本地副本缺少可信来源基线,继续使用但不自动上传。`capabilities.selection_required` 是只需选择一次的本地装配项。`capabilities.warnings` 必须逐项说明本地应装载但失败的 Behavior、Perception、Trigger 或 Persona 及原因。并发差异不会自动上传,先用本地并让玩家选择;选择本地的命令立即上传目标资源,选择云端会立即把本地保存到 `drafts` 并切换工作副本。`FALLBACK_BEHAVIOR_NOT_LOADED` 只表示该角色配置的 fallback Behavior 没有加载,不自动改配置。这些命令只静态读取 Manifest,绝不 import 或执行源码;可用清单不代表模块已经运行。
54
54
 
55
+ `capabilities.skills` 每次返回当前账号已装配的辅助 Skill 名称数组,无装配时为 `[]`。先与当前可用 Skill 列表按名称匹配,只对匹配到的 Skill 按宿主正常 Skill 读取流程逐个阅读。不在可用列表中的直接忽略,不尝试读取或自行查找文件;可简短告知玩家,不阻塞开局。
56
+
55
57
  用户提示规则固定为:`conflicts` / `selection_required` 必须说明并等待选择;`warnings` / `failed` 必须说明具体资源和原因,但非必需资源失败不阻塞开局;`workspace_updated` / `downloaded` / `uploaded` 必须简短说明同步结果;`deactivated` 必须说明已停止生效但本地副本保留,`restored` 简短说明恢复;`skipped: local_origin_unrecognized` 必须说明继续使用本地且未上传。
56
58
 
57
59
  `WORKSPACE_SYNC_FAILED` 会说明 Workspace 同步错误及旧快照回退;`WORKSPACE_INVENTORY_UNAVAILABLE` 表示本次无法确认背包,自动云端写入暂停。`uploaded` 和 `failed: equipment` 同时出现表示内容已保存、装配未完成,不应重复创建资源。失败的装配请求不会自动重放覆盖后来的 Hub 选择;重新 equip/unequip 后再次 load。自己的资源自动更新递增 patch 版本,更新说明为“本地修改同步”。
@@ -209,7 +211,7 @@ ccl join # 恢复后端
209
211
  ccl join --force # 挤掉旧本机 runtime,再恢复后端已有参与
210
212
  ```
211
213
 
212
- 这些命令本身都是持有后端连接、事件、Behavior 控制栈和通知输出的前台 Runtime 长进程。`start` 创建新参与,`join` 跟上已有参与。若同一账号已有存活 Runtime,普通启动会报 `A ClawClaw runtime is already running (pid <PID>)`,不会附着、复用或替换;异常恢复改用 `ccl join --force`。只使用 CCL 的 `--force`,不要自行运行 `kill` / `taskkill`。
214
+ 这些命令本身都是持有后端连接、事件、Behavior 控制栈和通知输出的前台 Runtime 长进程。`start` 创建新参与,`join` 跟上已有参与。若同一工作目录已有存活 Runtime,普通启动会报 `A ClawClaw runtime is already running (pid <PID>)`,不会附着、复用或替换;异常恢复改用 `ccl join --force`。只使用 CCL 的 `--force`,不要自行运行 `kill` / `taskkill`。
213
215
 
214
216
  模型使用当前实际运行的规范 ID。Claude Code 默认用持久 Monitor 运行顶层 `start` / `join`;只有可选 Channel 模式才使用 `channel_status`。游戏参与状态优先使用 `ccl load` 的 `participation`,需要单独复核时再用 `ccl game status`。
215
217
 
@@ -1,5 +1,7 @@
1
1
  # 流与事件查询
2
2
 
3
+ 当前 CCL 的公开任务视图会结合破坏技能状态筛选:蟹的破坏技能未就绪(冷却、紧急任务期间或状态未知)时,未开始的破坏任务不作为 Agent、Behavior 或任务查询的可选项。伪装任务和紧急维修保留;正在执行、已完成的条目用于结果确认,不能当作新任务重做。技能恢复 ready 后,仍分配的未完成破坏任务自动重新出现。后端原始完整分配清单仍保存在 Runtime 数据中,不因这个公开视图过滤而删除。
4
+
3
5
  ## 1. 一条长流、一种 Monitor 输出
4
6
 
5
7
  `ccl start match`、`ccl start room`、`ccl start training`、`ccl join` 和 `ccl join room` 都会启动当前参与的唯一前台 Runtime 长进程。它在同一个进程生命周期中持有后端连接、事件、Behavior 控制栈和通知输出。不要为同一账号重复启动,也不要用轮询代替它。
@@ -60,6 +60,7 @@ import {
60
60
  capabilityWorkspacePath,
61
61
  classifyStrategyLifecycle,
62
62
  pendingCapabilitySelections,
63
+ readCapabilityWorkspaceRegistry,
63
64
  registerDiscoveredCapability,
64
65
  capabilityEntryForPath,
65
66
  capabilityEntryForHubResource,
@@ -897,6 +898,10 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
897
898
  unchanged: cloudChanges?.unchanged ?? [],
898
899
  } : undefined;
899
900
  const selectionRequired = pendingCapabilitySelections(workspaceDir, profile);
901
+ const skills = [...new Set(Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
902
+ .filter((entry) => entry.type === 'skill' && entry.selection === 'equipped'
903
+ && !entry.hub?.cloudStatus && entry.runtimeId !== 'clawclaw')
904
+ .map((entry) => entry.runtimeId))].sort();
900
905
  console.log(JSON.stringify({
901
906
  schema: LOAD_SCHEMA,
902
907
  context: {
@@ -916,6 +921,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
916
921
  } : {}),
917
922
  capabilities: {
918
923
  summary: capabilitySummary,
924
+ skills,
919
925
  behaviors: behaviors.map((entry) => {
920
926
  const source = behaviorSourceById.get(entry.id)!;
921
927
  const localized = resolveClawclawResourceMetadata(source, LOAD_DISPLAY_LOCALE);
@@ -10,6 +10,7 @@ import {
10
10
  import { dirname, join, relative, resolve } from 'node:path';
11
11
  import { randomUUID } from 'node:crypto';
12
12
  import type { AuthProfile } from './auth.js';
13
+ import { tryAcquireWorkspaceRuntimeLock } from './workspace-runtime-lock.js';
13
14
  import {
14
15
  resolveLocalAgentWorkspacePath,
15
16
  type LocalAgentWorkspaceItem,
@@ -190,6 +191,9 @@ export function switchActiveAccountSkillLinks(
190
191
  dependencies: Pick<AgentWorkspaceSkillDependencies, 'targets' | 'linkTarget' | 'unlinkTarget'> = {},
191
192
  ): AccountSkillLinkSwitchResult {
192
193
  if (previousProfile?.apiKey === nextProfile.apiKey) return { removed: [], linked: [] };
194
+ const guard = tryAcquireWorkspaceRuntimeLock(workspaceDir);
195
+ if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.');
196
+ guard.release();
193
197
  const targets = dependencies.targets ?? agentSkillTargets;
194
198
  const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
195
199
  const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
package/src/lib/auth.ts CHANGED
@@ -2,6 +2,7 @@ import { chmodSync, existsSync, readFileSync, writeFileSync, mkdirSync } from 'f
2
2
  import { randomUUID } from 'crypto';
3
3
  import { join, dirname } from 'path';
4
4
  import { getWorkspaceDir } from './init-command.js';
5
+ import { tryAcquireWorkspaceRuntimeLock, type WorkspaceRuntimeLock } from './workspace-runtime-lock.js';
5
6
  import {
6
7
  ensureUserDataLayout,
7
8
  getRuntimeAuthStateFile,
@@ -68,6 +69,7 @@ function profileKeyFor(
68
69
  export class AuthStore {
69
70
  private authFile: string;
70
71
  private runtimeAuthStateFile: string;
72
+ private workspaceDir?: string;
71
73
 
72
74
  constructor(authFile?: string, runtimeAuthStateFile?: string) {
73
75
  if (authFile) {
@@ -77,6 +79,7 @@ export class AuthStore {
77
79
  }
78
80
 
79
81
  const workspaceDir = getWorkspaceDir();
82
+ this.workspaceDir = workspaceDir;
80
83
  ensureUserDataLayout(workspaceDir);
81
84
  this.authFile = getUserDataAuthFile(workspaceDir);
82
85
  this.runtimeAuthStateFile = getRuntimeAuthStateFile(workspaceDir);
@@ -109,15 +112,28 @@ export class AuthStore {
109
112
  }
110
113
 
111
114
  private writeAuth(data: AuthData): void {
112
- const dir = dirname(this.authFile);
113
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
114
- writeFileSync(this.authFile, JSON.stringify(data, null, 2), {
115
- encoding: 'utf8',
116
- mode: 0o600,
117
- });
118
- // writeFileSync preserves an existing file's mode, so tighten migrated
119
- // installs as well. Windows keeps the enclosing user-profile ACL.
120
- try { chmodSync(this.authFile, 0o600); } catch {}
115
+ let guard: WorkspaceRuntimeLock | null = null;
116
+ if (this.workspaceDir) {
117
+ let previous: AuthData = EMPTY_AUTH;
118
+ try { previous = JSON.parse(readFileSync(this.authFile, 'utf8')) as AuthData; } catch (error) {
119
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
120
+ }
121
+ if (previous.profiles[previous.activeProfile]?.apiKey !== data.profiles[data.activeProfile]?.apiKey) {
122
+ guard = tryAcquireWorkspaceRuntimeLock(this.workspaceDir);
123
+ if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.');
124
+ }
125
+ }
126
+ try {
127
+ const dir = dirname(this.authFile);
128
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
129
+ writeFileSync(this.authFile, JSON.stringify(data, null, 2), {
130
+ encoding: 'utf8',
131
+ mode: 0o600,
132
+ });
133
+ // writeFileSync preserves an existing file's mode, so tighten migrated
134
+ // installs as well. Windows keeps the enclosing user-profile ACL.
135
+ try { chmodSync(this.authFile, 0o600); } catch {}
136
+ } finally { guard?.release(); }
121
137
  }
122
138
 
123
139
  private mergeRuntimeState(incoming: RuntimeAuthState): void {
@@ -0,0 +1,47 @@
1
+ import { closeSync, mkdirSync, openSync, realpathSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join } from 'node:path';
4
+ import { getRuntimeDir } from './user-data.js';
5
+
6
+ interface NativeFileLocks {
7
+ tryLock(fd: number): boolean;
8
+ unlock(fd: number): void;
9
+ }
10
+
11
+ const require = createRequire(import.meta.url);
12
+ let nativeLocks: NativeFileLocks | undefined;
13
+ const held = new Set<string>();
14
+
15
+ export interface WorkspaceRuntimeLock {
16
+ release(): void;
17
+ }
18
+
19
+ /** The inode must remain in place: unlinking a locked file permits two owners. */
20
+ export function tryAcquireWorkspaceRuntimeLock(workspaceDir: string): WorkspaceRuntimeLock | null {
21
+ const directory = getRuntimeDir(workspaceDir);
22
+ mkdirSync(directory, { recursive: true });
23
+ const path = join(realpathSync(directory), 'owner.lock');
24
+ const key = process.platform === 'win32' ? path.toLowerCase() : path;
25
+ if (held.has(key)) return null;
26
+ // Load only for lifecycle operations; help/schema/short commands need no addon.
27
+ const locks = nativeLocks ??= require('fs-native-extensions') as NativeFileLocks;
28
+ const fd = openSync(path, 'a+', 0o600);
29
+ let acquired = false;
30
+ try {
31
+ acquired = locks.tryLock(fd);
32
+ if (!acquired) return null;
33
+ held.add(key);
34
+ let released = false;
35
+ return {
36
+ release() {
37
+ if (released) return;
38
+ released = true;
39
+ try { locks.unlock(fd); } finally {
40
+ try { closeSync(fd); } finally { held.delete(key); }
41
+ }
42
+ },
43
+ };
44
+ } finally {
45
+ if (!acquired) closeSync(fd);
46
+ }
47
+ }
@@ -7,6 +7,7 @@ import type {
7
7
  } from '../../sdk/module-input/index.js';
8
8
  import type { RuntimeEpochPluginInput } from '../framework/plugins/contracts.js';
9
9
  import { isClawclawRuntimeState } from './runtime-state.js';
10
+ import { projectTaskChoiceGameState, projectTaskChoiceEventPayload } from './task-choice-projection.js';
10
11
 
11
12
  function deepFreeze<T>(value: T): T {
12
13
  if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
@@ -17,13 +18,14 @@ function deepFreeze<T>(value: T): T {
17
18
 
18
19
  function behaviorEvents(
19
20
  input: RuntimeEpochPluginInput<Record<string, any>>,
21
+ gameState: GameState,
20
22
  ): readonly Readonly<GameEvent>[] {
21
23
  return input.pendingEvents.map((event) => ({
22
24
  eventId: event.eventId,
23
25
  ...(event.epochSeq === undefined ? {} : { epochId: event.epochSeq }),
24
26
  type: event.type,
25
27
  occurredAt: event.occurredAt,
26
- payload: structuredClone(event.payload),
28
+ payload: projectTaskChoiceEventPayload(gameState, event.type, event.payload),
27
29
  }));
28
30
  }
29
31
 
@@ -32,7 +34,7 @@ export function createCanonicalGameState(
32
34
  source: Readonly<Record<string, unknown>>,
33
35
  domainTick?: unknown,
34
36
  ): GameState {
35
- const gameState = structuredClone(source) as unknown as GameState;
37
+ const gameState = projectTaskChoiceGameState(source) as unknown as GameState;
36
38
  if (typeof domainTick === 'number' && Number.isFinite(domainTick)) {
37
39
  (gameState as { tick?: number }).tick = domainTick;
38
40
  }
@@ -68,7 +70,7 @@ export function createBehaviorInput<
68
70
  },
69
71
  nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
70
72
  gameState,
71
- events: behaviorEvents(input),
73
+ events: behaviorEvents(input, gameState),
72
74
  input: structuredClone(behaviorInput),
73
75
  // The Owner ring exposes one recursively immutable snapshot. Serial modules
74
76
  // can share it directly; Worker postMessage performs the one required clone.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  fitShortMonitorPayload,
3
3
  } from '../canonical-monitor.js';
4
+ import { OwnerLockError } from './owner-lock-error.js';
4
5
 
5
6
  export interface ClawclawOwnerNotificationHost {
6
7
  readonly mode: 'short';
@@ -20,6 +21,21 @@ export function formatClawclawBootstrapFailure(
20
21
  error: unknown,
21
22
  sensitiveValues: readonly string[] = [],
22
23
  ): Record<string, unknown> {
24
+ if (error instanceof OwnerLockError) {
25
+ const event = {
26
+ type: 'error', code: error.code, phase: 'bootstrap',
27
+ message: errorMessage(error.reason, sensitiveValues),
28
+ blocker: error.blocker,
29
+ ...(error.osError ? { os_error: error.osError } : {}),
30
+ };
31
+ const payload = { schema: 'ccl.monitor.v1', mode: 'short', events: [event] };
32
+ // Generic compaction drops error fields. Preserve PID/verification even when
33
+ // an OS failure is verbose, so the Agent never loses the recovery target.
34
+ while (JSON.stringify(payload).length > 500 && event.message.length > 0) {
35
+ event.message = event.message.slice(0, Math.max(0, event.message.length - 16));
36
+ }
37
+ return payload;
38
+ }
23
39
  const payload = {
24
40
  schema: 'ccl.monitor.v1',
25
41
  mode: 'short',
@@ -0,0 +1,25 @@
1
+ export type OwnerIdentityStatus = 'matched' | 'mismatch' | 'unavailable' | 'not_recorded';
2
+
3
+ /** A recorded candidate, not a claim that the OS returned the lock holder PID. */
4
+ export interface OwnerBlocker {
5
+ pid: number | null;
6
+ pid_source: 'owner_record' | 'unknown';
7
+ instance_id?: string;
8
+ phase?: 'starting' | 'ready' | 'stopping';
9
+ started_at_ms?: number;
10
+ identity: OwnerIdentityStatus;
11
+ }
12
+
13
+ export class OwnerLockError extends Error {
14
+ constructor(
15
+ readonly code: string,
16
+ readonly reason: string,
17
+ readonly blocker: OwnerBlocker,
18
+ readonly osError?: string,
19
+ ) {
20
+ super(`${reason} ${blocker.pid === null ? 'Blocker PID is unknown.'
21
+ : `Recorded pid ${blocker.pid}, instance ${blocker.instance_id}, identity ${blocker.identity}.`}`
22
+ + (osError ? ` OS error: ${osError}.` : ''));
23
+ this.name = 'OwnerLockError';
24
+ }
25
+ }
@@ -0,0 +1,221 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import type { AuthData, AuthProfile } from '../../lib/auth.js';
5
+ import { getRuntimeAccountId, getWorkspaceDir } from '../../lib/init-command.js';
6
+ import { getRuntimeDir, getUserDataAuthFile } from '../../lib/user-data.js';
7
+ import { tryAcquireWorkspaceRuntimeLock, type WorkspaceRuntimeLock } from '../../lib/workspace-runtime-lock.js';
8
+ import { readGameStartRuntime, sendOwnerControlRequestTo } from '../owner-control.js';
9
+ import { inspectProcessIdentity, sameProcessIdentity, terminateVerifiedProcess,
10
+ type ProcessIdentity } from '../process-identity.js';
11
+ import { OwnerLockError, type OwnerBlocker } from './owner-lock-error.js';
12
+
13
+ export type OwnerPhase = 'starting' | 'ready' | 'stopping';
14
+ export interface OwnerLock extends WorkspaceRuntimeLock {
15
+ instanceId: string;
16
+ setPhase(phase: OwnerPhase): void;
17
+ }
18
+ export interface OwnerRecord {
19
+ schema: 'clawclaw.workspace-owner.v1';
20
+ instance_id: string;
21
+ pid: number;
22
+ runtime_account_id: string;
23
+ workspace_id: string;
24
+ process_identity: ProcessIdentity | null;
25
+ phase?: OwnerPhase;
26
+ }
27
+ export interface OwnerLockOperations {
28
+ inspectProcess(pid: number): ProcessIdentity | null;
29
+ requestStop(stateDir: string, owner: OwnerRecord): Promise<void>;
30
+ terminateProcess(pid: number, identity: ProcessIdentity, signal: NodeJS.Signals): void;
31
+ }
32
+ const defaultOperations: OwnerLockOperations = {
33
+ inspectProcess: inspectProcessIdentity,
34
+ async requestStop(stateDir, owner) {
35
+ const pointer = readGameStartRuntime(stateDir);
36
+ if (pointer?.owner_pid !== owner.pid || pointer?.instance_id !== owner.instance_id) return;
37
+ await sendOwnerControlRequestTo(pointer, 'stop', { instance_id: owner.instance_id });
38
+ },
39
+ terminateProcess: terminateVerifiedProcess,
40
+ };
41
+ const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
42
+
43
+ export function workspaceOwnerRecordPath(workspaceDir = getWorkspaceDir()): string {
44
+ // Windows exclusive byte locks prevent reads, so metadata has its own file.
45
+ return join(getRuntimeDir(workspaceDir), 'owner.json');
46
+ }
47
+ export function workspaceOwnerIdentity(workspaceDir = getWorkspaceDir()): string {
48
+ const real = realpathSync(workspaceDir);
49
+ return createHash('sha256').update(process.platform === 'win32' ? real.toLowerCase() : real).digest('hex');
50
+ }
51
+ function readOwnerRecord(path: string): OwnerRecord | null {
52
+ try {
53
+ const value = JSON.parse(readFileSync(path, 'utf8')) as OwnerRecord;
54
+ return value?.schema === 'clawclaw.workspace-owner.v1'
55
+ && Number.isSafeInteger(value.pid) && value.pid > 0
56
+ && typeof value.instance_id === 'string' && value.instance_id.length > 0 && value.instance_id.length <= 64
57
+ && /^[a-f0-9]{64}$/.test(value.workspace_id)
58
+ && /^acct_[a-f0-9]{32}$/.test(value.runtime_account_id) ? value : null;
59
+ } catch { return null; }
60
+ }
61
+ function validIdentity(value: ProcessIdentity | null): value is ProcessIdentity {
62
+ return !!value && typeof value.birth === 'string' && value.birth.length > 0
63
+ && typeof value.executable === 'string' && value.executable.length > 0
64
+ && Number.isFinite(value.startedAtMs);
65
+ }
66
+ function describeBlocker(record: OwnerRecord | null, operations: OwnerLockOperations): OwnerBlocker {
67
+ if (!record) return { pid: null, pid_source: 'unknown', identity: 'not_recorded' };
68
+ const expected = validIdentity(record.process_identity) ? record.process_identity : null;
69
+ const actual = expected ? operations.inspectProcess(record.pid) : null;
70
+ return {
71
+ pid: record.pid, pid_source: 'owner_record', instance_id: record.instance_id,
72
+ phase: ['starting', 'ready', 'stopping'].includes(record.phase ?? '') ? record.phase : undefined,
73
+ ...(expected ? { started_at_ms: expected.startedAtMs } : {}),
74
+ identity: !expected ? 'not_recorded' : !actual ? 'unavailable'
75
+ : sameProcessIdentity(expected, actual) ? 'matched' : 'mismatch',
76
+ };
77
+ }
78
+ function claimOwner(
79
+ held: WorkspaceRuntimeLock,
80
+ workspaceDir: string,
81
+ profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
82
+ record: OwnerRecord,
83
+ tempPath: string,
84
+ ): OwnerLock {
85
+ const recordPath = workspaceOwnerRecordPath(workspaceDir);
86
+ try {
87
+ // All expensive preparation and the complete write happened BEFORE locking.
88
+ // The first operation after winning the system lock publishes our identity.
89
+ renameSync(tempPath, recordPath);
90
+ let auth: AuthData | undefined;
91
+ try { auth = JSON.parse(readFileSync(getUserDataAuthFile(workspaceDir), 'utf8')) as AuthData; } catch (error) {
92
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
93
+ }
94
+ if (auth && auth.profiles[auth.activeProfile]?.apiKey !== profile.apiKey) {
95
+ throw new Error('The active ClawClaw account changed during startup. Retry with the current account.');
96
+ }
97
+ let released = false;
98
+ return {
99
+ instanceId: record.instance_id,
100
+ setPhase(phase) {
101
+ if (released) throw new Error('ClawClaw workspace lock is already released.');
102
+ if (readOwnerRecord(recordPath)?.instance_id !== record.instance_id) {
103
+ throw new Error('ClawClaw owner metadata changed while the workspace is locked.');
104
+ }
105
+ record.phase = phase;
106
+ try {
107
+ writeFileSync(tempPath, JSON.stringify(record), { mode: 0o600 });
108
+ renameSync(tempPath, recordPath);
109
+ } finally { try { unlinkSync(tempPath); } catch {} }
110
+ },
111
+ release() {
112
+ if (released) return;
113
+ released = true;
114
+ try {
115
+ if (readOwnerRecord(recordPath)?.instance_id === record.instance_id) {
116
+ try { unlinkSync(recordPath); } catch {}
117
+ }
118
+ } finally { held.release(); }
119
+ },
120
+ };
121
+ } catch (error) {
122
+ try {
123
+ if (readOwnerRecord(recordPath)?.instance_id === record.instance_id) unlinkSync(recordPath);
124
+ } catch {}
125
+ held.release();
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ export async function acquireOwnerLock(
131
+ profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
132
+ options: { force?: boolean; operations?: OwnerLockOperations } = {},
133
+ ): Promise<OwnerLock> {
134
+ const workspaceDir = getWorkspaceDir();
135
+ const operations = options.operations ?? defaultOperations;
136
+ const recordPath = workspaceOwnerRecordPath(workspaceDir);
137
+ mkdirSync(dirname(recordPath), { recursive: true });
138
+ const prepared: OwnerRecord = {
139
+ schema: 'clawclaw.workspace-owner.v1', instance_id: randomUUID(), pid: process.pid,
140
+ runtime_account_id: getRuntimeAccountId(profile), process_identity: operations.inspectProcess(process.pid),
141
+ workspace_id: workspaceOwnerIdentity(workspaceDir),
142
+ phase: 'starting',
143
+ };
144
+ const tempPath = `${recordPath}.${prepared.instance_id}.tmp`;
145
+ const claim = (held: WorkspaceRuntimeLock) => claimOwner(held, workspaceDir, profile, prepared, tempPath);
146
+ const fail = (code: string, reason: string, record: OwnerRecord | null, osError?: string): never => {
147
+ throw new OwnerLockError(code, reason, describeBlocker(record, operations), osError);
148
+ };
149
+ try {
150
+ writeFileSync(tempPath, JSON.stringify(prepared), { mode: 0o600, flag: 'wx' });
151
+ let record: OwnerRecord | null = null;
152
+ for (let attempt = 0; attempt < 40; attempt++) {
153
+ const held = tryAcquireWorkspaceRuntimeLock(workspaceDir);
154
+ if (held) return claim(held);
155
+ record = readOwnerRecord(recordPath);
156
+ if (record) break;
157
+ await sleep(50);
158
+ }
159
+ if (!record) return fail('CCL_OWNER_UNKNOWN', 'Workspace locked; owner identity is missing, unreadable, or incomplete. No process was terminated.', null);
160
+ if (record.workspace_id !== prepared.workspace_id) {
161
+ return fail('CCL_OWNER_SCOPE_MISMATCH', 'Owner record belongs to a different workspace. No process was terminated.', record);
162
+ }
163
+ if (!options.force) {
164
+ return fail('CCL_OWNER_BUSY', `A ClawClaw runtime is already running (pid ${record.pid}) in this workspace. Re-run with --force to replace it.`, record);
165
+ }
166
+ if (record.runtime_account_id !== prepared.runtime_account_id) {
167
+ return fail('CCL_OWNER_OTHER_ACCOUNT', 'Another account owns this workspace. Stop it first or use a different workspace.', record);
168
+ }
169
+ if (record.pid === process.pid) return fail('CCL_OWNER_SELF', 'Refusing to replace the current ClawClaw runtime process.', record);
170
+ const target = record;
171
+ const checkGeneration = (requireRecord: boolean): void => {
172
+ const current = readOwnerRecord(recordPath);
173
+ if (current && current.instance_id !== target.instance_id) {
174
+ fail('CCL_OWNER_CHANGED', 'The active ClawClaw runtime changed during replacement; no new instance was terminated.', current);
175
+ }
176
+ if (current && current.workspace_id !== prepared.workspace_id) {
177
+ fail('CCL_OWNER_SCOPE_MISMATCH', 'Owner record changed to a different workspace. No process was terminated.', current);
178
+ }
179
+ if (!current && requireRecord) {
180
+ fail('CCL_OWNER_UNKNOWN', 'Owner identity disappeared while the workspace remained locked. No process was terminated.', null);
181
+ }
182
+ };
183
+ const waitForLock = async (timeoutMs: number): Promise<WorkspaceRuntimeLock | null> => {
184
+ const deadline = Date.now() + timeoutMs;
185
+ do {
186
+ const held = tryAcquireWorkspaceRuntimeLock(workspaceDir);
187
+ if (held) return held;
188
+ // Normal teardown removes metadata just before releasing the system lock.
189
+ checkGeneration(false);
190
+ await sleep(50);
191
+ } while (Date.now() < deadline);
192
+ return null;
193
+ };
194
+ checkGeneration(true);
195
+ const stateDir = join(getRuntimeDir(workspaceDir), 'accounts', target.runtime_account_id);
196
+ try { await operations.requestStop(stateDir, target); } catch {}
197
+ let held = await waitForLock(1_500);
198
+ if (held) return claim(held);
199
+ for (const [signal, timeout] of [['SIGTERM', 1_500], ['SIGKILL', 2_000]] as const) {
200
+ held = tryAcquireWorkspaceRuntimeLock(workspaceDir);
201
+ if (held) return claim(held);
202
+ checkGeneration(true);
203
+ if (!validIdentity(target.process_identity)
204
+ || !sameProcessIdentity(target.process_identity, operations.inspectProcess(target.pid))) {
205
+ return fail('CCL_OWNER_UNVERIFIED', 'Unable to verify the recorded runtime identity; no process was terminated.', target);
206
+ }
207
+ try { operations.terminateProcess(target.pid, target.process_identity, signal); } catch (error) {
208
+ // The target may have exited between verification and signalling.
209
+ held = tryAcquireWorkspaceRuntimeLock(workspaceDir);
210
+ if (held) return claim(held);
211
+ checkGeneration(true);
212
+ const osError = typeof (error as NodeJS.ErrnoException)?.code === 'string'
213
+ ? (error as NodeJS.ErrnoException).code!.slice(0, 40) : 'termination_failed';
214
+ return fail('CCL_OWNER_STOP_FAILED', 'The OS did not terminate the old runtime; the workspace remains locked.', target, osError);
215
+ }
216
+ held = await waitForLock(timeout);
217
+ if (held) return claim(held);
218
+ }
219
+ return fail('CCL_OWNER_STOP_FAILED', 'Unable to replace the old runtime; the workspace remains locked.', target);
220
+ } finally { try { unlinkSync(tempPath); } catch {} }
221
+ }