@myclaw163/clawclaw-cli 0.8.31 → 0.8.33

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.8.31",
3
+ "version": "0.8.33",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -87,7 +87,7 @@ function commandPath(raw) {
87
87
  if (second.includes('/')) return 'trigger';
88
88
  return `trigger ${second}`;
89
89
  }
90
- if (first === 'perception') return 'perception';
90
+ if (first === 'perception') return second === 'rename' ? 'perception rename' : 'perception';
91
91
  if (first === 'speak' || first === 'vote' || first === 'aside') return first;
92
92
  if (first === 'load') return 'load';
93
93
  return null;
@@ -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.105
4
+ version: 4.8.107
5
5
  ---
6
6
 
7
7
  # 龙虾杀(ClawClaw)
@@ -14,7 +14,7 @@ version: 4.8.105
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 暂不使用这套重名处理。
17
+ 策略、感知和人设的 Agent 操作名可能带 `_1`、`_2` 后缀,用于区分已分配同名操作名的资源。尚未装配的资源用 `selection_ref` 唯一选择;结合 `declared_id`、`working_copy_path`、`resource_id` 和作者信息核对目标,再执行返回 guidance 中的装配命令。首次装配时才确定 Agent 操作名;已经确定的操作名按账号保存,取消装配后不重新编号。执行 list/info/start、冲突选择和配置时使用 CCL 返回的完整操作名或明确提供的 `selection_ref`,不自行去掉后缀、不按显示名称猜测。操作名不改变脚本内容或 Hub 身份。辅助 Skill 暂不使用这套重名处理。
18
18
 
19
19
  ### 1.1 默认使用 Monitor 直推 + `ccl events` 详情
20
20
 
@@ -134,7 +134,7 @@ Claude/Claude Code 的局内行动不要改走 Channel MCP 工具。
134
134
  ccl load
135
135
  ```
136
136
 
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` 是首次发现的纯本地资源:只询问玩家一次是否装配,并执行返回 guidance 中明确给出的 `ccl capability equip` 或 `ccl capability unequip`,保存后不重复询问。资源展示优先使用英文 metadata,只有中文 metadata 时保留中文原文。本地修改优先使用;无并发差异时 CCL 自动上传,并发差异时使用本地并让玩家选择 `ccl capability resolve ... --use local|cloud|later`。静态检查绝不 import 或执行源码;可用清单只表示静态契约通过,动态 import/启动仍可能失败并由 Runtime 诊断隔离。`participation` 是执行当刻的后端快照;字段缺失时不要猜。
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
139
  `ccl load` 的同步结果按下面规则处理,不自行扩展状态机:
140
140
 
@@ -149,10 +149,12 @@ ccl load
149
149
 
150
150
  Hub 失败按 `code`、`operation` 和 `hint` 处理,不按 HTTP 422 猜测账号错误。装配的 `SKILL_NAME_CONFLICT` 必须让玩家到 Hub 处理同名冲突,完成后重新完整 `ccl load`;Agent 不自动卸载、替换或重试同名装配。创建/fork 同名失败不能按名称关联或覆盖已有资源;`INVALID_SKILL_NAME`、`SKILL_NAME_IMMUTABLE` 要修正源文件或明确新建资源,`SKILL_NAME_KEY_MISSING` 要联系运维。`WORKSPACE_REVISION_CONFLICT` 已由 CCL 刷新后有限重试,仍失败时不要循环重放。详细错误处理见 `references/HUB.md`。
151
151
 
152
- `changes.cloud_sync.fork_replacements[]` 表示云端编辑原资源 A 后,自己的 B 已替换原装配,并完成本地关联。告诉玩家当前使用的 B 操作名;如果同时存在 B 的 `conflicts[]`,说明本地和云端有不同修改,继续使用本地并询问 local/cloud/later。选择时使用冲突返回的 B 操作名:local 在命令内更新自己的 B,cloud 先保存本地草稿再采用云端 B,later 保留本地和冲突。A 原文件与原操作名保留。`FORK_RECONCILIATION_SKIPPED` 或 `skipped.reason=fork_relationship_unresolved` 表示关系不明确、没有自动衔接,必须说明原因和文件保留事实,不按同名猜测关系或自行上传旧副本。
152
+ `changes.cloud_sync.fork_replacements[]` 表示云端编辑原资源 A 后,自己的 B 已替换原装配,并完成本地关联。告诉玩家当前使用的 B 操作名。A 的本地内容未改动或已与 B 一致时,CCL 跟随 Hub 退役 A 的本地工作副本;A 有 B 尚未包含的本地修改时,不自动上传到 B,而是在 B 的 `conflicts[]` 中要求现有 local/cloud/later 选择。冲突未解决时继续保留本地内容,选择时使用冲突返回的 B 操作名或 `selection_ref`:local 在命令内更新自己的 B,cloud 先保存本地草稿再采用云端 B,later 保留本地和冲突。`FORK_RECONCILIATION_SKIPPED` 或 `skipped.reason=fork_relationship_unresolved` 表示关系不明确、没有自动衔接,必须说明原因和文件保留事实,不按同名猜测关系或自行上传旧副本。
153
153
 
154
154
  `ccl capability equip` 和 `ccl capability unequip` 立即保存装配状态;已经上传的本地能力会同时更新 Hub Workspace,Skill 还会立即切换四个宿主链接。全新本地能力上传成功时,CCL 也会把已经保存的装配选择同步给新建的 Workspace Item。`ccl capability resolve ... --use local` 在命令内只上传所选资源,`--use cloud` 在命令内保存草稿并切换工作副本。执行上述任一实际修改后,不得直接运行 `start`、`join` 或好友房开局命令:开局前必须重新执行一次完整 `ccl load`,以最终输出刷新 Persona、能力清单、同步结果和 `participation`;若新的 load 又产生待选择或冲突,处理后再次 load。`--use later` 不修改有效内容,不要求为此重复 load。不要用 `behavior list` 代替这次赛前 load。
155
155
 
156
+ 玩家明确要求修改已装配资源的本地操作名时,按类型使用 `ccl behavior rename <当前操作名> <新操作名>`、`ccl perception rename <当前操作名> <新操作名>` 或 `ccl persona rename <当前操作名> <新操作名>`。先用当前 list/info 核对目标,不能把源码 `declared_id` 或 Hub 展示名当作当前操作名。新名字不能与同账号、同类型中已分配的操作名冲突;已取消装配但保留映射的资源仍占名,未装配且从未分配操作名的资源不占名。命令只修改本地操作名及其配置引用,不修改源码 ID、文件路径或 Hub 身份;Owner Runtime 正在运行时拒绝改名。成功后完整执行 `ccl load` 再开局。不要自行编辑登记文件或直接删去 `_1`。
157
+
156
158
  如果 `participation` 显示后端已有匹配、房间或对局,但当前会话没有健康 Monitor,第一步统一在新的 30 分钟 Monitor(`timeout_ms=1800000`)中运行裸 `ccl join`,等待第一条非 error 通知。即使玩家原话是“创建房间”“创建训练房”“加入其他房间”或“开始匹配”,也先跟上现有参与,再判断是否需要切换;这次 `join` 是断线恢复,不是切换,不需要先征求退出确认。
