@myclaw163/clawclaw-cli 0.8.12 → 0.8.13

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.
@@ -0,0 +1,345 @@
1
+ import { Command, InvalidArgumentError } from 'commander';
2
+ import { AuthStore, type AuthProfile } from '../lib/auth.js';
3
+ import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
4
+ import {
5
+ capabilityWorkspacePath,
6
+ pendingCapabilitySelections,
7
+ readCapabilityWorkspaceRegistry,
8
+ saveCapabilityDirectoryDraft,
9
+ saveCapabilityDraft,
10
+ setCapabilitySelection,
11
+ setCapabilityConflictChoice,
12
+ updateCapabilityHubIdentity,
13
+ type CapabilityWorkspaceEntry,
14
+ type CapabilityWorkspaceType,
15
+ } from '../lib/capability-workspace.js';
16
+ import { getWorkspaceDir } from '../lib/init-command.js';
17
+ import { writePersonaSelection } from '../lib/persona.js';
18
+ import {
19
+ agentSkillTargets,
20
+ findSkillRoot,
21
+ linkAgentSkillTarget,
22
+ overwriteAgentSkillTarget,
23
+ unlinkAgentSkillTarget,
24
+ type SkillHostMutationResult,
25
+ } from '../lib/skill-host.js';
26
+ import { HubClient, type ResourceType } from '../lib/hub-client.js';
27
+ import { unzip } from '../lib/hub-unzip.js';
28
+ import { zipContentDigest } from '../lib/zip-store.js';
29
+ import { createHash, randomUUID } from 'node:crypto';
30
+ import { tmpdir } from 'node:os';
31
+ import { dirname, extname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path';
32
+ import {
33
+ existsSync,
34
+ mkdirSync,
35
+ mkdtempSync,
36
+ readFileSync,
37
+ readdirSync,
38
+ renameSync,
39
+ rmSync,
40
+ writeFileSync,
41
+ } from 'node:fs';
42
+ import {
43
+ readLocalAgentWorkspaceSnapshot,
44
+ resolveLocalAgentWorkspaceSnapshot,
45
+ } from '../lib/agent-workspace-sync.js';
46
+ import { syncCapabilitiesToCloud } from '../lib/capability-cloud-sync.js';
47
+
48
+ interface CapabilityResolveCloudClient {
49
+ getResource(type: ResourceType, id: string, workspaceItemId?: string): ReturnType<HubClient['getResource']>;
50
+ downloadArtifact(type: ResourceType, id: string, workspaceItemId?: string): ReturnType<HubClient['downloadArtifact']>;
51
+ }
52
+
53
+ export interface CapabilityCommandDependencies {
54
+ client?: CapabilityResolveCloudClient;
55
+ cloudSync?: typeof syncCapabilitiesToCloud;
56
+ skillTargets?: (name: string) => readonly string[];
57
+ linkSkillTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult;
58
+ unlinkSkillTarget?: (targetPath: string) => SkillHostMutationResult;
59
+ }
60
+
61
+ function pathInside(root: string, candidate: string): boolean {
62
+ const child = relative(resolvePath(root), resolvePath(candidate));
63
+ return child === '' || (!child.startsWith('..') && !isAbsolute(child));
64
+ }
65
+
66
+ function writeCloudFileAtomically(target: string, bytes: Buffer): void {
67
+ const stage = `${target}.ccl-stage-${randomUUID()}`;
68
+ const displaced = `${target}.ccl-old-${randomUUID()}`;
69
+ let moved = false;
70
+ try {
71
+ mkdirSync(dirname(target), { recursive: true });
72
+ writeFileSync(stage, bytes);
73
+ if (existsSync(target)) {
74
+ renameSync(target, displaced);
75
+ moved = true;
76
+ }
77
+ renameSync(stage, target);
78
+ if (moved) rmSync(displaced, { force: true });
79
+ } catch (error) {
80
+ rmSync(stage, { force: true });
81
+ if (moved && !existsSync(target) && existsSync(displaced)) {
82
+ try { renameSync(displaced, target); } catch { /* retain displaced recovery copy */ }
83
+ }
84
+ throw error;
85
+ }
86
+ }
87
+
88
+ function cloudSkillStage(archive: Buffer): { root: string; stage: string; digest: string } {
89
+ const stage = mkdtempSync(join(tmpdir(), 'ccl-capability-cloud-skill-'));
90
+ try {
91
+ for (const entry of unzip(archive)) {
92
+ const target = resolvePath(stage, ...entry.path.split('/'));
93
+ if (!pathInside(stage, target) || target === resolvePath(stage)) {
94
+ throw new Error('capability_cloud_skill_path_invalid');
95
+ }
96
+ mkdirSync(dirname(target), { recursive: true });
97
+ writeFileSync(target, entry.content);
98
+ }
99
+ const root = findSkillRoot(stage);
100
+ if (!existsSync(join(root, 'SKILL.md'))) throw new Error('capability_cloud_skill_invalid');
101
+ const files: Array<{ path: string; content: Buffer }> = [];
102
+ const visit = (directory: string): void => {
103
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
104
+ const path = join(directory, entry.name);
105
+ if (entry.isDirectory()) visit(path);
106
+ else if (entry.isFile()) files.push({
107
+ path: relative(root, path).replaceAll('\\', '/'),
108
+ content: readFileSync(path),
109
+ });
110
+ }
111
+ };
112
+ visit(root);
113
+ return { root, stage, digest: zipContentDigest(files) };
114
+ } catch (error) {
115
+ rmSync(stage, { recursive: true, force: true });
116
+ throw error;
117
+ }
118
+ }
119
+
120
+ function activeProfile(): AuthProfile {
121
+ const profile = new AuthStore().getActive();
122
+ if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
123
+ return profile;
124
+ }
125
+
126
+ function parseRef(value: string): { type: CapabilityWorkspaceType; id: string } {
127
+ const match = /^(behavior|perception|persona|skill)\/(\S.{0,254})$/u.exec(value);
128
+ if (!match) {
129
+ throw new InvalidArgumentError('expected <behavior|perception|persona|skill>/<id>');
130
+ }
131
+ return { type: match[1] as CapabilityWorkspaceType, id: match[2]! };
132
+ }
133
+
134
+ function applySkillSelection(
135
+ entry: CapabilityWorkspaceEntry,
136
+ equipped: boolean,
137
+ workspaceDir: string,
138
+ profile: AuthProfile,
139
+ dependencies: CapabilityCommandDependencies,
140
+ ): void {
141
+ const source = capabilityWorkspacePath(workspaceDir, profile, entry);
142
+ const targets = dependencies.skillTargets ?? agentSkillTargets;
143
+ const link = dependencies.linkSkillTarget ?? linkAgentSkillTarget;
144
+ const unlink = dependencies.unlinkSkillTarget ?? unlinkAgentSkillTarget;
145
+ const applied: string[] = [];
146
+ for (const target of targets(entry.runtimeId)) {
147
+ const result = equipped ? link(source, target) : unlink(target);
148
+ if (!result.ok) {
149
+ for (const completed of applied.reverse()) {
150
+ if (equipped) unlink(completed);
151
+ else link(source, completed);
152
+ }
153
+ throw new Error(`capability_skill_${equipped ? 'equip' : 'unequip'}_failed:${
154
+ result.error ?? result.stderr?.trim() ?? 'skill host mutation failed'
155
+ }`);
156
+ }
157
+ applied.push(target);
158
+ }
159
+ }
160
+
161
+ function updateSelection(
162
+ ref: string,
163
+ equipped: boolean,
164
+ dependencies: CapabilityCommandDependencies,
165
+ ): Record<string, unknown> {
166
+ const workspaceDir = getWorkspaceDir();
167
+ const profile = activeProfile();
168
+ discoverLocalCapabilities(workspaceDir, profile);
169
+ const { type, id } = parseRef(ref);
170
+ if (type === 'skill') {
171
+ const matches = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
172
+ .filter((candidate) => (
173
+ candidate.type === type && candidate.runtimeId === id && candidate.origin === 'local'
174
+ ));
175
+ if (matches.length !== 1) {
176
+ throw new Error(`capability_selection_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${type}:${id}`);
177
+ }
178
+ applySkillSelection(matches[0]!, equipped, workspaceDir, profile, dependencies);
179
+ }
180
+ const entry = setCapabilitySelection(workspaceDir, profile, type, id, equipped);
181
+ if (type === 'persona') {
182
+ writePersonaSelection(
183
+ workspaceDir,
184
+ profile,
185
+ equipped ? { source: 'local', id } : { source: 'none' },
186
+ );
187
+ }
188
+ return {
189
+ capability: `${type}/${id}`,
190
+ equipped,
191
+ selection: entry.selection,
192
+ effective: 'immediate',
193
+ reload_required_before_game: true,
194
+ };
195
+ }
196
+
197
+ export function createCapabilityCommand(dependencies: CapabilityCommandDependencies = {}): Command {
198
+ const capability = new Command('capability')
199
+ .alias('cap')
200
+ .description('Inspect and persist one-time local capability assembly choices');
201
+
202
+ capability.addCommand(new Command('pending')
203
+ .description('List newly discovered local capabilities awaiting one assembly choice')
204
+ .action(() => {
205
+ const workspaceDir = getWorkspaceDir();
206
+ const profile = activeProfile();
207
+ discoverLocalCapabilities(workspaceDir, profile);
208
+ console.log(JSON.stringify({ pending: pendingCapabilitySelections(workspaceDir, profile) }, null, 2));
209
+ }));
210
+
211
+ capability.addCommand(new Command('list')
212
+ .description('List persisted local capability assembly choices')
213
+ .action(() => {
214
+ const workspaceDir = getWorkspaceDir();
215
+ const profile = activeProfile();
216
+ discoverLocalCapabilities(workspaceDir, profile);
217
+ console.log(JSON.stringify({
218
+ capabilities: Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries),
219
+ }, null, 2));
220
+ }));
221
+
222
+ capability.addCommand(new Command('equip')
223
+ .argument('<type/id>', 'Local capability reference')
224
+ .allowExcessArguments(false)
225
+ .action((ref: string) => console.log(JSON.stringify(updateSelection(ref, true, dependencies), null, 2))));
226
+
227
+ capability.addCommand(new Command('unequip')
228
+ .argument('<type/id>', 'Local capability reference')
229
+ .allowExcessArguments(false)
230
+ .action((ref: string) => console.log(JSON.stringify(updateSelection(ref, false, dependencies), null, 2))));
231
+
232
+ capability.addCommand(new Command('resolve')
233
+ .description('Resolve one local/cloud content conflict')
234
+ .argument('<type/id>', 'Capability reference')
235
+ .requiredOption('--use <choice>', 'local | cloud | later')
236
+ .allowExcessArguments(false)
237
+ .action(async (ref: string, opts: { use: string }) => {
238
+ if (!['local', 'cloud', 'later'].includes(opts.use)) {
239
+ throw new InvalidArgumentError('--use must be local, cloud, or later');
240
+ }
241
+ const workspaceDir = getWorkspaceDir();
242
+ const profile = activeProfile();
243
+ const { type, id } = parseRef(ref);
244
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
245
+ const matches = Object.values(registry.entries).filter((entry) => (
246
+ entry.type === type && entry.runtimeId === id && entry.hub
247
+ ));
248
+ if (matches.length !== 1) throw new Error(`capability_conflict_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${ref}`);
249
+ const entry = matches[0]!;
250
+ if (opts.use === 'local') {
251
+ const storedSnapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
252
+ if (!storedSnapshot) throw new Error(`capability_local_upload_requires_load:${ref}`);
253
+ const snapshot = resolveLocalAgentWorkspaceSnapshot(workspaceDir, profile, storedSnapshot);
254
+ setCapabilityConflictChoice(workspaceDir, profile, entry.key, 'local');
255
+ const synced = await (dependencies.cloudSync ?? syncCapabilitiesToCloud)(
256
+ workspaceDir,
257
+ profile,
258
+ snapshot,
259
+ { entryKeys: [entry.key] },
260
+ );
261
+ const uploaded = synced.uploaded.find((item) => item.type === type && item.id === id);
262
+ const unchanged = synced.unchanged.some((item) => item.type === type && item.id === id);
263
+ const conflict = synced.conflicts.find((item) => item.type === type && item.id === id);
264
+ const failures = synced.failed.filter((item) => item.type === type && item.id === id);
265
+ if (!uploaded && !unchanged) {
266
+ if (conflict) throw new Error(`capability_upload_conflict:${ref}`);
267
+ throw new Error(`capability_upload_failed:${ref}:${failures[0]?.error ?? 'unknown'}`);
268
+ }
269
+ console.log(JSON.stringify({
270
+ capability: ref,
271
+ resolution: 'local',
272
+ effective: 'immediate',
273
+ upload: uploaded ? {
274
+ status: 'completed',
275
+ action: uploaded.action,
276
+ resource_id: uploaded.resource_id,
277
+ version_id: uploaded.version_id,
278
+ } : { status: 'unchanged' },
279
+ ...(failures.length > 0 ? { warnings: failures.map(({ error }) => error) } : {}),
280
+ reload_required_before_game: true,
281
+ }, null, 2));
282
+ return;
283
+ }
284
+ if (opts.use === 'later') {
285
+ setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined);
286
+ console.log(JSON.stringify({
287
+ capability: ref,
288
+ resolution: 'deferred',
289
+ effective: 'current_local',
290
+ reload_required_before_game: false,
291
+ }, null, 2));
292
+ return;
293
+ }
294
+ if (!entry.hub) throw new Error(`capability_cloud_identity_missing:${ref}`);
295
+ const hubType = (type === 'behavior' ? 'strategy' : type) as ResourceType;
296
+ const client = dependencies.client ?? HubClient.fromProfile(profile);
297
+ const workspaceItemId = entry.hub.publisher === 'self' ? undefined : entry.hub.workspaceItemId;
298
+ const detail = await client.getResource(hubType, entry.hub.resourceId, workspaceItemId);
299
+ const cloudBytes = await client.downloadArtifact(hubType, entry.hub.resourceId, workspaceItemId);
300
+ const target = capabilityWorkspacePath(workspaceDir, profile, entry);
301
+ let draft: string;
302
+ let digest: string;
303
+ if (type === 'skill') {
304
+ const staged = cloudSkillStage(cloudBytes);
305
+ try {
306
+ draft = saveCapabilityDirectoryDraft(workspaceDir, profile, {
307
+ type,
308
+ runtimeId: id,
309
+ sourcePath: target,
310
+ });
311
+ const replaced = overwriteAgentSkillTarget(staged.root, target);
312
+ if (!replaced.ok) throw new Error(replaced.error ?? 'capability_cloud_restore_failed');
313
+ digest = staged.digest;
314
+ } finally {
315
+ rmSync(staged.stage, { recursive: true, force: true });
316
+ }
317
+ } else {
318
+ draft = saveCapabilityDraft(workspaceDir, profile, {
319
+ type,
320
+ runtimeId: id,
321
+ bytes: readFileSync(target),
322
+ extension: extname(target),
323
+ });
324
+ writeCloudFileAtomically(target, cloudBytes);
325
+ digest = createHash('sha256').update(cloudBytes).digest('hex');
326
+ }
327
+ updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
328
+ ...entry.hub,
329
+ versionId: detail.versionId,
330
+ baseSha256: digest,
331
+ lastUploadedSha256: digest,
332
+ observedCloudVersionId: undefined,
333
+ });
334
+ setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined);
335
+ console.log(JSON.stringify({
336
+ capability: ref,
337
+ resolution: 'cloud',
338
+ draft,
339
+ effective: 'immediate',
340
+ reload_required_before_game: true,
341
+ }, null, 2));
342
+ }));
343
+
344
+ return capability;
345
+ }
@@ -1,4 +1,5 @@
1
1
  import { Command } from 'commander';
