@myclaw163/clawclaw-cli 0.8.15 → 0.8.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/docs/configuration.md +7 -3
  2. package/package.json +1 -1
  3. package/scripts/sync-bundled-skill.mjs +28 -57
  4. package/skills/clawclaw/SKILL.md +23 -4
  5. package/skills/clawclaw/references/COMMANDS.md +8 -4
  6. package/skills/clawclaw/references/HUB.md +2 -1
  7. package/src/commands/account.ts +45 -1
  8. package/src/commands/behavior.ts +17 -17
  9. package/src/commands/capability.ts +39 -26
  10. package/src/commands/load.ts +156 -8
  11. package/src/commands/perception.ts +17 -16
  12. package/src/commands/persona.ts +24 -6
  13. package/src/lib/agent-workspace-client.ts +2 -0
  14. package/src/lib/agent-workspace-runtime.ts +12 -3
  15. package/src/lib/agent-workspace-skills.ts +241 -23
  16. package/src/lib/agent-workspace-sync.ts +54 -10
  17. package/src/lib/capability-cloud-presence.ts +179 -0
  18. package/src/lib/capability-cloud-refresh.ts +43 -21
  19. package/src/lib/capability-cloud-sync.ts +165 -8
  20. package/src/lib/capability-selection.ts +62 -0
  21. package/src/lib/capability-workspace.ts +6 -0
  22. package/src/lib/game-client.ts +10 -0
  23. package/src/lib/hub-client.ts +75 -0
  24. package/src/lib/persona.ts +14 -1
  25. package/src/pipeline/event-hints.ts +1 -1
  26. package/src/runtime/clawclaw/owner.ts +25 -4
  27. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +107 -0
  28. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  29. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +12 -0
  30. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +10 -3
  31. package/src/runtime/game-sync-protocol.ts +47 -0
  32. package/src/runtime/ws-client.ts +7 -0
@@ -1,13 +1,23 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
- import { dirname, join, resolve } from 'node:path';
1
+ import {
2
+ existsSync,
3
+ lstatSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readdirSync,
7
+ renameSync,
8
+ writeFileSync,
9
+ } from 'node:fs';
10
+ import { dirname, join, relative, resolve } from 'node:path';
3
11
  import { randomUUID } from 'node:crypto';
4
12
  import type { AuthProfile } from './auth.js';
5
13
  import {
6
14
  resolveLocalAgentWorkspacePath,
15
+ type LocalAgentWorkspaceItem,
7
16
  type LocalAgentWorkspaceSnapshot,
8
17
  } from './agent-workspace-sync.js';
9
18
  import {
10
19
  capabilityWorkspacePath,
20
+ capabilityEntryForHubResource,
11
21
  readCapabilityWorkspaceRegistry,
12
22
  registerDiscoveredCapability,
13
23
  } from './capability-workspace.js';
@@ -21,17 +31,25 @@ import {
21
31
  linkAgentSkillTarget,
22
32
  overwriteAgentSkillTarget,
23
33
  readSkillName,
24
- resolveBundledClawclawSkill,
25
34
  unlinkAgentSkillTarget,
26
35
  type SkillHostMutationResult,
27
36
  } from './skill-host.js';
37
+ import { zipContentDigest } from './zip-store.js';
28
38
 
29
39
  interface ActiveSkillEntry {
30
40
  name: string;
31
- kind: 'official' | 'hub' | 'local';
41
+ kind: 'hub' | 'local';
32
42
  canonicalPath: string;
43
+ /** Last accepted remote directory hash. */
33
44
  sourceDigest?: string;
45
+ /** Latest observed remote directory hash. */
34
46
  remoteDigest?: string;
47
+ /** Upload-compatible digest for the last accepted remote content. */
48
+ sourceCloudDigest?: string;
49
+ /** Upload-compatible digest for the latest observed remote content. */
50
+ remoteCloudDigest?: string;
51
+ knownSourceDigests?: string[];
52
+ knownCloudDigests?: string[];
35
53
  resourceId?: string;
36
54
  versionId?: string;
37
55
  }