157
159
 
158
160
  跟上当前参与后,不要把玩家原话机械套进固定句式表。先分开判断三件事:玩家是在继续当前参与还是进入新的参与;目标房间的精确类型是否已经知道;执行目标是否需要退出当前参与。
@@ -46,7 +46,9 @@ Runtime 另外允许 `duration_ms` 或 `timeout_ms`,两者只能选一个,
46
46
 
47
47
  ### 修改已安装策略的源码
48
48
 
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`。不要从相同显示名称推断两项是同一资源,不要去掉后缀后再执行指令。
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` / `ccl load` 的 `selection_ref` 选择,结合路径、作者和 `hub.resourceId` 确认目标;装配后再以返回的操作名执行 Behavior。不要从相同显示名称推断两项是同一资源,不要去掉已分配的后缀后再执行指令。
50
+
51
+ 玩家明确要求修改当前已装配 Behavior 的本地操作名时,可运行 `ccl behavior rename <当前id> <新id>`。先用 `list/info` 确认当前 id;新 id 须符合 Behavior ID 字符规则且未被其他已分配的 Behavior 操作名占用。它不修改源码 manifest ID、工作文件或 Hub 资源。fallback 与 Trigger 的本地绑定会随操作名更新,重新 `ccl load` 后用于下一次 Runtime。
50
52
 
51
53
  | 账号内路径 | 用途 |
52
54
  |---|---|
@@ -6,9 +6,11 @@
6
6
 
7
7
  ## 赛前(设置)
8
8
 
9
- 云端编辑第三方 A 得到自己的 B 时,`load` 可返回 `changes.cloud_sync.fork_replacements`(含 A/B 资源 ID、操作名和内容决议)。B 若有冲突,使用 B 的完整操作名执行 `ccl capability resolve <type/id> --use local|cloud|later`;local 更新 B 的新版本,cloud 先存本地草稿,later 继续本地且不上传。取消再重新装配不能清掉未解决冲突。`FORK_RECONCILIATION_SKIPPED` 明确说明无法自动衔接的原因;A/B 文件均保留,不把来源不明的副本自动上传。
9
+ 云端编辑第三方 A 得到自己的 B 时,`load` 可返回 `changes.cloud_sync.fork_replacements`(含 A/B 资源 ID、操作名和内容决议)。A 的本地内容未改动或已与 B 一致时,CCL 退役 A 的本地工作副本;A 有 B 尚未包含的本地修改时,B 报冲突且不自动上传。使用 B 的完整操作名执行 `ccl capability resolve <type/id> --use local|cloud|later`;local 更新 B 的新版本,cloud 先存本地草稿,later 继续本地且不上传。取消再重新装配不能清掉未解决冲突。`FORK_RECONCILIATION_SKIPPED` 明确说明无法自动衔接的原因;关系不明时保留文件,不把来源不明的副本自动上传。
10
10
 
11
- 策略、感知和人设的命令参数使用 CCL 返回的本地操作名,如 `xx`、`xx_1`;不同资源同名时均可存在,名称按账号持久保存,取消装配或更新版本不重新编号。`behavior list/info` 和 `perception --list` 返回 `declared_id`、`working_copy_path`、`runtime_source_path`;`persona list` 返回操作名、原名、路径和可用的 Hub 身份。后缀不写入原脚本或 Hub。辅助 Skill 的重名规则本轮不变。
11
+ 策略、感知和人设装配后的 Agent 命令使用 CCL 返回的本地操作名,如 `xx`、`xx_1`;首次装配才确定操作名,已有名称按账号持久保存,取消装配或更新版本不重新编号。未装配项用 `selection_ref` 作为装配选择器,先核对其 `declared_id`、`working_copy_path`、Hub `resource_id` 与作者身份。`behavior list/info` 和 `perception --list` 返回运行操作名、`declared_id`、`working_copy_path`、`runtime_source_path`;`persona list` 返回操作名、`selection_ref`、原名、路径和可用的 Hub 身份。后缀不写入原脚本或 Hub。辅助 Skill 的重名规则本轮不变。
12
+
13
+ 用户要求自定义已装配资源的本地操作名时,用 `ccl behavior rename xx_1 xx`、`ccl perception rename xx_1 xx` 或 `ccl persona rename xx_1 xx`。当前操作名由对应 list/info 返回;同账号同类型的已分配操作名(包括暂时取消装配的资源)不能重复。命令会同步本地 fallback、Trigger、禁用项或人设选择中的引用,不修改原脚本 ID、路径、Hub 标题与资源 ID。Owner Runtime 正在运行时拒绝改名;成功后重新完整 `ccl load`。
12
14
 