2
+ import { readFileSync } from 'node:fs';
2
3
  import { basename, extname, resolve } from 'node:path';
3
4
  import { loadContext } from '../lib/load-context.js';
4
5
  import { AuthStore } from '../lib/auth.js';
@@ -15,10 +16,8 @@ import {
15
16
  getUserDataAccountPerceptionsDir,
16
17
  getUserDataAccountTriggersDir,
17
18
  } from '../lib/user-data.js';
18
- import { listClawclawPerceptionSourcesInDirectory } from '../runtime/clawclaw/plugins/perception/perception-source.js';
19
19
  import {
20
20
  behaviorSourceCompatibilityError,
21
- listClawclawBehaviorSources,
22
21
  } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
23
22
  import { listClawclawTriggerSources } from '../runtime/clawclaw/plugins/trigger/trigger-source.js';
24
23
  import { GameClient } from '../lib/game-client.js';
@@ -34,6 +33,7 @@ import { pluginApiVersionStatus } from '../runtime/clawclaw/plugins/plugin-api-v
34
33
  import {
35
34
  readLocalAgentWorkspaceSnapshot,
36
35
  resolveLocalAgentWorkspacePath,
36
+ resolveLocalAgentWorkspaceWorkingCopyPath,
37
37
  resolveLocalAgentWorkspaceSnapshot,
38
38
  syncAgentWorkspaceConfig,
39
39
  type AgentWorkspaceSyncResult,
@@ -53,6 +53,17 @@ import {
53
53
  type ModuleCapabilityType,
54
54
  } from '../lib/capability-load-diagnostics.js';
55
55
  import { resolveClawclawResourceMetadata } from '../sdk/resource-metadata.js';
56
+ import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
57
+ import {
58
+ classifyStrategyLifecycle,
59
+ pendingCapabilitySelections,
60
+ registerDiscoveredCapability,
61
+ } from '../lib/capability-workspace.js';
62
+ import { syncCapabilitiesToCloud } from '../lib/capability-cloud-sync.js';
63
+ import {
64
+ refreshCapabilitiesFromCloud,
65
+ syncInstalledCapabilityUpdates,
66
+ } from '../lib/capability-cloud-refresh.js';
56
67
 
57
68
  const LOAD_SCHEMA = 'ccl.load.v2';
58
69
  const LOAD_DISPLAY_LOCALE = 'en-US';
@@ -62,6 +73,9 @@ export interface LoadCommandDependencies {
62
73
  authStore?: AuthStore;
63
74
  workspaceSync?: typeof syncAgentWorkspaceConfig;
64
75
  skillSync?: typeof syncAgentWorkspaceSkills;
76
+ cloudWorkspaceUpdates?: typeof syncInstalledCapabilityUpdates;
77
+ cloudRefresh?: typeof refreshCapabilitiesFromCloud;
78
+ cloudSync?: typeof syncCapabilitiesToCloud;
65
79
  }
66
80
 
67
81
  function compatibilityWarning(
@@ -189,6 +203,17 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
189
203
  if (!profile) throw new Error(noAccountMessage('load'));
190
204
  ensureAccountUserDataLayout(workspaceDir, profile);
191
205
 
206
+ let cloudWorkspaceUpdates = { updated: [], failed: [] } as Awaited<ReturnType<typeof syncInstalledCapabilityUpdates>>;
207
+ try {
208
+ cloudWorkspaceUpdates = await (
209
+ dependencies.cloudWorkspaceUpdates ?? syncInstalledCapabilityUpdates
210
+ )(profile);
211
+ } catch (error) {
212
+ console.error(`[clawclaw-cli] Hub workspace update check unavailable: ${
213
+ error instanceof Error ? error.message : String(error)
214
+ }`);
215
+ }
216
+
192
217
  let workspaceResult: AgentWorkspaceSyncResult | undefined;
193
218
  const storedWorkspace = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
194
219
  let activeWorkspace = storedWorkspace
@@ -206,6 +231,12 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
206
231
  console.error(`[clawclaw-cli] Agent workspace sync unavailable: ${workspaceSyncError}`);
207
232
  }
208
233
 
234
+ const cloudRefreshChanges = await (dependencies.cloudRefresh ?? refreshCapabilitiesFromCloud)(
235
+ workspaceDir,
236
+ profile,
237
+ activeWorkspace,
238
+ );
239
+
209
240
  let snapshot;
210
241
  try {
211
242
  snapshot = loadContext(authStore);
@@ -217,14 +248,46 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
217
248
  }
218
249
 
219
250
  const gameplay = readGameplayConfig(workspaceDir, profile);
251
+ const discoveredLocal = discoverLocalCapabilities(workspaceDir, profile);
220
252
  const capabilityWarnings: CapabilityLoadWarning[] = [];
221
253
  const disabledBehaviors = new Set(gameplay.disabled_behaviors);
222
254
  const hubBehaviors = activeWorkspace
223
255
  ? listAgentWorkspaceBehaviorSources(workspaceDir, profile, activeWorkspace)
224
256
  : [];
257
+ if (activeWorkspace) {
258
+ for (const source of hubBehaviors) {
259
+ const item = activeWorkspace.items.strategy.find((candidate) => (
260
+ candidate.resourceId === source.management.resourceId
261
+ ));
262
+ const workingPath = item
263
+ ? resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item)
264
+ : undefined;
265
+ if (!item || !workingPath) continue;
266
+ registerDiscoveredCapability(workspaceDir, profile, {
267
+ type: 'behavior',
268
+ path: workingPath,
269
+ runtimeId: source.id,
270
+ title: source.name,
271
+ description: source.description,
272
+ strategyLifecycle: classifyStrategyLifecycle(readFileSync(workingPath, 'utf8')),
273
+ selectedByHub: true,
274
+ hub: {
275
+ resourceId: item.resourceId,
276
+ versionId: item.versionId,
277
+ workspaceItemId: item.workspaceItemId,
278
+ publisher: item.hub?.publisher ?? 'community',
279
+ baseSha256: item.sourceFiles[0]?.sha256,
280
+ },
281
+ });
282
+ }
283
+ }
225
284
  const localBehaviorDir = getUserDataAccountBehaviorsDir(workspaceDir, profile);