@@ -58,7 +76,12 @@ export interface AgentWorkspaceSkillDependencies {
58
76
  overwriteTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult;
59
77
  linkTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult;
60
78
  unlinkTarget?: (targetPath: string) => SkillHostMutationResult;
61
- bundledSkill?: () => string;
79
+ cloudDigest?: (path: string) => string | undefined;
80
+ }
81
+
82
+ export interface AccountSkillLinkSwitchResult {
83
+ removed: string[];
84
+ linked: string[];
62
85
  }
63
86
 
64
87
  function manifestPath(
@@ -98,6 +121,116 @@ function resultError(result: SkillHostMutationResult): string {
98
121
  return result.error ?? result.stderr?.trim() ?? 'skill host mutation failed';
99
122
  }
100
123
 
124
+ function skillCloudDigest(path: string): string | undefined {
125
+ if (!existsSync(path)) return undefined;
126
+ const root = resolve(path);
127
+ const files: Array<{ path: string; content: Buffer }> = [];
128
+ const visit = (directory: string): void => {
129
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
130
+ const child = join(directory, entry.name);
131
+ const stat = lstatSync(child);
132
+ if (stat.isSymbolicLink()) throw new Error('skill_source_symlink_unsupported');
133
+ if (stat.isDirectory()) visit(child);
134
+ else if (stat.isFile()) files.push({
135
+ path: relative(root, child).replaceAll('\\', '/'),
136
+ content: readFileSync(child),
137
+ });
138
+ }
139
+ };
140
+ try {
141
+ visit(root);
142
+ return files.length > 0 ? zipContentDigest(files) : undefined;
143
+ } catch {
144
+ return undefined;
145
+ }
146
+ }
147
+
148
+ function unique(values: Array<string | undefined>): string[] {
149
+ return [...new Set(values.filter((value): value is string => !!value))];
150
+ }
151
+
152
+ function accountManagedSkillSources(
153
+ workspaceDir: string,
154
+ profile: Pick<AuthProfile, 'apiKey'>,
155
+ includeInactive = false,
156
+ ): Map<string, string> {
157
+ const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
158
+ const sources = new Map<string, string>();
159
+ for (const [name] of Object.entries(readManifest(workspaceDir, profile).entries)) {
160
+ if (name === 'clawclaw') continue;
161
+ const entry = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
162
+ .find(entry => entry.type === 'skill' && entry.runtimeId === name);
163
+ if (!includeInactive && entry && (entry.selection !== 'equipped' || entry.hub?.cloudStatus)) continue;
164
+ sources.set(name, join(skillsRoot, name));
165
+ }
166
+ for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
167
+ if (
168
+ entry.type !== 'skill'
169
+ || entry.runtimeId === 'clawclaw'
170
+ || entry.origin !== 'local'
171
+ || entry.selection !== 'equipped'
172
+ ) continue;
173
+ sources.set(entry.runtimeId, capabilityWorkspacePath(workspaceDir, profile, entry));
174
+ }
175
+ return sources;
176
+ }
177
+
178
+ /**
179
+ * Move the device-wide account-managed Skill links before AuthStore commits an
180
+ * account switch. The package-owned clawclaw Skill is deliberately untouched.
181
+ */
182
+ export function switchActiveAccountSkillLinks(
183
+ workspaceDir: string,
184
+ previousProfile: Pick<AuthProfile, 'apiKey'> | null,
185
+ nextProfile: Pick<AuthProfile, 'apiKey'>,
186
+ dependencies: Pick<AgentWorkspaceSkillDependencies, 'targets' | 'linkTarget' | 'unlinkTarget'> = {},
187
+ ): AccountSkillLinkSwitchResult {
188
+ if (previousProfile?.apiKey === nextProfile.apiKey) return { removed: [], linked: [] };
189
+ const targets = dependencies.targets ?? agentSkillTargets;
190
+ const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
191
+ const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
192
+ const previous = previousProfile
193
+ ? accountManagedSkillSources(workspaceDir, previousProfile, true)
194
+ : new Map<string, string>();
195
+ const next = accountManagedSkillSources(workspaceDir, nextProfile);
196
+
197
+ for (const [name, source] of next) {
198
+ if (!existsSync(source) || readSkillName(source) !== name) {
199
+ throw new Error(`account_skill_source_unavailable:${name}`);
200
+ }
201
+ }
202
+
203
+ const removedTargets: Array<{ name: string; target: string }> = [];
204
+ const linkedTargets: Array<{ name: string; target: string }> = [];
205
+ try {
206
+ for (const [name] of previous) {
207
+ for (const target of targets(name)) {
208
+ const result = unlinkTarget(target);
209
+ if (!result.ok) throw new Error(`account_skill_unlink_failed:${name}:${resultError(result)}`);
210
+ removedTargets.push({ name, target });
211
+ }
212
+ }
213
+ for (const [name, source] of next) {
214
+ for (const target of targets(name)) {
215
+ const result = linkTarget(source, target);
216
+ if (!result.ok) throw new Error(`account_skill_link_failed:${name}:${resultError(result)}`);
217
+ linkedTargets.push({ name, target });
218
+ }
219
+ }
220
+ } catch (error) {
221
+ for (const { target } of linkedTargets.reverse()) unlinkTarget(target);
222
+ for (const { name, target } of removedTargets.reverse()) {
223
+ const source = previous.get(name);
224
+ if (source && existsSync(source)) linkTarget(source, target);
225
+ }
226
+ throw error;
227
+ }
228
+ return {
229
+ removed: [...previous.keys()],
230
+ linked: [...next.keys()],
231
+ };
232
+ }
233
+
101
234
  export function syncAgentWorkspaceSkills(
102
235
  workspaceDir: string,
103
236
  profile: Pick<AuthProfile, 'apiKey'>,
@@ -112,6 +245,7 @@ export function syncAgentWorkspaceSkills(
112
245
  const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
113
246
  const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
114
247
  const targets = dependencies.targets ?? agentSkillTargets;
248
+ const cloudDigest = dependencies.cloudDigest ?? skillCloudDigest;
115
249
  const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
116
250
  mkdirSync(skillsRoot, { recursive: true });
117
251
 
@@ -121,10 +255,10 @@ export function syncAgentWorkspaceSkills(
121
255
  resourceId?: string;
122
256
  versionId?: string;
123
257
  remoteDigest?: string;
258
+ remoteCloudDigest?: string;
124
259
  publisher?: 'official' | 'self' | 'community';
260
+ remoteItem?: LocalAgentWorkspaceItem;
125
261
  }>();
126
- const bundled = (dependencies.bundledSkill ?? resolveBundledClawclawSkill)();
127
- desired.set('clawclaw', { kind: 'official', sourcePath: bundled });
128
262
 
129
263
  for (const item of snapshot.items.skill) {
130
264
  if (!item.skillRootPath) continue;
@@ -150,14 +284,25 @@ export function syncAgentWorkspaceSkills(
150
284
  resourceId: item.resourceId,
151
285
  versionId: item.versionId,
152
286
  remoteDigest: hashDirectory(path),
287
+ remoteCloudDigest: cloudDigest(path),
153
288
  publisher: item.hub?.publisher ?? 'community',
289
+ remoteItem: item,
154
290
  });
155
291
  }
156
292
 
157
293
  for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
158
294
  if (entry.type !== 'skill' || entry.origin !== 'local' || entry.selection !== 'equipped') continue;
295
+ if (entry.runtimeId === 'clawclaw') {
296
+ failed.push({
297
+ name: entry.runtimeId,
298
+ action: 'add',
299
+ error: 'The official clawclaw Skill is managed by the installed CCL package',
300
+ });
301
+ continue;
302
+ }
159
303
  const path = capabilityWorkspacePath(workspaceDir, profile, entry);
160
304
  if (desired.has(entry.runtimeId)) {
305
+ if (entry.hub?.resourceId === desired.get(entry.runtimeId)?.resourceId) continue;
161
306
  failed.push({ name: entry.runtimeId, action: 'add', error: 'local and Hub Skill names conflict' });
162
307
  continue;
163
308
  }
@@ -174,33 +319,69 @@ export function syncAgentWorkspaceSkills(
174
319
  const canonical = join(skillsRoot, name);
175
320
  const previous = current.entries[name];
176
321
  const sourceDigest = hashDirectory(item.sourcePath);
177
- if (!sourceDigest) {
322
+ const sourceCloudDigest = item.remoteCloudDigest ?? cloudDigest(item.sourcePath);
323
+ if (!sourceDigest || !sourceCloudDigest) {
178
324
  failed.push({ name, action: previous ? 'update' : 'add', error: 'Skill source is unreadable' });
179
325
  continue;
180
326
  }
181
327
  const canonicalDigest = hashDirectory(canonical);
328
+ const canonicalCloudDigest = cloudDigest(canonical);
329
+ const registered = item.kind === 'hub' && item.resourceId
330
+ ? capabilityEntryForHubResource(workspaceDir, profile, 'skill', item.resourceId)
331
+ : undefined;
332
+ const knownSourceDigests = unique([
333
+ ...(previous?.knownSourceDigests ?? []),
334
+ previous?.sourceDigest,
335
+ previous?.remoteDigest,
336
+ sourceDigest,
337
+ ]);
338
+ const knownCloudDigests = unique([
339
+ ...(previous?.knownCloudDigests ?? []),
340
+ previous?.sourceCloudDigest,
341
+ previous?.remoteCloudDigest,
342
+ registered?.hub?.baseSha256,
343
+ registered?.hub?.lastUploadedSha256,
344
+ sourceCloudDigest,
345
+ ]);
182
346
  let applied = false;
183
347
  let preserved = false;
348
+ let resolution: LocalAgentWorkspaceItem['resolution'] = 'hub';
184
349
  if (item.kind === 'local' && resolve(item.sourcePath) === resolve(canonical)) {
185
350
  applied = true;
186
- } else if (item.kind === 'official') {
187
- if (canonicalDigest !== sourceDigest) {
188
- const result = overwriteTarget(item.sourcePath, canonical);
189
- if (!result.ok) {
190
- failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
191
- continue;
192
- }
193
- applied = true;
194
- }
195
351
  } else if (canonicalDigest === sourceDigest) {
196
352
  applied = true;
197
- } else if (canonicalDigest === undefined || canonicalDigest === previous?.sourceDigest) {
353
+ } else if (canonicalDigest === undefined) {
198
354
  const result = overwriteTarget(item.sourcePath, canonical);
199
355
  if (!result.ok) {
200
356
  failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
201
357
  continue;
202
358
  }
203
359
  applied = true;
360
+ } else if (item.kind === 'hub') {
361
+ const originRecognized = registered?.hub?.localOriginUnrecognized !== true
362
+ && (!!registered?.hub || !!previous?.sourceDigest);
363
+ const localMatchesKnownVersion = knownSourceDigests.includes(canonicalDigest)
364
+ || (!!canonicalCloudDigest && knownCloudDigests.includes(canonicalCloudDigest));
365
+ const remoteAdvanced = registered?.hub
366
+ ? registered.hub.versionId !== item.versionId
367
+ : !!previous?.sourceDigest && previous.sourceDigest !== sourceDigest;
368
+ if (localMatchesKnownVersion) {
369
+ const result = overwriteTarget(item.sourcePath, canonical);
370
+ if (!result.ok) {
371
+ failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
372
+ continue;
373
+ }
374
+ applied = true;
375
+ resolution = 'known_online_old';
376
+ } else {
377
+ preserved = true;
378
+ resolution = !originRecognized
379
+ ? 'local_origin_unrecognized'
380
+ : remoteAdvanced
381
+ ? 'concurrent_difference'
382
+ : 'local_modified';
383
+ preservedModified.push(name);
384
+ }
204
385
  } else {
205
386
  preserved = true;
206
387
  preservedModified.push(name);
@@ -220,6 +401,28 @@ export function syncAgentWorkspaceSkills(
220
401
  }
221
402
  }
222
403
  if (linkFailed) continue;
404
+ const effectiveCloudDigest = cloudDigest(canonical);
405
+ if (!effectiveCloudDigest) {
406
+ failed.push({ name, action: previous ? 'update' : 'add', error: 'Canonical Skill is unreadable' });
407
+ continue;
408
+ }
409
+ if (item.remoteItem) {
410
+ item.remoteItem.resolution = resolution;
411
+ if (resolution === 'hub' || resolution === 'known_online_old') {
412
+ delete item.remoteItem.localContentDigest;
413
+ delete item.remoteItem.localModifiedAtMs;
414
+ } else {
415
+ item.remoteItem.localContentDigest = effectiveCloudDigest;
416
+ }
417
+ }
418
+ const acceptedVersionId = preserved
419
+ ? registered?.hub?.versionId ?? item.versionId
420
+ : item.versionId;
421
+ const acceptedCloudDigest = preserved
422
+ ? registered?.hub?.baseSha256
423
+ ?? previous?.sourceCloudDigest
424
+ ?? (registered?.hub?.versionId === item.versionId ? sourceCloudDigest : undefined)
425
+ : sourceCloudDigest;
223
426
  registerDiscoveredCapability(workspaceDir, profile, {
224
427
  type: 'skill',
225
428
  path: canonical,
@@ -230,9 +433,16 @@ export function syncAgentWorkspaceSkills(
230
433
  ...(item.kind === 'hub' && item.resourceId && item.versionId ? {
231
434
  hub: {
232
435
  resourceId: item.resourceId,
233
- versionId: item.versionId,
436
+ versionId: acceptedVersionId!,
437
+ workspaceItemId: item.remoteItem?.workspaceItemId,
234
438
  publisher: item.publisher ?? 'community',
235
- baseSha256: item.remoteDigest,
439
+ baseSha256: acceptedCloudDigest,
440
+ observedCloudVersionId: resolution === 'concurrent_difference'
441
+ ? item.versionId
442
+ : undefined,
443
+ localOriginUnrecognized: resolution === 'local_origin_unrecognized'
444
+ ? true
445
+ : undefined,
236
446
  },
237
447
  } : {}),
238
448
  });
@@ -240,8 +450,15 @@ export function syncAgentWorkspaceSkills(
240
450
  name,
241
451
  kind: item.kind,
242
452
  canonicalPath: canonical,
243
- sourceDigest: preserved ? previous?.sourceDigest : sourceDigest,
244
- remoteDigest: item.remoteDigest,
453
+ sourceDigest: preserved
454
+ ? previous?.sourceDigest
455
+ ?? (registered?.hub?.versionId === item.versionId ? sourceDigest : undefined)
456
+ : sourceDigest,
457
+ remoteDigest: sourceDigest,
458
+ sourceCloudDigest: acceptedCloudDigest,
459
+ remoteCloudDigest: sourceCloudDigest,
460
+ knownSourceDigests,
461
+ knownCloudDigests,
245
462
  resourceId: item.resourceId,
246
463
  versionId: item.versionId,
247
464
  };
@@ -251,7 +468,7 @@ export function syncAgentWorkspaceSkills(
251
468
  }
252
469
 
253
470
  for (const [name] of Object.entries(current.entries)) {
254
- if (desired.has(name)) continue;
471
+ if (name === 'clawclaw' || desired.has(name)) continue;
255
472
  let failedRemoval = false;
256
473
  for (const target of targets(name)) {
257
474
  const result = unlinkTarget(target);
@@ -261,6 +478,7 @@ export function syncAgentWorkspaceSkills(
261
478
  }
262
479
  }
263
480
  if (!failedRemoval) removed.push(name);
481
+ else next.entries[name] = current.entries[name]!;
264
482
  }
265
483
 
266
484
  writeManifest(workspaceDir, profile, next);
@@ -34,6 +34,10 @@ import {
34
34
  capabilityEntryForHubResource,
35
35
  capabilityWorkspacePath,
36
36
  } from './capability-workspace.js';
37
+ import { inspectClawclawBehaviorSource, behaviorSourceCompatibilityError } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
38
+ import { listClawclawPerceptionSourcesInDirectory } from '../runtime/clawclaw/plugins/perception/perception-source.js';
39
+ import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js';
40
+ import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js';
37
41
 
38
42
  const RESOURCE_TYPES: readonly ResourceType[] = ['skill', 'strategy', 'persona', 'perception'];
39
43
  const SHA256 = /^[0-9a-f]{64}$/;
@@ -52,6 +56,8 @@ export interface LocalAgentWorkspaceItem {
52
56
  workspaceItemId: string;
53
57
  resourceId: string;
54
58
  versionId: string;
59
+ versionNumber?: string;
60
+ versionDescription?: string;
55
61
  resourceType: ResourceType;
56
62
  hub?: {
57
63
  workspaceKind: 'owned' | 'installed';
@@ -72,7 +78,12 @@ export interface LocalAgentWorkspaceItem {
72
78
  contentDigest: string;
73
79
  sourceSha256: string;
74
80
  }>;
75
- resolution?: 'hub' | 'local_modified' | 'concurrent_difference' | 'known_online_old';
81
+ resolution?:
82
+ | 'hub'
83
+ | 'local_modified'
84
+ | 'concurrent_difference'
85
+ | 'known_online_old'
86
+ | 'local_origin_unrecognized';
76
87
  localContentDigest?: string;
77
88
  localModifiedAtMs?: number;
78
89
  }
@@ -349,6 +360,8 @@ async function materializeItem(
349
360
  workspaceItemId: item.workspace_item_id,
350
361
  resourceId: item.resource_id,
351
362
  versionId: item.version_id,
363
+ versionNumber: item.version_number,
364
+ versionDescription: item.version_description,
352
365
  resourceType: item.resource_type,
353
366
  hub: {
354
367
  workspaceKind: item.workspace_kind,
@@ -398,6 +411,7 @@ interface LocalOverride {
398
411
  sha256: string;
399
412
  contentDigest: string;
400
413
  modifiedAtMs: number;
414
+ originRecognized: boolean;
401
415
  }
402
416
 
403
417
  interface WorkingCopyMetadata {
@@ -600,7 +614,9 @@ function inspectLocalSnapshot(
600
614
  }
601
615
  const localDigest = singleFileContentDigest(source.relativePath, bytes);
602
616
  const modifiedAtMs = statSync(workingPath).mtimeMs;
603
- item.resolution = 'local_modified';
617
+ item.resolution = item.resolution === 'local_origin_unrecognized'
618
+ ? 'local_origin_unrecognized'
619
+ : item.resolution === 'concurrent_difference' ? 'concurrent_difference' : 'local_modified';
604
620
  item.localContentDigest = localDigest;
605
621
  item.localModifiedAtMs = modifiedAtMs;
606
622
  if (projectionSha !== localSha) projectionOutdated = true;
@@ -609,6 +625,7 @@ function inspectLocalSnapshot(
609
625
  sha256: localSha,
610
626
  contentDigest: localDigest,
611
627
  modifiedAtMs,
628
+ originRecognized: item.resolution !== 'local_origin_unrecognized',
612
629
  });
613
630
  }
614
631
  }
@@ -670,8 +687,15 @@ export async function syncAgentWorkspaceConfig(
670
687
  const client = dependencies.client ?? new AgentWorkspaceClient(profile);
671
688
  const remote = await client.getConfig();
672
689
  validateRemoteConfig(remote);
690
+ const contentUnchanged = previous && RESOURCE_TYPES.every(type => {
691
+ const items = previous.items[type];
692
+ return items.length === remote.items[type].length && remote.items[type].every(item =>
693
+ items.some(old => old.resourceId === item.resource_id && old.versionId === item.version_id
694
+ && old.workspaceItemId === item.workspace_item_id && old.contentDigest === item.content_digest));
695
+ });
673
696
  if (
674
697
  previous?.revision === remote.revision
698
+ && contentUnchanged
675
699
  && previous.metadataVersion === 1
676
700
  && previous.layoutVersion === 3
677
701
  && inspected?.projectionOutdated !== true
@@ -700,11 +724,12 @@ export async function syncAgentWorkspaceConfig(
700
724
  );
701
725
  for (const type of RESOURCE_TYPES) {
702
726
  for (const item of remote.items[type]) {
703
- const materialized = await materializeItem(
704
- temporary,
705
- item,
706
- dependencies.download ?? downloadAgentWorkspaceFile,
707
- );
727
+ let materialized: LocalAgentWorkspaceItem;
728
+ try {
729
+ materialized = await materializeItem(temporary, item, dependencies.download ?? downloadAgentWorkspaceFile);
730
+ } catch (error) {
731
+ throw new Error(`agent_workspace_resource_failed:${type}:${item.resource_id}:${item.source_files.map(file => file.relative_path).join(',')}:${error instanceof Error ? error.message : String(error)}`);
732
+ }
708
733
  const prior = previousByKey.get(type)?.get(materialized.resourceId);
709
734
  let workingPath: string | undefined;
710
735
  let persistedWorkingMetadata: WorkingCopyMetadata | undefined;
@@ -753,6 +778,7 @@ export async function syncAgentWorkspaceConfig(
753
778
  bytes,
754
779
  ),
755
780
  modifiedAtMs: statSync(workingPath).mtimeMs,
781
+ originRecognized: persistedWorkingMetadata !== undefined,
756
782
  };
757
783
  }
758
784
  }
@@ -774,9 +800,11 @@ export async function syncAgentWorkspaceConfig(
774
800
  && !persistedWorkingMetadata.knownVersions.some(
775
801
  (entry) => entry.versionId === materialized.versionId,
776
802
  );
777
- materialized.resolution = remoteAdvancedFromLocalBaseline
778
- ? 'concurrent_difference'
779
- : 'local_modified';
803
+ materialized.resolution = !override.originRecognized
804
+ ? 'local_origin_unrecognized'
805
+ : remoteAdvancedFromLocalBaseline || prior?.resolution === 'concurrent_difference'
806
+ ? 'concurrent_difference'
807
+ : 'local_modified';
780
808
  materialized.localContentDigest = override.contentDigest;
781
809
  materialized.localModifiedAtMs = override.modifiedAtMs;
782
810
  } else {
@@ -788,6 +816,22 @@ export async function syncAgentWorkspaceConfig(
788
816
  ));
789
817
  }
790
818
  }
819
+ // Reject an invalid cloud replacement before touching the working copy
820
+ // or pointer. Invalid local edits remain visible to load diagnostics.
821
+ if (prior && materialized.resolution === 'hub' && materialized.runtimeEntryPath) {
822
+ const path = join(temporary, materialized.runtimeEntryPath);
823
+ if (type === 'strategy') {
824
+ const source = inspectClawclawBehaviorSource(path, dirname(path));
825
+ if (!source || source.apiVersion !== BEHAVIOR_PLUGIN_API_VERSION || behaviorSourceCompatibilityError(source)) {
826
+ throw new Error(`agent_workspace_resource_failed:strategy:${item.resource_id}:cloud_module_invalid`);
827
+ }
828
+ } else if (type === 'perception') {
829
+ const source = listClawclawPerceptionSourcesInDirectory(dirname(path)).find(source => source.sourcePath === path);
830
+ if (!source || source.apiVersion !== PERCEPTION_PLUGIN_API_VERSION) {
831
+ throw new Error(`agent_workspace_resource_failed:perception:${item.resource_id}:cloud_module_invalid`);
832
+ }
833
+ }
834
+ }
791
835
  if (materialized.workingCopyPath && effectiveBytes) {
792
836
  const accountRoot = getUserDataAccountDir(workspaceDir, profile);
793
837
  workingUpdates.push({