13
15
  ```bash
14
16
  ccl account register --check # 先探:本服务器是否需要邀请码 + 该用哪段固定话术;绝不建号
@@ -42,6 +42,7 @@ import {
42
42
  } from '../lib/capability-workspace.js';
43
43
  import { readFileSync } from 'node:fs';
44
44
  import { selectCapability } from '../lib/capability-selection.js';
45
+ import { renameCapabilityOperationWhenIdle } from '../lib/capability-operation-rename.js';
45
46
 
46
47
  const OWNER_CONTROL_TIMEOUT_MS = 30_000;
47
48
  const MAX_BEHAVIOR_RUNTIME_MS = 120_000;
@@ -347,6 +348,16 @@ export function createBehaviorCommand(dependencies: BehaviorCommandDependencies
347
348
  : '<active-account>/capabilities/behaviors';
348
349
  return `\nBehavior modules:\n Place .ts or .js files in ${directory}\n Discovery reads static manifests without executing module code.\n`;
349
350
  });
351
+ behavior.addCommand(new Command('rename')
352
+ .description('Rename one equipped Behavior operation for the active account')
353
+ .argument('<current-id>', 'Current CCL operation name')
354
+ .argument('<new-id>', 'New account-local operation name')
355
+ .allowExcessArguments(false)
356
+ .action(async (currentId: string, newId: string) => {
357
+ console.log(JSON.stringify(await renameCapabilityOperationWhenIdle(
358
+ getWorkspaceDir(), activeProfile(dependencies), 'behavior', currentId, newId,
359
+ ), null, 2));
360
+ }));
350
361
 
351
362
  behavior.addCommand(new Command('list')
352
363
  .description('List statically discovered Behavior modules')
@@ -2,12 +2,12 @@ import { Command, InvalidArgumentError } from 'commander';
2
2
  import { AuthStore, type AuthProfile } from '../lib/auth.js';
3
3
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
4
4
  import {
5
+ capabilitySelectionRef,
5
6
  capabilityWorkspacePath,
6
7
  pendingCapabilitySelections,
7
8
  readCapabilityWorkspaceRegistry,
8
9
  saveCapabilityDirectoryDraft,
9
10
  saveCapabilityDraft,
10
- setCapabilitySelection,
11
11
  setCapabilityConflictChoice,
12
12
  updateCapabilityHubIdentity,
13
13
  type CapabilityWorkspaceEntry,
@@ -199,16 +199,17 @@ async function updateSelection(
199
199
  }
200
200
  if (type === 'persona' && equipped) {
201
201
  writePersonaSelection(workspaceDir, profile, entry.hub
202
- ? { source: 'hub' } : { source: 'local', id });
202
+ ? { source: 'hub' } : { source: 'local', id: entry.runtimeId });
203
203
  } else if (type === 'persona') {
204
204
  // Do not clear another active Persona when this particular item is unequipped.
205
205
  const selected = readPersonaSelection(workspaceDir, profile);
206
- if (selected?.source === 'local' && selected.id === id) {
206
+ if (selected?.source === 'local' && selected.id === entry.runtimeId) {
207
207
  writePersonaSelection(workspaceDir, profile, { source: 'hub' });
208
208
  }
209
209
  }
210
210
  return {
211
- capability: `${type}/${id}`, equipped, selection: entry.selection,
211
+ capability: `${type}/${entry.runtimeId}`, selection_ref: capabilitySelectionRef(entry),
212
+ equipped, selection: entry.selection,
212
213
  effective: skipped && equipped ? 'skipped' : 'immediate', reload_required_before_game: true,
213
214
  ...(skipped ? { skipped: [skipped] } : {}),
214
215
  };
@@ -224,7 +225,8 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
224
225
  const workspaceDir = getWorkspaceDir();
225
226
  const profile = activeProfile();
226
227
  discoverLocalCapabilities(workspaceDir, profile);
227
- console.log(JSON.stringify({ pending: pendingCapabilitySelections(workspaceDir, profile) }, null, 2));
228
+ console.log(JSON.stringify({ pending: pendingCapabilitySelections(workspaceDir, profile)
229
+ .map(entry => ({ ...entry, selection_ref: capabilitySelectionRef(entry) })) }, null, 2));
228
230
  }));
229
231
 
230
232
  capability.addCommand(new Command('list')
@@ -234,7 +236,8 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
234
236
  const profile = activeProfile();
235
237
  discoverLocalCapabilities(workspaceDir, profile);
236
238
  console.log(JSON.stringify({
237
- capabilities: Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries),
239
+ capabilities: Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
240
+ .map(entry => ({ ...entry, selection_ref: capabilitySelectionRef(entry) })),
238
241
  }, null, 2));
239
242
  }));
240
243
 
@@ -266,10 +269,12 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
266
269
  const { type, id } = parseRef(ref);
267
270
  const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
268
271
  const matches = Object.values(registry.entries).filter((entry) => (
269
- entry.type === type && entry.runtimeId === id && entry.hub
272
+ entry.type === type && entry.hub && (id.startsWith('@')
273
+ ? capabilitySelectionRef(entry) === `${type}/${id}` : entry.runtimeId === id)
270
274
  ));
271
275
  if (matches.length !== 1) throw new Error(`capability_conflict_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${ref}`);
272
276
  const entry = matches[0]!;
277
+ const operationId = entry.runtimeId;
273
278
  if (opts.use === 'local') {
274
279
  const storedSnapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
275
280
  if (!storedSnapshot) throw new Error(`capability_local_upload_requires_load:${ref}`);
@@ -281,10 +286,10 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
281
286
  snapshot,
282
287
  { entryKeys: [entry.key] },
283
288
  );
284
- const uploaded = synced.uploaded.find((item) => item.type === type && item.id === id);
285
- const unchanged = synced.unchanged.some((item) => item.type === type && item.id === id);
286
- const conflict = synced.conflicts.find((item) => item.type === type && item.id === id);
287
- const failures = synced.failed.filter((item) => item.type === type && item.id === id);
289
+ const uploaded = synced.uploaded.find((item) => item.type === type && item.id === operationId);
290
+ const unchanged = synced.unchanged.some((item) => item.type === type && item.id === operationId);
291
+ const conflict = synced.conflicts.find((item) => item.type === type && item.id === operationId);
292
+ const failures = synced.failed.filter((item) => item.type === type && item.id === operationId);
288
293
  if (!uploaded && !unchanged) {
289
294
  if (conflict) throw new Error(`capability_upload_conflict:${ref}`);
290
295
  throw new CommandOutputError(`capability_upload_failed:${ref}:${failures[0]?.error ?? 'unknown'}`, {
@@ -292,7 +297,7 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
292
297
  });
293
298
  }
294
299
  console.log(JSON.stringify({
295
- capability: ref,
300
+ capability: `${type}/${operationId}`,
296
301
  resolution: 'local',
297
302
  effective: 'immediate',
298
303
  upload: uploaded ? {
@@ -309,7 +314,7 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
309
314
  if (opts.use === 'later') {
310
315
  setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined);
311
316
  console.log(JSON.stringify({
312
- capability: ref,
317
+ capability: `${type}/${operationId}`,
313
318
  resolution: 'deferred',
314
319
  effective: 'current_local',
315
320
  reload_required_before_game: false,
@@ -330,7 +335,7 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
330
335
  try {
331
336
  draft = saveCapabilityDirectoryDraft(workspaceDir, profile, {
332
337
  type,
333
- runtimeId: id,
338
+ runtimeId: operationId,
334
339
  sourcePath: target,
335
340
  });
336
341
  const replaced = overwriteAgentSkillTarget(staged.root, target);
@@ -342,7 +347,7 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
342
347
  } else {
343
348
  draft = saveCapabilityDraft(workspaceDir, profile, {
344
349
  type,
345
- runtimeId: id,
350
+ runtimeId: operationId,
346
351
  bytes: readFileSync(target),
347
352
  extension: extname(target),
348
353
  });
@@ -360,7 +365,7 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
360
365
  });
361
366
  setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined);
362
367
  console.log(JSON.stringify({
363
- capability: ref,
368
+ capability: `${type}/${operationId}`,
364
369
  resolution: 'cloud',
365
370
  draft,
366
371
  effective: 'immediate',
@@ -56,6 +56,8 @@ import {
56
56
  import { resolveClawclawResourceMetadata } from '../sdk/resource-metadata.js';
57
57
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
58
58
  import {
59
+ capabilitySelectionRef,
60
+ capabilityWorkspacePath,
59
61
  classifyStrategyLifecycle,
60
62
  pendingCapabilitySelections,
61
63
  registerDiscoveredCapability,
@@ -849,13 +851,18 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
849
851
  candidate.type === value.type
850
852
  && candidate.id === value.id
851
853
  && candidate.resource_id === value.resource_id
852
- )) === index);
854
+ )) === index).map(value => {
855
+ const entry = capabilityEntryForHubResource(workspaceDir, profile, value.type, value.resource_id);
856
+ return { ...value, ...(entry ? { selection_ref: capabilitySelectionRef(entry),
857
+ working_copy_path: capabilityWorkspacePath(workspaceDir, profile, entry) } : {}) };
858
+ });
853
859
  const cloudFailures = [...cloudRefreshChanges.failed, ...(cloudChanges?.failed ?? [])];
854
860
  const forkReplacements = newForkReplacements.map(item => {
855
861
  const type = item.resourceType === 'strategy' ? 'behavior' : item.resourceType;
856
862
  const entry = capabilityEntryForHubResource(workspaceDir, profile, type, item.resourceId);
857
863
  const finalItem = Object.values(activeWorkspace?.items ?? {}).flat().find(current => current.resourceId === item.resourceId);
858
864
  return { type, id: entry?.runtimeId, resource_id: item.resourceId,
865
+ ...(entry ? { selection_ref: capabilitySelectionRef(entry) } : {}),
859
866
  forked_from_resource_id: item.forkReconciliation!.parentResourceId,
860
867
  from_id: item.forkReconciliation!.parentOperationName,
861
868
  resolution: finalItem?.resolution ?? item.resolution,
@@ -947,8 +954,14 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
947
954
  selection_required: selectionRequired.map((entry) => ({
948
955
  type: entry.type,
949
956
  id: entry.runtimeId,
957
+ declared_id: entry.declaredId ?? entry.runtimeId,
958
+ selection_ref: capabilitySelectionRef(entry),
959
+ working_copy_path: capabilityWorkspacePath(workspaceDir, profile, entry),
960
+ title: entry.title,
961
+ ...(entry.hub ? { resource_id: entry.hub.resourceId, publisher: entry.hub.publisher,
962
+ owner_id: entry.hub.ownerId, owner_name: entry.hub.ownerName } : {}),
950
963
  strategy_type: entry.strategyLifecycle,
951
- action: `Choose once with ccl capability equip ${entry.type}/${entry.runtimeId} or ccl capability unequip ${entry.type}/${entry.runtimeId}.`,
964
+ action: `Choose once with ccl capability equip ${capabilitySelectionRef(entry)} or ccl capability unequip ${capabilitySelectionRef(entry)}.`,
952
965
  })),
953
966
  },
954
967
  configuration_warnings: compactConfigurationWarnings(configurationWarnings),
@@ -21,6 +21,7 @@ import { pluginApiVersionStatus } from '../runtime/clawclaw/plugins/plugin-api-v
21
21
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
22
22
  import { capabilityEntryForPath, readCapabilityWorkspaceRegistry } from '../lib/capability-workspace.js';
23
23
  import { selectCapability } from '../lib/capability-selection.js';
24
+ import { renameCapabilityOperationWhenIdle } from '../lib/capability-operation-rename.js';
24
25
 
25
26
  export interface PerceptionCommandDependencies {
26
27
  activeProfile?: () => AuthProfile | null;
@@ -136,5 +137,15 @@ Perception modules:
136
137
  }
137
138
  cmd.help();
138
139
  });
140
+ cmd.addCommand(new Command('rename')
141
+ .description('Rename one equipped Perception operation for the active account')
142
+ .argument('<current-id>', 'Current CCL operation name')
143
+ .argument('<new-id>', 'New account-local operation name')
144
+ .allowExcessArguments(false)
145
+ .action(async (currentId: string, newId: string) => {
146
+ console.log(JSON.stringify(await renameCapabilityOperationWhenIdle(
147
+ getWorkspaceDir(), activeProfile(dependencies), 'perception', currentId, newId,
148
+ ), null, 2));
149
+ }));
139
150
  return cmd;
140
151
  }
@@ -15,11 +15,12 @@ import {
15
15
  } from '../lib/user-data.js';
16
16
  import { loadPersonaSnapshot } from '../lib/load-context.js';
17
17
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
18
- import { setCapabilitySelection } from '../lib/capability-workspace.js';
19
- import { readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry, capabilityEntryForPath, capabilityWorkspacePath } from '../lib/capability-workspace.js';
18
+ import { readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry, capabilityEntryForPath,
19
+ capabilitySelectionRef, capabilityWorkspacePath } from '../lib/capability-workspace.js';
20
20
  import { selectCapability } from '../lib/capability-selection.js';
21
21
  import { HubClient } from '../lib/hub-client.js';
22
22
  import { readLocalAgentWorkspaceSnapshot } from '../lib/agent-workspace-sync.js';
23
+ import { renameCapabilityOperationWhenIdle } from '../lib/capability-operation-rename.js';
23
24
 
24
25
  function context() {
25
26
  const profile = new AuthStore().getActive();
@@ -39,6 +40,16 @@ export function createPersonaCommand(): Command {
39
40
  .alias('prs')
40
41
  .description('Per-account roleplay persona notes');
41
42
 
43
+ persona
44
+ .command('rename <current-id> <new-id>')
45
+ .description('Rename one equipped Persona operation for the active account')
46
+ .action(async (currentId: string, newId: string) => {
47
+ const { workspaceDir, profile } = context();
48
+ console.log(JSON.stringify(await renameCapabilityOperationWhenIdle(
49
+ workspaceDir, profile, 'persona', currentId, newId,
50
+ ), null, 2));
51
+ });
52
+
42
53
  persona
43
54
  .command('list')
44
55
  .description('List local persona presets for the active account')
@@ -48,8 +59,10 @@ export function createPersonaCommand(): Command {
48
59
  resolveActivePersonaFile();
49
60
  const presets = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
50
61
  .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,
62
+ .map(entry => ({ id: entry.runtimeId, selection_ref: capabilitySelectionRef(entry),
63
+ name: entry.title, declared_id: entry.declaredId ?? entry.runtimeId,
52
64
  source: entry.hub ? 'hub' : 'local', resource_id: entry.hub?.resourceId,
65
+ owner_id: entry.hub?.ownerId, owner_name: entry.hub?.ownerName,
53
66
  path: capabilityWorkspacePath(workspaceDir, profile, entry), selection: entry.selection }));
54
67
  console.log(JSON.stringify({ presets }, null, 2));
55
68
  });
@@ -75,12 +88,13 @@ export function createPersonaCommand(): Command {
75
88
  const { directory, workspaceDir, profile } = context();
76
89
  const created = createPersonaPreset(name, directory);
77
90
  discoverLocalCapabilities(workspaceDir, profile);
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 });
91
+ const discovered = capabilityEntryForPath(workspaceDir, profile, 'persona', created.path)!;
92
+ const entry = await selectCapability(workspaceDir, profile, 'persona',
93
+ capabilitySelectionRef(discovered).slice('persona/'.length), true);
94
+ writePersonaSelection(workspaceDir, profile, { source: 'local', id: entry.runtimeId });
81
95
  console.log(JSON.stringify({
82
96
  path: created.path,
83
- preset: { id: operationName, name: created.name, source: 'local' },
97
+ preset: { id: entry.runtimeId, name: created.name, source: 'local' },
84
98
  }, null, 2));
85
99
  });
86
100
 
@@ -92,9 +106,12 @@ export function createPersonaCommand(): Command {
92
106
  discoverLocalCapabilities(workspaceDir, profile);
93
107
  resolveActivePersonaFile();
94
108
  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);
109
+ .filter(entry => entry.type === 'persona' && (entry.runtimeId === presetName
110
+ || capabilitySelectionRef(entry) === `persona/${presetName}`));
111
+ if (named.length > 1) throw new Error(`persona_selection_ambiguous:${presetName}:use_selection_ref`);
112
+ if (named.length === 1) {
113
+ const entry = await selectCapability(workspaceDir, profile, 'persona',
114
+ capabilitySelectionRef(named[0]!).slice('persona/'.length), true);
98
115
  writePersonaSelection(workspaceDir, profile, entry.hub ? { source: 'hub' } : { source: 'local', id: entry.runtimeId });
99
116
  console.log(JSON.stringify({ path: capabilityWorkspacePath(workspaceDir, profile, entry),
100
117
  preset: { id: entry.runtimeId, name: entry.title, source: entry.hub ? 'hub' : 'local' } }, null, 2));
@@ -106,8 +123,9 @@ export function createPersonaCommand(): Command {
106
123
  throw new Error(`Persona preset "${presetName}" not found. Available: ${available}`);
107
124
  }
108
125
  discoverLocalCapabilities(workspaceDir, profile);
109
- const operationName = capabilityEntryForPath(workspaceDir, profile, 'persona', found.path)!.runtimeId;
110
- const entry = await selectCapability(workspaceDir, profile, 'persona', operationName, true);
126
+ const discovered = capabilityEntryForPath(workspaceDir, profile, 'persona', found.path)!;
127
+ const entry = await selectCapability(workspaceDir, profile, 'persona',
128
+ capabilitySelectionRef(discovered).slice('persona/'.length), true);
111
129
  writePersonaSelection(workspaceDir, profile, entry.hub ? { source: 'hub' } : { source: 'local', id: entry.runtimeId });
112
130
  console.log(JSON.stringify({
113
131
  path: found.path,
@@ -116,6 +116,7 @@ export function listAgentWorkspaceBehaviorSources(
116
116
  initialDescription: source.description,
117
117
  hub: { resourceId: item.resourceId, versionId: item.versionId,
118
118
  workspaceItemId: item.workspaceItemId, publisher: item.hub?.publisher ?? 'community',
119
+ ownerId: item.hub?.ownerId, ownerName: item.hub?.ownerName,
119
120
  pendingForkConflict: item.forkReconciliation?.status === 'linked' && item.resolution === 'concurrent_difference' || undefined,
120
121
  ...(item.forkReconciliation?.status === 'unresolved' ? { forkRelationshipUnresolved: true } : {}),
121
122
  baseSha256: item.sourceFiles[0]?.sha256 },
@@ -149,6 +150,7 @@ export function listAgentWorkspacePerceptionSources(
149
150
  description: item.description, selectedByHub: true,
150
151
  initialDescription: source.description,
151
152
  hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId,
153
+ ownerId: item.hub?.ownerId, ownerName: item.hub?.ownerName,
152
154
  pendingForkConflict: item.forkReconciliation?.status === 'linked' && item.resolution === 'concurrent_difference' || undefined,
153
155
  ...(item.forkReconciliation?.status === 'unresolved' ? { forkRelationshipUnresolved: true } : {}),
154
156
  publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256 },
@@ -33,13 +33,16 @@ import {
33
33
  import {
34
34
  capabilityEntryForHubResource,
35
35
  capabilityWorkspacePath,
36
+ readCapabilityWorkspaceRegistry,
36
37
  registerDiscoveredCapability,
37
38
  updateCapabilityHubIdentity,
39
+ writeCapabilityWorkspaceRegistry,
38
40
  } from './capability-workspace.js';
39
41
  import { inspectClawclawBehaviorSource, behaviorSourceCompatibilityError } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
40
42
  import { listClawclawPerceptionSourcesInDirectory } from '../runtime/clawclaw/plugins/perception/perception-source.js';
41
43
  import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js';
42
44
  import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js';
45
+ import { updateGameplayConfig } from './gameplay-config.js';
43
46
 
44
47
  const RESOURCE_TYPES: readonly ResourceType[] = ['skill', 'strategy', 'persona', 'perception'];
45
48
  const SHA256 = /^[0-9a-f]{64}$/;
@@ -694,6 +697,59 @@ function writeCurrentPointer(
694
697
  renameSync(temporary, target);
695
698
  }
696
699
 
700
+ type ForkWorkspaceType = 'behavior' | 'persona' | 'perception';
701
+ type ForkParentRetirement = { type: ForkWorkspaceType; resourceId: string;
702
+ childResourceId: string; path: string; sha256: string; clean: boolean };
703
+
704
+ function retireReplacedForkParent(
705
+ workspaceDir: string,
706
+ profile: Pick<AuthProfile, 'apiKey'>,
707
+ parent: ForkParentRetirement,
708
+ transferOperationName: boolean,
709
+ ): void {
710
+ const entry = capabilityEntryForHubResource(workspaceDir, profile, parent.type, parent.resourceId);
711
+ if (!entry || !existsSync(parent.path) || sha256(readFileSync(parent.path)) !== parent.sha256) return;
712
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
713
+ if (registry.entries[entry.key]?.hub?.resourceId !== parent.resourceId) return;
714
+ const child = Object.values(registry.entries).find(candidate => (
715
+ candidate.type === parent.type && candidate.hub?.resourceId === parent.childResourceId
716
+ ));
717
+ if (!child) return;
718
+ // A newly discovered B may inherit A's name. An already named B keeps its
719
+ // existing name even when A is retired during an upgrade from older CCL.
720
+ if (transferOperationName && child.declaredId === entry.declaredId
721
+ && !Object.values(registry.entries).some(candidate => (
722
+ candidate.key !== entry.key && candidate.key !== child.key
723
+ && candidate.type === parent.type && candidate.runtimeId === entry.runtimeId
724
+ ))) child.runtimeId = entry.runtimeId;
725
+ const oldOperationName = entry.runtimeId;
726
+ const newOperationName = child.runtimeId;
727
+ // Keep unique local edits at A's original path for recovery and the
728
+ // existing B-targeted conflict flow. A clean copy is redundant.
729
+ if (parent.clean) rmSync(parent.path, { force: true });
730
+ delete registry.entries[entry.key];
731
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
732
+ if (oldOperationName !== newOperationName && parent.type !== 'persona') {
733
+ updateGameplayConfig(config => {
734
+ if (parent.type === 'behavior') {
735
+ for (const role of Object.keys(config.fallback_behaviors) as Array<keyof typeof config.fallback_behaviors>) {
736
+ if (config.fallback_behaviors[role] === oldOperationName) {
737
+ config.fallback_behaviors[role] = newOperationName;
738
+ }
739
+ }
740
+ config.disabled_behaviors = [...new Set(config.disabled_behaviors.map(id =>
741
+ id === oldOperationName ? newOperationName : id))];
742
+ for (const trigger of Object.values(config.triggers)) {
743
+ if (trigger.behavior === oldOperationName) trigger.behavior = newOperationName;
744
+ }
745
+ } else {
746
+ config.disabled_perception_modules = [...new Set(config.disabled_perception_modules.map(id =>
747
+ id === oldOperationName ? newOperationName : id))];
748
+ }
749
+ }, workspaceDir, profile);
750
+ }
751
+ }
752
+
697
753
  export async function syncAgentWorkspaceConfig(
698
754
  workspaceDir: string,
699
755
  profile: Pick<AuthProfile, 'apiKey' | 'serverUrl'>,
@@ -707,6 +763,32 @@ export async function syncAgentWorkspaceConfig(
707
763
  const client = dependencies.client ?? new AgentWorkspaceClient(profile);
708
764
  const remote = await client.getConfig();
709
765
  validateRemoteConfig(remote);
766
+ if (previous && dependencies.workspaceInventory) {
767
+ const inventory = dependencies.workspaceInventory;
768
+ for (const item of Object.values(previous.items).flat()) {
769
+ const relation = item.forkReconciliation;
770
+ if (relation?.status !== 'linked' || inventory.some(candidate => candidate.resourceId === relation.parentResourceId)
771
+ || !inventory.some(candidate => candidate.resourceId === item.resourceId)) continue;
772
+ const type: ForkWorkspaceType = item.resourceType === 'strategy' ? 'behavior'
773
+ : item.resourceType as ForkWorkspaceType;
774
+ if (item.resourceType === 'skill') continue;
775
+ const parentEntry = capabilityEntryForHubResource(workspaceDir, profile, type, relation.parentResourceId);
776
+ if (!parentEntry) continue;
777
+ const path = capabilityWorkspacePath(workspaceDir, profile, parentEntry);
778
+ if (!existsSync(path)) continue;
779
+ const digest = sha256(readFileSync(path));
780
+ const remoteChild = remote.items[item.resourceType].find(candidate => candidate.resource_id === item.resourceId);
781
+ const clean = digest === parentEntry.hub?.baseSha256
782
+ || digest === remoteChild?.source_files[0]?.sha256;
783
+ // Older installations may already have a pending A/B conflict. Keep an
784
+ // unmatched A edit until that existing conflict has been resolved.
785
+ if (!clean) continue;
786
+ retireReplacedForkParent(workspaceDir, profile, {
787
+ type, resourceId: relation.parentResourceId, childResourceId: item.resourceId,
788
+ path, sha256: digest, clean,
789
+ }, false);
790
+ }
791
+ }
710
792
  const contentUnchanged = previous && RESOURCE_TYPES.every(type => {
711
793
  const items = previous.items[type];
712
794
  return items.length === remote.items[type].length && remote.items[type].every(item =>
@@ -740,6 +822,7 @@ export async function syncAgentWorkspaceConfig(
740
822
  const workingMetadataUpdates: Array<{ path: string; value: WorkingCopyMetadata }> = [];
741
823
  const forkReplacements: string[] = [];
742
824
  const forkRegistrations: Array<Parameters<typeof registerDiscoveredCapability>[2]> = [];
825
+ const replacedForkParents: ForkParentRetirement[] = [];
743
826
  const unresolvedParentKeys = new Set<string>();
744
827
  const previousByKey = new Map<ResourceType, Map<string, LocalAgentWorkspaceItem>>(
745
828
  RESOURCE_TYPES.map((type) => [
@@ -835,15 +918,22 @@ export async function syncAgentWorkspaceConfig(
835
918
  const digest = sha256(bytes);
836
919
  relation.status = 'linked';
837
920
  forkReplacements.push(item.resource_id);
838
- const localChanged = digest !== baseline && !knownVersions(parent).some(version => version.sourceSha256 === digest);
839
- if (localChanged && digest !== materialized.sourceFiles[0]?.sha256) {
921
+ const localChanged = digest !== baseline;
922
+ const childSha256 = materialized.sourceFiles[0]?.sha256;
923
+ if (!dependencies.workspaceInventory.some(candidate => candidate.resourceId === parent.resourceId)) {
924
+ replacedForkParents.push({ type: workspaceType, resourceId: parent.resourceId,
925
+ childResourceId: item.resource_id, path: parentPath, sha256: digest,
926
+ clean: !localChanged || digest === childSha256 });
927
+ }
928
+ if (localChanged && digest !== childSha256) {
840
929
  override = {
841
930
  bytes, sha256: digest,
842
931
  contentDigest: singleFileContentDigest(materialized.sourceFiles[0]!.relativePath, bytes),
843
932
  modifiedAtMs: statSync(parentPath).mtimeMs, originRecognized: true,
844
933
  };
845
- forkCloudChanged = baseline !== materialized.sourceFiles[0]?.sha256
846
- || parent.resolution === 'concurrent_difference' || parentEntry?.hub?.pendingForkConflict === true;
934
+ // A's uncommitted edit must be chosen explicitly before it is
935
+ // written to the newly owned B, even if B still equals A's base.
936
+ forkCloudChanged = true;
847
937
  }
848
938
  }
849
939
  materialized.forkReconciliation = relation;
@@ -983,6 +1073,7 @@ export async function syncAgentWorkspaceConfig(
983
1073
  renameSync(temporary, target);
984
1074
  writeCurrentPointer(workspaceDir, profile, { revision: remote.revision, relative_dir: relativeDir });
985
1075
  for (const registration of forkRegistrations) registerDiscoveredCapability(workspaceDir, profile, registration);
1076
+ for (const parent of replacedForkParents) retireReplacedForkParent(workspaceDir, profile, parent, true);
986
1077
  for (const key of unresolvedParentKeys) {
987
1078
  const parent = Object.values(previous?.items ?? {}).flat().find(item => {
988
1079
  const type = item.resourceType === 'strategy' ? 'behavior' : item.resourceType;
@@ -0,0 +1,136 @@
1
+ import { rmSync } from 'node:fs';
2
+ import type { AuthProfile } from './auth.js';
3
+ import {
4
+ capabilityWorkspacePath,
5
+ readCapabilityWorkspaceRegistry,
6
+ writeCapabilityWorkspaceRegistry,
7
+ type CapabilityWorkspaceType,
8
+ } from './capability-workspace.js';
9
+ import { readGameplayConfig, writeGameplayConfig } from './gameplay-config.js';
10
+ import { readPersonaSelection, writePersonaSelection } from './persona.js';
11
+ import { getUserDataAccountPersonaSelectionFile, getUserDataAccountTriggersDir } from './user-data.js';
12
+ import { listClawclawTriggerSources } from '../runtime/clawclaw/plugins/trigger/trigger-source.js';
13
+ import { sendProfileOwnerControlRequest } from '../runtime/owner-control.js';
14
+
15
+ export type RenameableCapabilityType = Exclude<CapabilityWorkspaceType, 'skill'>;
16
+
17
+ const MODULE_OPERATION_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;
18
+
19
+ function validName(type: RenameableCapabilityType, name: string): boolean {
20
+ if (type !== 'persona') return MODULE_OPERATION_NAME.test(name);
21
+ return !!name.trim() && name === name.trim() && name.length <= 255
22
+ && !/[\\/\u0000-\u001f]/u.test(name) && name !== '.' && name !== '..';
23
+ }
24
+
25
+ export async function renameCapabilityOperationWhenIdle(
26
+ workspaceDir: string,
27
+ profile: AuthProfile,
28
+ type: RenameableCapabilityType,
29
+ currentName: string,
30
+ newName: string,
31
+ ownerRequest: typeof sendProfileOwnerControlRequest = sendProfileOwnerControlRequest,
32
+ ) {
33
+ let owner;
34
+ try {
35
+ owner = await ownerRequest(profile, 'behavior_status', {}, 750);
36
+ } catch (error) {
37
+ const code = (error as NodeJS.ErrnoException).code;
38
+ if (code !== 'ENOENT' && code !== 'ECONNREFUSED') {
39
+ throw new Error('capability_operation_name_runtime_check_failed', { cause: error });
40
+ }
41
+ owner = null;
42
+ }
43
+ if (owner) throw new Error('capability_operation_name_runtime_active');
44
+ return renameCapabilityOperation(workspaceDir, profile, type, currentName, newName);
45
+ }
46
+
47
+ export function renameCapabilityOperation(
48
+ workspaceDir: string,
49
+ profile: Pick<AuthProfile, 'apiKey'>,
50
+ type: RenameableCapabilityType,
51
+ currentName: string,
52
+ newName: string,
53
+ ) {
54
+ if (!validName(type, newName)) {
55
+ throw new Error(`capability_operation_name_invalid:${type}:${newName}`);
56
+ }
57
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
58
+ const matches = Object.values(registry.entries).filter(entry => (
59
+ entry.type === type && entry.runtimeId === currentName
60
+ && entry.selection === 'equipped' && !entry.hub?.cloudStatus
61
+ && entry.operationNameAssigned !== false
62
+ ));
63
+ if (matches.length !== 1) {
64
+ throw new Error(`capability_operation_name_target_${matches.length ? 'ambiguous' : 'not_equipped'}:${type}:${currentName}`);
65
+ }
66
+ const entry = matches[0]!;
67
+ const path = capabilityWorkspacePath(workspaceDir, profile, entry);
68
+ const identity = { resource_id: entry.hub?.resourceId, declared_id: entry.declaredId ?? currentName,
69
+ working_copy_path: path };
70
+ if (newName === currentName) {
71
+ return { type, old_id: currentName, id: newName, changed: false,
72
+ scope: 'account_operation_name', effective: 'next_runtime',
73
+ ...identity, reload_required_before_game: false };
74
+ }
75
+ if (Object.values(registry.entries).some(other => (
76
+ other.key !== entry.key && other.type === type && other.runtimeId === newName
77
+ && other.operationNameAssigned !== false
78
+ ))) {
79
+ throw new Error(`capability_operation_name_conflict:${type}:${newName}`);
80
+ }
81
+
82
+ const beforeRegistry = structuredClone(registry);
83
+ const beforeGameplay = type === 'persona' ? undefined : readGameplayConfig(workspaceDir, profile);
84
+ const nextGameplay = beforeGameplay ? structuredClone(beforeGameplay) : undefined;
85
+ if (nextGameplay && type === 'behavior') {
86
+ for (const role of Object.keys(nextGameplay.fallback_behaviors) as Array<keyof typeof nextGameplay.fallback_behaviors>) {
87
+ if (nextGameplay.fallback_behaviors[role] === currentName) {
88
+ nextGameplay.fallback_behaviors[role] = newName;
89
+ }
90
+ }
91
+ nextGameplay.disabled_behaviors = [...new Set(nextGameplay.disabled_behaviors.map(id =>
92
+ id === currentName ? newName : id))];
93
+ for (const trigger of Object.values(nextGameplay.triggers)) {
94
+ if (trigger.behavior === currentName) trigger.behavior = newName;
95
+ }
96
+ for (const trigger of listClawclawTriggerSources(getUserDataAccountTriggersDir(workspaceDir, profile))) {
97
+ if (trigger.manifest.defaultBehavior === currentName
98
+ && nextGameplay.triggers[trigger.id]?.behavior === undefined) {
99
+ nextGameplay.triggers[trigger.id] = { ...nextGameplay.triggers[trigger.id], behavior: newName };
100
+ }
101
+ }
102
+ } else if (nextGameplay) {
103
+ nextGameplay.disabled_perception_modules = [...new Set(nextGameplay.disabled_perception_modules.map(id =>
104
+ id === currentName ? newName : id))];
105
+ }
106
+ const beforePersona = type === 'persona' ? readPersonaSelection(workspaceDir, profile) : undefined;
107
+ const nextPersona = beforePersona?.source === 'local' && beforePersona.id === currentName
108
+ ? { source: 'local' as const, id: newName } : undefined;
109
+
110
+ entry.runtimeId = newName;
111
+ entry.updatedAt = new Date().toISOString();
112
+ try {
113
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
114
+ if (nextGameplay && JSON.stringify(nextGameplay) !== JSON.stringify(beforeGameplay)) {
115
+ writeGameplayConfig(nextGameplay, workspaceDir, profile);
116
+ }
117
+ if (nextPersona) writePersonaSelection(workspaceDir, profile, nextPersona);
118
+ } catch (error) {
119
+ // Registry and command bindings must never intentionally disagree after a
120
+ // failed rename. Restore every touched local source of operation names.
121
+ try {
122
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, beforeRegistry);
123
+ if (beforeGameplay) writeGameplayConfig(beforeGameplay, workspaceDir, profile);
124
+ if (type === 'persona') {
125
+ if (beforePersona) writePersonaSelection(workspaceDir, profile, beforePersona);
126
+ else rmSync(getUserDataAccountPersonaSelectionFile(workspaceDir, profile), { force: true });
127
+ }
128
+ } catch (rollbackError) {
129
+ throw new Error(`capability_operation_name_rollback_failed:${String(rollbackError)}`, { cause: error });
130
+ }
131
+ throw error;
132
+ }
133
+ return { type, old_id: currentName, id: newName, changed: true,
134
+ scope: 'account_operation_name', effective: 'next_runtime',
135
+ ...identity, reload_required_before_game: true };
136
+ }
@@ -1,6 +1,7 @@
1
1
  import type { AuthProfile } from './auth.js';
2
2
  import { HubClient } from './hub-client.js';
3
- import { readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry,
3
+ import { assignCapabilityOperationName, capabilitySelectionRef,
4
+ readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry,
4
5
  type CapabilityWorkspaceType } from './capability-workspace.js';
5
6
  import { updateGameplayConfig } from './gameplay-config.js';
6
7
 
@@ -19,11 +20,11 @@ export async function selectCapability(
19
20
  providedClient?: EquipmentClient,
20
21
  ) {
21
22
  const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
22
- const matches = Object.values(registry.entries).filter(entry => entry.type === type && entry.runtimeId === id);
23
- const local = matches.filter(entry => entry.origin === 'local');
24
- const candidates = local.length ? local : matches;
25
- if (candidates.length !== 1) throw new Error(`capability_selection_${candidates.length ? 'ambiguous' : 'not_found'}:${type}:${id}`);
26
- const entry = candidates[0]!;
23
+ const matches = Object.values(registry.entries).filter(entry => entry.type === type && (
24
+ id.startsWith('@') ? capabilitySelectionRef(entry) === `${type}/${id}` : entry.runtimeId === id
25
+ ));
26
+ if (matches.length !== 1) throw new Error(`capability_selection_${matches.length ? 'ambiguous' : 'not_found'}:${type}:${id}`);
27
+ const entry = matches[0]!;
27
28
  if (entry.hub) {
28
29
  const client = providedClient ?? HubClient.fromProfile(profile);
29
30
  if (entry.hub.cloudStatus) throw new Error(`capability_workspace_removed:${type}/${id}`);
@@ -48,14 +49,15 @@ export async function selectCapability(
48
49
  }
49
50
  }
50
51
  }
52
+ if (equipped) assignCapabilityOperationName(registry, entry);
51
53
  entry.selection = equipped ? 'equipped' : 'unequipped';
52
54
  entry.updatedAt = new Date().toISOString();
53
55
  writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
54
56
  if (type === 'behavior' || type === 'perception') {
55
57
  updateGameplayConfig(config => {
56
58
  const field = type === 'behavior' ? 'disabled_behaviors' : 'disabled_perception_modules';
57
- config[field] = config[field].filter(value => value !== id);
58
- if (!equipped && !entry.hub) config[field].push(id);
59
+ config[field] = config[field].filter(value => value !== entry.runtimeId && value !== id);
60
+ if (!equipped && !entry.hub) config[field].push(entry.runtimeId);
59
61
  }, workspaceDir, profile);
60
62
  }
61
63
  return entry;
@@ -6,7 +6,7 @@ import {
6
6
  renameSync,
7
7
  writeFileSync,
8
8
  } from 'node:fs';
9
- import { randomUUID } from 'node:crypto';
9
+ import { createHash, randomUUID } from 'node:crypto';
10
10
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
11
  import type { AuthProfile } from './auth.js';
12
12
  import {
@@ -25,6 +25,8 @@ export interface CapabilityHubIdentity {
25
25
  versionId: string;
26
26
  workspaceItemId?: string;
27
27
  publisher: 'official' | 'self' | 'community';
28
+ ownerId?: string;
29
+ ownerName?: string | null;
28
30
  baseSha256?: string;
29
31
  lastUploadedSha256?: string;
30
32
  pendingBackpackRestoreResourceId?: string;
@@ -46,8 +48,10 @@ export interface CapabilityWorkspaceEntry {
46
48
  origin: 'local' | 'hub';
47
49
  relativePath: string;
48
50
  runtimeId: string;
49
- /** Original source identity. runtimeId is the account-local operation name. */
51
+ /** Original source identity. runtimeId becomes the stable Agent operation name on equip. */
50
52
  declaredId?: string;
53
+ /** New local discoveries have only a selection reference until first equip. */
54
+ operationNameAssigned?: boolean;
51
55
  title: string;
52
56
  description: string;
53
57
  selection: CapabilitySelection;
@@ -148,11 +152,17 @@ export function registerDiscoveredCapability(
148
152
  const now = new Date().toISOString();
149
153
  const previous = registry.entries[key];
150
154
  const declaredId = input.runtimeId;
155
+ const operationNameAssigned = input.type === 'skill' || (previous?.operationNameAssigned !== false
156
+ && (previous !== undefined || input.selectedByHub === true));
157
+ const assigningNow = input.type !== 'skill' && input.selectedByHub === true
158
+ && previous?.operationNameAssigned === false;
151
159
  const occupied = new Set(Object.values(registry.entries)
152
- .filter(entry => entry.type === input.type && entry.key !== key).map(entry => entry.runtimeId));
153
- let runtimeId = previous?.runtimeId ?? declaredId;
154
- // Keep retired/unselected entries in the registry: their operation names must
155
- // never silently point to a different script after the next load.
160
+ .filter(entry => entry.type === input.type && entry.key !== key
161
+ && (!operationNameAssigned || entry.operationNameAssigned !== false))
162
+ .map(entry => entry.runtimeId));
163
+ let runtimeId = assigningNow ? declaredId : previous?.runtimeId ?? declaredId;
164
+ // Already assigned operation names stay reserved across deselection. A new
165
+ // pending item has only a provisional management name and selection_ref.
156
166
  for (let suffix = 1; input.type !== 'skill' && occupied.has(runtimeId); suffix++) {
157
167
  const tail = `_${suffix}`;
158
168
  runtimeId = `${declaredId.slice(0, 255 - tail.length)}${tail}`;
@@ -164,6 +174,7 @@ export function registerDiscoveredCapability(
164
174
  relativePath,
165
175
  runtimeId,
166
176
  declaredId,
177
+ operationNameAssigned: operationNameAssigned || assigningNow,
167
178
  // Only a Hub snapshot may replace existing human-facing text. Rediscovering
168
179
  // a script must not overwrite it with Agent-facing documentation.
169
180
  title: (input.selectedByHub ? input.title?.trim() : undefined)
@@ -186,6 +197,30 @@ export function registerDiscoveredCapability(
186
197
  return entry;
187
198
  }
188
199
 
200
+ /** Stable management selector, independent of an Agent operation name. */
201
+ export function capabilitySelectionRef(entry: Pick<CapabilityWorkspaceEntry, 'key' | 'type'>): string {
202
+ const digest = createHash('sha256').update(entry.key, 'utf8').digest('hex');
203
+ return `${entry.type}/@${digest}`;
204
+ }
205
+
206
+ export function assignCapabilityOperationName(
207
+ registry: CapabilityWorkspaceRegistry,
208
+ entry: CapabilityWorkspaceEntry,
209
+ ): void {
210
+ if (entry.type === 'skill' || entry.operationNameAssigned !== false) return;
211
+ const declaredId = entry.declaredId ?? entry.runtimeId;
212
+ const occupied = new Set(Object.values(registry.entries)
213
+ .filter(other => other.key !== entry.key && other.type === entry.type
214
+ && other.operationNameAssigned !== false).map(other => other.runtimeId));
215
+ let operationName = declaredId;
216
+ for (let suffix = 1; occupied.has(operationName); suffix++) {
217
+ const tail = `_${suffix}`;
218
+ operationName = `${declaredId.slice(0, 255 - tail.length)}${tail}`;
219
+ }
220
+ entry.runtimeId = operationName;
221
+ entry.operationNameAssigned = true;
222
+ }
223
+
189
224
  export function capabilityEntryForPath(
190
225
  workspaceDir: string,
191
226
  profile: Pick<AuthProfile, 'apiKey'>,
@@ -220,9 +255,11 @@ export function setCapabilitySelection(
220
255
  ): CapabilityWorkspaceEntry {
221
256
  const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
222
257
  const matches = Object.values(registry.entries)
223
- .filter((entry) => entry.type === type && entry.runtimeId === runtimeId && entry.origin === 'local');
258
+ .filter((entry) => entry.type === type && entry.origin === 'local' && (runtimeId.startsWith('@')
259
+ ? capabilitySelectionRef(entry) === `${type}/${runtimeId}` : entry.runtimeId === runtimeId));
224
260
  if (matches.length !== 1) throw new Error(`capability_selection_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${type}:${runtimeId}`);
225
261
  const entry = matches[0]!;
262
+ if (equipped) assignCapabilityOperationName(registry, entry);
226
263
  entry.selection = equipped ? 'equipped' : 'unequipped';
227
264
  entry.updatedAt = new Date().toISOString();
228
265
  writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
@@ -139,6 +139,7 @@ function hubPersona(
139
139
  const entry = registerDiscoveredCapability(workspaceDir, profile, {
140
140
  type: 'persona', path: working, runtimeId: basename(working, '.md'), selectedByHub: true,
141
141
  hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId,
142
+ ownerId: item.hub?.ownerId, ownerName: item.hub?.ownerName,
142
143
  pendingForkConflict: item.forkReconciliation?.status === 'linked' && item.resolution === 'concurrent_difference' || undefined,
143
144
  ...(item.forkReconciliation?.status === 'unresolved' ? { forkRelationshipUnresolved: true } : {}),
144
145
  publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256 },