226
- const allLocalBehaviors = listClawclawBehaviorSources(localBehaviorDir);
227
- const localBehaviors = allLocalBehaviors.filter(({ id }) => !disabledBehaviors.has(id));
285
+ const allLocalBehaviors = discoveredLocal.behaviors.map(({ source }) => source);
286
+ const localBehaviors = discoveredLocal.behaviors
287
+ .filter(({ source, entry }) => (
288
+ entry.selection === 'equipped' && !disabledBehaviors.has(source.id)
289
+ ))
290
+ .map(({ source }) => source);
228
291
  const localBehaviorSourcePaths = new Set(allLocalBehaviors.map(({ sourcePath }) => resolve(sourcePath)));
229
292
  let expectedLocalBehaviors = localBehaviors.length;
230
293
  for (const path of listCapabilityModuleCandidates(localBehaviorDir)) {
@@ -300,6 +363,16 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
300
363
  reason,
301
364
  ));
302
365
  }
366
+ const selectedLocalBehaviorPaths = new Set(localBehaviors.map(({ sourcePath }) => resolve(sourcePath)));
367
+ for (const source of allLocalBehaviors) {
368
+ if (selectedLocalBehaviorPaths.has(resolve(source.sourcePath))) continue;
369
+ const compatibilityError = behaviorSourceCompatibilityError(source);
370
+ const reason = source.apiVersion === BEHAVIOR_PLUGIN_API_VERSION
371
+ ? compatibilityError
372
+ : `behavior_api_version_unsupported:expected=${BEHAVIOR_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`;
373
+ if (!reason) continue;
374
+ capabilityWarnings.push(compatibilityWarning('behavior', 'local', source, reason));
375
+ }
303
376
  const configurationWarnings: Array<Record<string, unknown>> = [];
304
377
  if (snapshot.memory.truncated) {
305
378
  configurationWarnings.push({
@@ -325,10 +398,46 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
325
398
  const hubPerceptions = activeWorkspace
326
399
  ? listAgentWorkspacePerceptionSources(workspaceDir, profile, activeWorkspace)
327
400
  : [];
401
+ if (activeWorkspace) {
402
+ for (const source of hubPerceptions) {
403
+ const item = activeWorkspace.items.perception.find((candidate) => (
404
+ !!candidate.runtimeEntryPath
405
+ && resolveLocalAgentWorkspacePath(
406
+ workspaceDir,
407
+ profile,
408
+ activeWorkspace,
409
+ candidate.runtimeEntryPath,
410
+ ) === source.sourcePath
411
+ ));
412
+ const workingPath = item
413
+ ? resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item)
414
+ : undefined;
415
+ if (!item || !workingPath) continue;
416
+ registerDiscoveredCapability(workspaceDir, profile, {
417
+ type: 'perception',
418
+ path: workingPath,
419
+ runtimeId: source.id,
420
+ title: source.name,
421
+ description: source.description,
422
+ selectedByHub: true,
423
+ hub: {
424
+ resourceId: item.resourceId,
425
+ versionId: item.versionId,
426
+ workspaceItemId: item.workspaceItemId,
427
+ publisher: item.hub?.publisher ?? 'community',
428
+ baseSha256: item.sourceFiles[0]?.sha256,
429
+ },
430
+ });
431
+ }
432
+ }
328
433
  const hubPerceptionIds = new Set(hubPerceptions.map(({ id }) => id));
329
434
  const localPerceptionDir = getUserDataAccountPerceptionsDir(workspaceDir, profile);
330
- const allLocalPerceptions = listClawclawPerceptionSourcesInDirectory(localPerceptionDir);
331
- const localPerceptions = allLocalPerceptions.filter(({ id }) => !disabledPerceptions.has(id));
435
+ const allLocalPerceptions = discoveredLocal.perceptions.map(({ source }) => source);
436
+ const localPerceptions = discoveredLocal.perceptions
437
+ .filter(({ source, entry }) => (
438
+ entry.selection === 'equipped' && !disabledPerceptions.has(source.id)
439
+ ))
440
+ .map(({ source }) => source);
332
441
  const localPerceptionSourcePaths = new Set(
333
442
  allLocalPerceptions.map(({ sourcePath }) => resolve(sourcePath)),
334
443
  );
@@ -388,6 +497,19 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
388
497
  `perception_api_version_unsupported:expected=${PERCEPTION_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`,
389
498
  ));
390
499
  }
500
+ const selectedLocalPerceptionPaths = new Set(localPerceptions.map(({ sourcePath }) => resolve(sourcePath)));
501
+ for (const source of allLocalPerceptions) {
502
+ if (
503
+ selectedLocalPerceptionPaths.has(resolve(source.sourcePath))
504
+ || source.apiVersion === PERCEPTION_PLUGIN_API_VERSION
505
+ ) continue;
506
+ capabilityWarnings.push(compatibilityWarning(
507
+ 'perception',
508
+ 'local',
509
+ source,
510
+ `perception_api_version_unsupported:expected=${PERCEPTION_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`,
511
+ ));
512
+ }
391
513
  const disabledTriggers = new Set(gameplay.disabled_triggers);
392
514
  const localTriggerDir = getUserDataAccountTriggersDir(workspaceDir, profile);
393
515
  const triggerSources = listClawclawTriggerSources(localTriggerDir);
@@ -446,7 +568,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
446
568
  requiresUserConfirmation: false,
447
569
  };
448
570
  const hubPersonaItem = activeWorkspace?.items.persona[0];
449
- if (hubPersonaItem && (
571
+ if (hubPersonaItem && snapshot.persona.source !== 'local' && (
450
572
  snapshot.persona.source !== 'hub'
451
573
  || snapshot.persona.resource_id !== hubPersonaItem.resourceId
452
574
  || snapshot.persona.exists !== true
@@ -472,6 +594,35 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
472
594
  path: snapshot.persona.path,
473
595
  });
474
596
  }
597
+ if (
598
+ hubPersonaItem
599
+ && snapshot.persona.source === 'hub'
600
+ && snapshot.persona.path
601
+ && snapshot.persona.exists
602
+ ) {
603
+ registerDiscoveredCapability(workspaceDir, profile, {
604
+ type: 'persona',
605
+ path: snapshot.persona.path,
606
+ runtimeId: snapshot.persona.id ?? basename(snapshot.persona.path, extname(snapshot.persona.path)),
607
+ title: snapshot.persona.id ?? basename(snapshot.persona.path, extname(snapshot.persona.path)),
608
+ description: `Persona ${snapshot.persona.id ?? basename(snapshot.persona.path)}`,
609
+ selectedByHub: true,
610
+ hub: {
611
+ resourceId: hubPersonaItem.resourceId,
612
+ versionId: hubPersonaItem.versionId,
613
+ workspaceItemId: hubPersonaItem.workspaceItemId,
614
+ publisher: hubPersonaItem.hub?.publisher ?? 'community',
615
+ baseSha256: hubPersonaItem.sourceFiles[0]?.sha256,
616
+ },
617
+ });
618
+ }
619
+ const cloudChanges = activeWorkspace
620
+ ? await (dependencies.cloudSync ?? syncCapabilitiesToCloud)(
621
+ workspaceDir,
622
+ profile,
623
+ activeWorkspace,
624
+ )
625
+ : undefined;
475
626
  let participation;
476
627
  try {
477
628
  const client = (dependencies.clientFactory ?? (() => GameClient.fromAuth()))();
@@ -523,6 +674,30 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
523
674
  const perceptionSourceById = new Map(enabledPerceptions.map((source) => [source.id, source]));
524
675
  const triggerSourceById = new Map(enabledTriggers.map((source) => [source.id, source]));
525
676
  const skillChangeSummary = compactSkillChanges(skillChanges);
677
+ const cloudConflicts = [...cloudRefreshChanges.conflicts, ...(cloudChanges?.conflicts ?? [])]
678
+ .filter((value, index, values) => values.findIndex((candidate) => (
679
+ candidate.type === value.type
680
+ && candidate.id === value.id
681
+ && candidate.resource_id === value.resource_id
682
+ )) === index);
683
+ const cloudFailures = [...cloudRefreshChanges.failed, ...(cloudChanges?.failed ?? [])];
684
+ const cloudChangeSummary = (
685
+ cloudWorkspaceUpdates.updated.length > 0
686
+ || cloudWorkspaceUpdates.failed.length > 0
687
+ || cloudRefreshChanges.downloaded.length > 0
688
+ || (cloudChanges?.uploaded.length ?? 0) > 0
689
+ || cloudConflicts.length > 0
690
+ || cloudFailures.length > 0
691
+ ) ? {
692
+ workspace_updated: cloudWorkspaceUpdates.updated,
693
+ workspace_update_failed: cloudWorkspaceUpdates.failed,
694
+ downloaded: cloudRefreshChanges.downloaded,
695
+ uploaded: cloudChanges?.uploaded ?? [],
696
+ conflicts: cloudConflicts,
697
+ failed: cloudFailures,
698
+ unchanged: cloudChanges?.unchanged ?? [],
699
+ } : undefined;
700
+ const selectionRequired = pendingCapabilitySelections(workspaceDir, profile);
526
701
  console.log(JSON.stringify({
527
702
  schema: LOAD_SCHEMA,
528
703
  context: {
@@ -534,7 +709,12 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
534
709
  revision: activeWorkspace?.revision ?? null,
535
710
  ...(workspaceSyncError ? { error: workspaceSyncError } : {}),
536
711
  },
537
- ...(skillChangeSummary ? { changes: { skills: skillChangeSummary } } : {}),
712
+ ...(skillChangeSummary || cloudChangeSummary ? {
713
+ changes: {
714
+ ...(skillChangeSummary ? { skills: skillChangeSummary } : {}),
715
+ ...(cloudChangeSummary ? { cloud_sync: cloudChangeSummary } : {}),
716
+ },
717
+ } : {}),
538
718
  capabilities: {
539
719
  summary: capabilitySummary,
540
720
  behaviors: behaviors.map((entry) => {
@@ -545,6 +725,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
545
725
  name: localized.name,
546
726
  description: localized.description,
547
727
  source: entry.source,
728
+ strategy_type: classifyStrategyLifecycle(readFileSync(source.sourcePath, 'utf8')),
548
729
  };
549
730
  }),
550
731
  perceptions: perceptions.map((entry) => {
@@ -569,6 +750,12 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
569
750
  };
570
751
  }),
571
752
  warnings: capabilityWarnings.map(compactCapabilityWarning),
753
+ selection_required: selectionRequired.map((entry) => ({
754
+ type: entry.type,
755
+ id: entry.runtimeId,
756
+ strategy_type: entry.strategyLifecycle,
757
+ action: `Choose once with ccl capability equip ${entry.type}/${entry.runtimeId} or ccl capability unequip ${entry.type}/${entry.runtimeId}.`,
758
+ })),
572
759
  },
573
760
  configuration_warnings: compactConfigurationWarnings(configurationWarnings),
574
761
  participation: compactParticipation(participation),