@myclaw163/clawclaw-cli 0.8.20 → 0.8.22

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 (50) hide show
  1. package/docs/configuration.md +57 -2
  2. package/docs/custom-modules/api-reference.md +2 -0
  3. package/docs/custom-modules/perception.md +25 -0
  4. package/docs/runtime/official-perception-modules.md +23 -0
  5. package/package.json +1 -1
  6. package/skills/clawclaw/SKILL.md +3 -1
  7. package/skills/clawclaw/references/COMMANDS.md +2 -0
  8. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +2 -0
  9. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +25 -0
  10. package/src/commands/behavior.ts +1 -0
  11. package/src/commands/capability.ts +1 -0
  12. package/src/commands/data.ts +1 -0
  13. package/src/commands/load.ts +31 -2
  14. package/src/lib/agent-workspace-client.ts +1 -0
  15. package/src/lib/agent-workspace-runtime.ts +6 -0
  16. package/src/lib/agent-workspace-sync.ts +117 -6
  17. package/src/lib/capability-cloud-refresh.ts +7 -0
  18. package/src/lib/capability-cloud-sync.ts +11 -3
  19. package/src/lib/capability-workspace.ts +3 -0
  20. package/src/lib/diagnostics-config.ts +26 -1
  21. package/src/lib/hub-client.ts +6 -0
  22. package/src/lib/persona.ts +2 -0
  23. package/src/runtime/clawclaw/agent-event-policy.ts +7 -0
  24. package/src/runtime/clawclaw/owner.ts +17 -10
  25. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +21 -0
  26. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +26 -12
  27. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +19 -1
  28. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +2 -0
  29. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +10 -1
  30. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +17 -1
  31. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +5 -2
  32. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +46 -15
  33. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +36 -0
  34. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +2 -1
  35. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -0
  36. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +13 -0
  37. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +4 -0
  38. package/src/runtime/clawclaw/runtime-data-export.ts +9 -0
  39. package/src/runtime/framework/events/event-ingress.ts +1 -0
  40. package/src/runtime/framework/events/memory-event-repository.ts +5 -4
  41. package/src/runtime/framework/events/sqlite-event-repository.ts +36 -9
  42. package/src/runtime/framework/events/types.ts +4 -0
  43. package/src/runtime/framework/mailbox/types.ts +4 -0
  44. package/src/runtime/framework/plugins/contracts.ts +2 -0
  45. package/src/runtime/framework/runtime.ts +13 -0
  46. package/src/runtime/mailbox-host-relay.ts +13 -12
  47. package/src/runtime/observability/detail-capture.ts +123 -0
  48. package/src/runtime/observability/factory.ts +13 -0
  49. package/src/runtime/observability/recorder.ts +34 -5
  50. package/src/sdk/perception-plugin/index.ts +4 -0
@@ -19,7 +19,7 @@ import {
19
19
  type AgentWorkspaceRemoteFile,
20
20
  type AgentWorkspaceRemoteItem,
21
21
  } from './agent-workspace-client.js';
22
- import type { ResourceType } from './hub-client.js';
22
+ import type { ResourceType, WorkspaceResourceSummary } from './hub-client.js';
23
23
  import { unzip } from './hub-unzip.js';
24
24
  import {
25
25
  getUserDataAgentWorkspaceCurrentFile,
@@ -33,6 +33,8 @@ import {
33
33
  import {
34
34
  capabilityEntryForHubResource,
35
35
  capabilityWorkspacePath,
36
+ registerDiscoveredCapability,
37
+ updateCapabilityHubIdentity,
36
38
  } from './capability-workspace.js';
37
39
  import { inspectClawclawBehaviorSource, behaviorSourceCompatibilityError } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
38
40
  import { listClawclawPerceptionSourcesInDirectory } from '../runtime/clawclaw/plugins/perception/perception-source.js';
@@ -54,6 +56,15 @@ export interface LocalAgentWorkspaceFile {
54
56
 
55
57
  export interface LocalAgentWorkspaceItem {
56
58
  workspaceItemId: string;
59
+ forkedFromResourceId?: string;
60
+ forkReconciliation?: {
61
+ parentResourceId: string;
62
+ parentVersionId?: string;
63
+ parentOperationName?: string;
64
+ status: 'linked' | 'unresolved';
65
+ reason?: 'multiple_forks' | 'parent_still_equipped' | 'baseline_unrecognized'
66
+ | 'parent_working_copy_missing' | 'target_working_copy_exists' | 'not_owned' | 'inventory_unavailable';
67
+ };
57
68
  resourceId: string;
58
69
  versionId: string;
59
70
  versionNumber?: string;
@@ -108,12 +119,14 @@ export interface AgentWorkspaceSyncResult {
108
119
  status: AgentWorkspaceSyncStatus;
109
120
  snapshot: LocalAgentWorkspaceSnapshot;
110
121
  previous?: LocalAgentWorkspaceSnapshot;
122
+ forkReplacements?: readonly string[];
111
123
  }
112
124
 
113
125
  export interface AgentWorkspaceSyncDependencies {
114
126
  client?: AgentWorkspaceConfigReader;
115
127
  download?: (url: string) => Promise<Buffer>;
116
128
  now?: () => Date;
129
+ workspaceInventory?: readonly WorkspaceResourceSummary[];
117
130
  }
118
131
 
119
132
  function record(value: unknown): Record<string, unknown> | null {
@@ -170,6 +183,7 @@ function validateRemoteItem(item: AgentWorkspaceRemoteItem, expectedType: Resour
170
183
  if (item.resource_type !== expectedType) throw new Error('agent_workspace_resource_type_mismatch');
171
184
  safeSegment(item.workspace_item_id, 'workspace_item_id');
172
185
  safeSegment(item.resource_id, 'resource_id');
186
+ if (item.forked_from_resource_id != null) safeSegment(item.forked_from_resource_id, 'forked_from_resource_id');
173
187
  safeSegment(item.version_id, 'version_id');
174
188
  if (
175
189
  !['owned', 'installed'].includes(item.workspace_kind)
@@ -359,6 +373,7 @@ async function materializeItem(
359
373
  return {
360
374
  workspaceItemId: item.workspace_item_id,
361
375
  resourceId: item.resource_id,
376
+ forkedFromResourceId: item.forked_from_resource_id ?? undefined,
362
377
  versionId: item.version_id,
363
378
  versionNumber: item.version_number,
364
379
  versionDescription: item.version_description,
@@ -420,6 +435,7 @@ interface WorkingCopyMetadata {
420
435
  resourceId: string;
421
436
  relativePath: string;
422
437
  knownVersions: NonNullable<LocalAgentWorkspaceItem['knownVersions']>;
438
+ forkReconciliation?: LocalAgentWorkspaceItem['forkReconciliation'];
423
439
  }
424
440
 
425
441
  function singleFileContentDigest(relativePath: string, bytes: Buffer): string {
@@ -691,7 +707,8 @@ export async function syncAgentWorkspaceConfig(
691
707
  const items = previous.items[type];
692
708
  return items.length === remote.items[type].length && remote.items[type].every(item =>
693
709
  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));
710
+ && old.workspaceItemId === item.workspace_item_id && old.contentDigest === item.content_digest
711
+ && old.forkedFromResourceId === (item.forked_from_resource_id ?? undefined)));
695
712
  });
696
713
  if (
697
714
  previous?.revision === remote.revision
@@ -716,12 +733,25 @@ export async function syncAgentWorkspaceConfig(
716
733
  const items = emptyItems();
717
734
  const workingUpdates: Array<{ path: string; bytes: Buffer }> = [];
718
735
  const workingMetadataUpdates: Array<{ path: string; value: WorkingCopyMetadata }> = [];
736
+ const forkReplacements: string[] = [];
737
+ const forkRegistrations: Array<Parameters<typeof registerDiscoveredCapability>[2]> = [];
738
+ const unresolvedParentKeys = new Set<string>();
719
739
  const previousByKey = new Map<ResourceType, Map<string, LocalAgentWorkspaceItem>>(
720
740
  RESOURCE_TYPES.map((type) => [
721
741
  type,
722
742
  new Map((previous?.items[type] ?? []).map((item) => [item.resourceId, item])),
723
743
  ]),
724
744
  );
745
+ const selectedResourceIds = new Set(Object.values(remote.items).flat().map(item => item.resource_id));
746
+ const forkChildren = new Map<string, Set<string>>();
747
+ const addChild = (parent: string | null | undefined, child: string): void => {
748
+ if (!parent) return;
749
+ const children = forkChildren.get(parent) ?? new Set<string>();
750
+ children.add(child);
751
+ forkChildren.set(parent, children);
752
+ };
753
+ for (const item of Object.values(remote.items).flat()) addChild(item.forked_from_resource_id, item.resource_id);
754
+ for (const item of dependencies.workspaceInventory ?? []) addChild(item.forkedFromResourceId, item.resourceId);
725
755
  for (const type of RESOURCE_TYPES) {
726
756
  for (const item of remote.items[type]) {
727
757
  let materialized: LocalAgentWorkspaceItem;
@@ -733,6 +763,8 @@ export async function syncAgentWorkspaceConfig(
733
763
  const prior = previousByKey.get(type)?.get(materialized.resourceId);
734
764
  let workingPath: string | undefined;
735
765
  let persistedWorkingMetadata: WorkingCopyMetadata | undefined;
766
+ let targetAlreadyRegistered = false;
767
+ let pendingForkConflict = false;
736
768
  if (type !== 'skill' && materialized.sourceFiles[0]) {
737
769
  const workspaceType = type === 'strategy' ? 'behavior' : type;
738
770
  const registered = capabilityEntryForHubResource(
@@ -741,6 +773,8 @@ export async function syncAgentWorkspaceConfig(
741
773
  workspaceType,
742
774
  materialized.resourceId,
743
775
  );
776
+ targetAlreadyRegistered = registered !== undefined;
777
+ pendingForkConflict = registered?.hub?.pendingForkConflict === true;
744
778
  workingPath = registered
745
779
  ? capabilityWorkspacePath(workspaceDir, profile, registered)
746
780
  : hubWorkingCopyPath(
@@ -765,7 +799,51 @@ export async function syncAgentWorkspaceConfig(
765
799
  ...(persistedWorkingMetadata?.knownVersions ?? []),
766
800
  ...knownVersions(materialized),
767
801
  ].map((entry) => [entry.versionId, entry])).values()];
802
+ materialized.forkReconciliation = prior?.forkReconciliation ?? persistedWorkingMetadata?.forkReconciliation;
768
803
  let override = inspected?.overrides.get(`${type}:${materialized.resourceId}`);
804
+ let forkCloudChanged: boolean | undefined;
805
+ // Only bridge a newly received, owned, direct replacement. Keep A's
806
+ // file and operation name intact; B gets a separate working copy/name.
807
+ const parentId = materialized.forkedFromResourceId;
808
+ const parent = parentId ? previousByKey.get(type)?.get(parentId) : undefined;
809
+ if (type !== 'skill' && parent && !prior && !targetAlreadyRegistered && !materialized.forkReconciliation) {
810
+ if (!dependencies.workspaceInventory) {
811
+ throw new Error(`agent_workspace_resource_failed:${type}:${item.resource_id}:fork_inventory_unavailable`);
812
+ }
813
+ const workspaceType = type === 'strategy' ? 'behavior' : type;
814
+ const parentEntry = capabilityEntryForHubResource(workspaceDir, profile, workspaceType, parent.resourceId);
815
+ const relation: NonNullable<LocalAgentWorkspaceItem['forkReconciliation']> = {
816
+ parentResourceId: parent.resourceId, parentVersionId: parent.versionId,
817
+ parentOperationName: parentEntry?.runtimeId, status: 'unresolved',
818
+ };
819
+ const parentPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, parent);
820
+ const baseline = parent.sourceFiles[0]?.sha256;
821
+ if (!item.is_created_by_me || item.workspace_kind !== 'owned') relation.reason = 'not_owned';
822
+ else if (selectedResourceIds.has(parent.resourceId)) relation.reason = 'parent_still_equipped';
823
+ else if (forkChildren.get(parent.resourceId)?.size !== 1) relation.reason = 'multiple_forks';
824
+ else if (!baseline || parent.resolution === 'local_origin_unrecognized' || parentEntry?.hub?.localOriginUnrecognized) {
825
+ relation.reason = 'baseline_unrecognized';
826
+ } else if (!parentPath || !existsSync(parentPath)) relation.reason = 'parent_working_copy_missing';
827
+ else if (workingPath && existsSync(workingPath)) relation.reason = 'target_working_copy_exists';
828
+ else {
829
+ const bytes = readFileSync(parentPath);
830
+ const digest = sha256(bytes);
831
+ relation.status = 'linked';
832
+ forkReplacements.push(item.resource_id);
833
+ const localChanged = digest !== baseline && !knownVersions(parent).some(version => version.sourceSha256 === digest);
834
+ if (localChanged && digest !== materialized.sourceFiles[0]?.sha256) {
835
+ override = {
836
+ bytes, sha256: digest,
837
+ contentDigest: singleFileContentDigest(materialized.sourceFiles[0]!.relativePath, bytes),
838
+ modifiedAtMs: statSync(parentPath).mtimeMs, originRecognized: true,
839
+ };
840
+ forkCloudChanged = baseline !== materialized.sourceFiles[0]?.sha256
841
+ || parent.resolution === 'concurrent_difference' || parentEntry?.hub?.pendingForkConflict === true;
842
+ }
843
+ }
844
+ materialized.forkReconciliation = relation;
845
+ if (relation.status === 'unresolved' && parentEntry) unresolvedParentKeys.add(parentEntry.key);
846
+ }
769
847
  if (!override && !prior && workingPath && existsSync(workingPath)) {
770
848
  const bytes = readFileSync(workingPath);
771
849
  const localSha = sha256(bytes);
@@ -794,15 +872,15 @@ export async function syncAgentWorkspaceConfig(
794
872
  );
795
873
  writeFileSync(runtimePath, override.bytes);
796
874
  effectiveBytes = override.bytes;
797
- const remoteAdvancedFromLocalBaseline = prior
875
+ const remoteAdvancedFromLocalBaseline = forkCloudChanged ?? (prior
798
876
  ? prior.versionId !== materialized.versionId
799
877
  : persistedWorkingMetadata !== undefined
800
878
  && !persistedWorkingMetadata.knownVersions.some(
801
879
  (entry) => entry.versionId === materialized.versionId,
802
- );
880
+ ));
803
881
  materialized.resolution = !override.originRecognized
804
882
  ? 'local_origin_unrecognized'
805
- : remoteAdvancedFromLocalBaseline || prior?.resolution === 'concurrent_difference'
883
+ : remoteAdvancedFromLocalBaseline || prior?.resolution === 'concurrent_difference' || pendingForkConflict
806
884
  ? 'concurrent_difference'
807
885
  : 'local_modified';
808
886
  materialized.localContentDigest = override.contentDigest;
@@ -854,8 +932,29 @@ export async function syncAgentWorkspaceConfig(
854
932
  resourceId: materialized.resourceId,
855
933
  relativePath: materialized.sourceFiles[0]!.relativePath,
856
934
  knownVersions: materialized.knownVersions,
935
+ forkReconciliation: materialized.forkReconciliation,
857
936
  },
858
937
  });
938
+ if (materialized.forkReconciliation?.status === 'linked' && forkReplacements.includes(item.resource_id)) {
939
+ const workspaceType = type === 'strategy' ? 'behavior' : type as 'persona' | 'perception';
940
+ const stagedPath = join(temporary, materialized.runtimeEntryPath!);
941
+ const source = type === 'strategy' ? inspectClawclawBehaviorSource(stagedPath, dirname(stagedPath))
942
+ : type === 'perception' ? listClawclawPerceptionSourcesInDirectory(dirname(stagedPath))
943
+ .find(source => source.sourcePath === stagedPath) : undefined;
944
+ const parentEntry = capabilityEntryForHubResource(workspaceDir, profile, workspaceType,
945
+ materialized.forkReconciliation.parentResourceId);
946
+ const runtimeId = source?.id ?? (type === 'persona'
947
+ ? materialized.sourceFiles[0]!.relativePath.replace(/\.md$/i, '')
948
+ : parentEntry?.declaredId ?? parentEntry?.runtimeId);
949
+ if (runtimeId) forkRegistrations.push({
950
+ type: workspaceType, path: workingPath!, runtimeId,
951
+ title: source?.name ?? parentEntry?.title, description: source?.description ?? parentEntry?.description,
952
+ selectedByHub: true,
953
+ hub: { resourceId: item.resource_id, versionId: item.version_id, workspaceItemId: item.workspace_item_id,
954
+ publisher: 'self', baseSha256: materialized.sourceFiles[0]!.sha256,
955
+ pendingForkConflict: materialized.resolution === 'concurrent_difference' || undefined },
956
+ });
957
+ }
859
958
  }
860
959
  items[type].push(materialized);
861
960
  }
@@ -877,7 +976,19 @@ export async function syncAgentWorkspaceConfig(
877
976
  const target = join(revisionsDir, relativeDir);
878
977
  renameSync(temporary, target);
879
978
  writeCurrentPointer(workspaceDir, profile, { revision: remote.revision, relative_dir: relativeDir });
880
- return { status: 'updated', snapshot, ...(previous ? { previous } : {}) };
979
+ for (const registration of forkRegistrations) registerDiscoveredCapability(workspaceDir, profile, registration);
980
+ for (const key of unresolvedParentKeys) {
981
+ const parent = Object.values(previous?.items ?? {}).flat().find(item => {
982
+ const type = item.resourceType === 'strategy' ? 'behavior' : item.resourceType;
983
+ return capabilityEntryForHubResource(workspaceDir, profile, type, item.resourceId)?.key === key;
984
+ });
985
+ if (!parent) continue;
986
+ const type = parent.resourceType === 'strategy' ? 'behavior' : parent.resourceType;
987
+ const entry = capabilityEntryForHubResource(workspaceDir, profile, type, parent.resourceId)!;
988
+ updateCapabilityHubIdentity(workspaceDir, profile, key, { ...entry.hub!, forkRelationshipUnresolved: true });
989
+ }
990
+ return { status: 'updated', snapshot, ...(previous ? { previous } : {}),
991
+ ...(forkReplacements.length ? { forkReplacements } : {}) };
881
992
  } catch (error) {
882
993
  rmSync(temporary, { recursive: true, force: true });
883
994
  throw error;
@@ -233,12 +233,16 @@ export async function refreshCapabilitiesFromCloud(
233
233
  const client = dependencies.client ?? HubClient.fromProfile(profile);
234
234
  const result: CapabilityCloudRefreshResult = { downloaded: [], conflicts: [], failed: [], unchanged: [] };
235
235
  const active = activeResourceIds(activeWorkspace);
236
+ const unresolvedParents = new Set(Object.values(activeWorkspace?.items ?? {}).flat().flatMap(item =>
237
+ item.forkReconciliation?.status === 'unresolved' ? [item.forkReconciliation.parentResourceId] : []));
236
238
  const entries = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
237
239
  .filter((entry) => (
238
240
  entry.runtimeId !== 'clawclaw'
239
241
  && entry.hub
240
242
  && !entry.hub.cloudStatus
243
+ && !entry.hub.forkRelationshipUnresolved
241
244
  && !active.has(entry.hub.resourceId)
245
+ && !unresolvedParents.has(entry.hub.resourceId)
242
246
  ));
243
247
  for (const entry of entries) {
244
248
  const hub = entry.hub!;
@@ -257,12 +261,14 @@ export async function refreshCapabilitiesFromCloud(
257
261
  if (detail.versionId === hub.versionId) {
258
262
  if (
259
263
  hub.observedCloudVersionId
264
+ || (hub.pendingForkConflict && before === hub.baseSha256)
260
265
  || (hub.localOriginUnrecognized && (
261
266
  before === hub.baseSha256 || before === hub.lastUploadedSha256
262
267
  ))
263
268
  ) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
264
269
  ...hub,
265
270
  observedCloudVersionId: undefined,
271
+ pendingForkConflict: before === hub.baseSha256 ? undefined : hub.pendingForkConflict,
266
272
  localOriginUnrecognized: before === hub.baseSha256 || before === hub.lastUploadedSha256
267
273
  ? undefined
268
274
  : hub.localOriginUnrecognized,
@@ -311,6 +317,7 @@ export async function refreshCapabilitiesFromCloud(
311
317
  lastUploadedSha256: artifact.digest,
312
318
  observedCloudVersionId: undefined,
313
319
  localOriginUnrecognized: undefined,
320
+ pendingForkConflict: undefined,
314
321
  });
315
322
  result.downloaded.push({
316
323
  type: entry.type,
@@ -60,7 +60,7 @@ export interface CapabilityCloudSyncFailure {
60
60
  export interface CapabilityCloudSyncSkip {
61
61
  type: CapabilityWorkspaceType;
62
62
  id: string;
63
- reason: 'local_origin_unrecognized';
63
+ reason: 'local_origin_unrecognized' | 'fork_relationship_unresolved';
64
64
  }
65
65
 
66
66
  export interface CapabilityCloudSyncResult {
@@ -241,6 +241,9 @@ export async function syncCapabilitiesToCloud(
241
241
  unchanged: [],
242
242
  };
243
243
  const selectedKeys = dependencies.entryKeys ? new Set(dependencies.entryKeys) : undefined;
244
+ const unresolvedForks = new Set(Object.values(snapshot.items).flat().flatMap(item =>
245
+ item.forkReconciliation?.status === 'unresolved'
246
+ ? [item.resourceId, item.forkReconciliation.parentResourceId] : []));
244
247
  const entries = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
245
248
  .filter((entry) => (
246
249
  entry.runtimeId !== 'clawclaw'
@@ -248,6 +251,10 @@ export async function syncCapabilitiesToCloud(
248
251
  && (!selectedKeys || selectedKeys.has(entry.key))
249
252
  ));
250
253
  for (const entry of entries) {
254
+ if (entry.hub && (entry.hub.forkRelationshipUnresolved || unresolvedForks.has(entry.hub.resourceId))) {
255
+ result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'fork_relationship_unresolved' });
256
+ continue;
257
+ }
251
258
  if (entry.hub?.pendingEquipment !== undefined) {
252
259
  // An old request must never replay over a newer Hub selection. The player
253
260
  // can retry equip explicitly; load always consumes the latest cloud state.
@@ -305,8 +312,8 @@ export async function syncCapabilitiesToCloud(
305
312
  continue;
306
313
  }
307
314
  if (
308
- entry.hub?.observedCloudVersionId
309
- && entry.hub.observedCloudVersionId !== entry.hub.versionId
315
+ (entry.hub?.pendingForkConflict || (entry.hub?.observedCloudVersionId
316
+ && entry.hub.observedCloudVersionId !== entry.hub.versionId))
310
317
  && entry.conflictChoice !== 'local'
311
318
  ) {
312
319
  result.conflicts.push({
@@ -396,6 +403,7 @@ export async function syncCapabilitiesToCloud(
396
403
  baseSha256: payload.digest,
397
404
  lastUploadedSha256: payload.digest,
398
405
  observedCloudVersionId: undefined,
406
+ pendingForkConflict: undefined,
399
407
  ...(action === 'fork' && entry.hub ? {
400
408
  pendingBackpackRestoreResourceId: entry.hub.resourceId,
401
409
  } : {}),
@@ -31,6 +31,9 @@ export interface CapabilityHubIdentity {
31
31
  /** Retry a local equipment choice after the cloud resource itself was created successfully. */
32
32
  pendingEquipment?: boolean;
33
33
  observedCloudVersionId?: string;
34
+ /** Retain a bridged A→B conflict even while B is unequipped. */
35
+ pendingForkConflict?: boolean;
36
+ forkRelationshipUnresolved?: boolean;
34
37
  /** The working copy existed before CCL had a trustworthy Hub baseline. */
35
38
  localOriginUnrecognized?: boolean;
36
39
  /** Cloud association is retained locally but automatic cloud I/O is suspended. */
@@ -11,9 +11,17 @@ export type DiagnosticsLevel = typeof DIAGNOSTICS_LEVELS[number];
11
11
  export interface DiagnosticsConfig {
12
12
  level: DiagnosticsLevel;
13
13
  allow_upload: boolean;
14
+ capture?: DiagnosticsCaptureConfig;
14
15
  }
15
16
 
16
- const TOP_LEVEL_KEYS = new Set(['level', 'allow_upload']);
17
+ export interface DiagnosticsCaptureConfig {
18
+ actions?: boolean;
19
+ behavior_io?: boolean;
20
+ perception_io?: boolean;
21
+ max_record_bytes?: number;
22
+ }
23
+
24
+ const TOP_LEVEL_KEYS = new Set(['level', 'allow_upload', 'capture']);
17
25
 
18
26
  export function defaultDiagnosticsConfig(): DiagnosticsConfig {
19
27
  return {
@@ -41,9 +49,26 @@ export function parseDiagnosticsConfig(value: unknown): DiagnosticsConfig {
41
49
  if (typeof root.allow_upload !== 'boolean') {
42
50
  throw new Error('user-data/diagnostics.json allow_upload must be a boolean.');
43
51
  }
52
+ let capture: DiagnosticsCaptureConfig | undefined;
53
+ if (root.capture !== undefined) {
54
+ const value = record(root.capture);
55
+ if (!value) throw new Error('diagnostics.capture must be an object.');
56
+ if (Object.keys(value).some(key => !['actions', 'behavior_io', 'perception_io', 'max_record_bytes'].includes(key))) {
57
+ throw new Error('Unknown diagnostics.capture field.');
58
+ }
59
+ for (const key of ['actions', 'behavior_io', 'perception_io']) {
60
+ if (value[key] !== undefined && typeof value[key] !== 'boolean') throw new Error(`diagnostics.capture.${key} must be boolean.`);
61
+ }
62
+ if (value.max_record_bytes !== undefined && (!Number.isInteger(value.max_record_bytes)
63
+ || Number(value.max_record_bytes) < 4096 || Number(value.max_record_bytes) > 4 * 1024 * 1024)) {
64
+ throw new Error('diagnostics.capture.max_record_bytes must be 4096..4194304.');
65
+ }
66
+ capture = value as DiagnosticsCaptureConfig;
67
+ }
44
68
  return {
45
69
  level: root.level as DiagnosticsLevel,
46
70
  allow_upload: root.allow_upload,
71
+ ...(capture ? { capture } : {}),
47
72
  };
48
73
  }
49
74
 
@@ -13,6 +13,7 @@ export interface ResourceStats {
13
13
 
14
14
  export interface ResourceSummary {
15
15
  id: string;
16
+ forkedFromResourceId?: string;
16
17
  type: ResourceType;
17
18
  title: string;
18
19
  description: string;
@@ -61,6 +62,7 @@ export interface ListOptions {
61
62
 
62
63
  export interface WorkspaceResourceSummary {
63
64
  workspaceItemId: string;
65
+ forkedFromResourceId?: string;
64
66
  resourceId: string;
65
67
  resourceType: ResourceType;
66
68
  title: string;
@@ -126,6 +128,7 @@ interface RawVersion {
126
128
 
127
129
  interface RawResource {
128
130
  id?: string;
131
+ forked_from_resource_id?: string | null;
129
132
  resource_id: string;
130
133
  resource_type: ResourceType;
131
134
  owner?: { id?: string; name?: string | null; avatar_url?: string | null; is_official?: boolean };
@@ -142,6 +145,7 @@ interface RawResource {
142
145
 
143
146
  interface RawWorkspaceItem {
144
147
  workspace_item_id: string;
148
+ forked_from_resource_id?: string | null;
145
149
  resource_id: string;
146
150
  resource_type: ResourceType;
147
151
  title?: string;
@@ -182,6 +186,7 @@ function toSummary(resource: RawResource): ResourceSummary {
182
186
  const owner = resource.owner ?? {};
183
187
  return {
184
188
  id: resource.resource_id ?? resource.id ?? '',
189
+ forkedFromResourceId: resource.forked_from_resource_id ?? undefined,
185
190
  type: resource.resource_type,
186
191
  title: version.title,
187
192
  description: version.description,
@@ -313,6 +318,7 @@ export class HubClient {
313
318
  return {
314
319
  items: response.data.items.map((item) => ({
315
320
  workspaceItemId: item.workspace_item_id,
321
+ forkedFromResourceId: item.forked_from_resource_id ?? undefined,
316
322
  resourceId: item.resource_id,
317
323
  resourceType: item.resource_type,
318
324
  title: item.title ?? '',
@@ -139,6 +139,8 @@ 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
+ pendingForkConflict: item.forkReconciliation?.status === 'linked' && item.resolution === 'concurrent_difference' || undefined,
143
+ ...(item.forkReconciliation?.status === 'unresolved' ? { forkRelationshipUnresolved: true } : {}),
142
144
  publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256 },
143
145
  });
144
146
  return { path: working, source: 'hub', resourceId: item.resourceId, id: entry.runtimeId };
@@ -46,6 +46,13 @@ export function clawclawMonitorPriority(type: string): number {
46
46
  return CLAWCLAW_MONITOR_EVENT_PRIORITY[type] ?? DEFAULT_MONITOR_PRIORITY;
47
47
  }
48
48
 
49
+ /** Resolved per-event priority; wake policy only changes visual Event ranking. */
50
+ export function clawclawMonitorEventPriority(event: { type: string; wakeAgent?: boolean }): number {
51
+ return event.type.startsWith('visual.')
52
+ ? event.wakeAgent === false ? 40 : 50
53
+ : clawclawMonitorPriority(event.type);
54
+ }
55
+
49
56
  export function clawclawMonitorDelayMs(type: string): number {
50
57
  return CLAWCLAW_MONITOR_DELAY_MS[type] ?? 0;
51
58
  }
@@ -862,6 +862,7 @@ export async function runClawclawOwner(
862
862
  scheduler: runtime?.runtimeEpochDiagnosticSnapshot(),
863
863
  retained_records: runtime?.runtimeRetainedRecordCounts(),
864
864
  persistence: runtime?.runtimePersistenceDiagnostics(),
865
+ detail_capture: telemetry?.detailStats(),
865
866
  behavior: {
866
867
  ...assembly.behavior.diagnosticSnapshot(),
867
868
  effective_source: effectiveBehavior
@@ -896,9 +897,19 @@ export async function runClawclawOwner(
896
897
  throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
897
898
  }
898
899
  const mailboxRepository = runtime.repository;
900
+ const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
901
+ producerPluginId: assembly.perception.id,
902
+ descriptor: (eventType) => assembly.perception.localizedModuleDescriptorForEvent(
903
+ eventType,
904
+ client.gameSyncLocale,
905
+ ),
906
+ send: (reports) => client.reportGameSyncPerceptions(reports),
907
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
908
+ });
899
909
  cclEventsMailbox = new AgentMailboxCoordinator({
900
910
  repository: mailboxRepository,
901
911
  readyView: () => runtime!.readReadyView(0, 1),
912
+ onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
902
913
  presentEvent: ownerAgentEventPresenter('ccl_events', !!options.desktopEvents),
903
914
  compactState: compactStateForEvents,
904
915
  eventFilter: clawclawEventRequiresDetails,
@@ -920,24 +931,15 @@ export async function runClawclawOwner(
920
931
  monitorEnabled: !!options.notificationHost,
921
932
  diagnostic: (name, attributes, severity) => runtime?.diagnostic(name, attributes, severity),
922
933
  });
923
- const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
924
- producerPluginId: assembly.perception.id,
925
- descriptor: (eventType) => assembly.perception.localizedModuleDescriptorForEvent(
926
- eventType,
927
- client.gameSyncLocale,
928
- ),
929
- send: (reports) => client.reportGameSyncPerceptions(reports),
930
- diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
931
- });
932
934
  const mailboxDrivers: ClawclawMailboxDriver[] = [
933
935
  mailboxService,
934
936
  cclEventsMailbox,
935
- perceptionReportAdapter,
936
937
  ];
937
938
  if (options.desktopEvents) {
938
939
  desktopMailbox = new AgentMailboxCoordinator({
939
940
  repository: mailboxRepository,
940
941
  readyView: () => runtime!.readReadyView(0, 1),
942
+ onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
941
943
  presentEvent: ownerAgentEventPresenter('desktop_ipc', true),
942
944
  compactState: compactStateForEvents,
943
945
  consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID,
@@ -992,6 +994,7 @@ export async function runClawclawOwner(
992
994
  assembly.behavior.attachDriver(createClawclawBehaviorControlDriver(runtime));
993
995
  if (channelPolicy.enabled) {
994
996
  channelAdapter = new ClaudeChannelMailboxAdapter({
997
+ onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
995
998
  repository: mailboxRepository,
996
999
  readyView: () => runtime!.readReadyView(0, 1),
997
1000
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
@@ -1079,6 +1082,10 @@ export async function runClawclawOwner(
1079
1082
  mailboxRepository,
1080
1083
  'short',
1081
1084
  MONITOR_MAILBOX_CONSUMER_ID,
1085
+ undefined,
1086
+ (eventIds) => {
1087
+ perceptionReportAdapter.reportDelivered(mailboxService!.monitorDeliveredEvents(eventIds));
1088
+ },
1082
1089
  );
1083
1090
  relayAbort = new AbortController();
1084
1091
  relayAlive = true;
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { DetailCapture } from '../../../observability/detail-capture.js';
2
3
  import { performance } from 'node:perf_hooks';
3
4
  import type { GameClient } from '../../../../lib/game-client.js';
4
5
  import { ApiError } from '../../../../lib/http-transport.js';
@@ -31,6 +32,8 @@ export interface ClawclawActionRequest {
31
32
  audioFile?: { path: string; contentType: string };
32
33
  /** Host-only preconditions for one unified Behavior activation instance. */
33
34
  behaviorOriginEpochSeq?: number;
35
+ /** Runtime-owned operation name, for diagnostic attribution; not sent to the backend. */
36
+ behaviorOriginId?: string;
34
37
  behaviorOriginTick?: number;
35
38
  behaviorActionSafetyGeneration?: number;
36
39
  behaviorActivationGeneration?: number;
@@ -185,6 +188,7 @@ function automatedDiagnosticAttributes(
185
188
  : 'unknown',
186
189
  route: admitted.route,
187
190
  caller_kind: caller.kind,
191
+ behavior_id: request.behaviorOriginId,
188
192
  behavior_activation_id: caller.activationId,
189
193
  behavior_activation_generation: caller.activationGeneration,
190
194
  behavior_layer: caller.layer,
@@ -278,6 +282,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
278
282
  private readonly automatedProviderQueueDepths = new Map<string, number>();
279
283
 
280
284
  constructor(private readonly client: GameClient) {}
285
+ private detailCapture?: DetailCapture;
281
286
 
282
287
  attachAgentActivity(listener: () => void): void {
283
288
  this.noteAgentActivity = listener;
@@ -287,6 +292,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
287
292
  if (this.unregister) throw new Error('Clawclaw Action Plugin is already started.');
288
293
  this.stage = context.currentSegment().kind === 'room_lobby' ? 'room' : 'matching';
289
294
  this.diagnostic = context.diagnostic;
295
+ this.detailCapture = new DetailCapture('actions', context.diagnostic);
290
296
  this.unregister = context.capabilities.provideAction({
291
297
  capability: CLAWCLAW_ACTION_CAPABILITY,
292
298
  describeControl: describeClawclawActionControl,
@@ -347,6 +353,10 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
347
353
  queuePositionReleased = true;
348
354
  const releasedAtMs = performance.now();
349
355
  if (endpointStarted) timing.startedAtMs = releasedAtMs;
356
+ this.detailCapture?.emit(endpointStarted ? 'queue_released' : 'provider_skipped', () => ({
357
+ ...automatedDiagnosticAttributes(request, admitted, caller), action: admitted.action,
358
+ queue_wait_ms: elapsedMs(timing.queuedAtMs, releasedAtMs),
359
+ }));
350
360
  const remainingQueueDepth = Math.max(
351
361
  0,
352
362
  (this.automatedProviderQueueDepths.get(queueKey) ?? 1) - 1,
@@ -533,6 +543,8 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
533
543
  queue_depth: queued.timing.queueDepthAtAdmission,
534
544
  in_flight: queued.timing.inFlightAtAdmission,
535
545
  });
546
+ this.detailCapture?.emit('queued', () => ({ ...automatedDiagnosticAttributes(request, admitted, caller),
547
+ action: admitted.action, queue_depth: queued.timing.queueDepthAtAdmission }));
536
548
  const ownedSettlement = this.ownSettlement(
537
549
  scope,
538
550
  caller,
@@ -589,6 +601,8 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
589
601
  );
590
602
  if (rejected) return rejected;
591
603
  const pending = this.client.chatRoomConfirmed(action.text);
604
+ this.detailCapture?.emit('provider_started', () => ({ action_id: admitted.actionId,
605
+ action, caller, behavior_id: request.behaviorOriginId, route: admitted.route }));
592
606
  actionEndpointStarted = true;
593
607
  markProviderStartedOrSkipped(true);
594
608
  return acknowledgedActionResult(
@@ -604,6 +618,9 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
604
618
  );
605
619
  if (rejected) return rejected;
606
620
  const pending = this.client.submitPreparedActionConfirmed(preparedAction, context.signal);
621
+ this.detailCapture?.emit('provider_started', () => ({ action_id: admitted.actionId,
622
+ action: preparedAction, caller, behavior_id: request.behaviorOriginId,
623
+ origin_epoch_seq: request.behaviorOriginEpochSeq, origin_tick: request.behaviorOriginTick, route: admitted.route }));
607
624
  actionEndpointStarted = true;
608
625
  markProviderStartedOrSkipped(true);
609
626
  const response = await untilAborted(pending, context.signal);
@@ -650,9 +667,13 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
650
667
  // may be stopped after the Runtime starts draining, but the final provider
651
668
  // result still belongs to this Action dispatch and must remain observable.
652
669
  const diagnostic = this.diagnostic;
670
+ const detailCapture = this.detailCapture;
653
671
  const report = (result: ActionResult): ActionResult => {
654
672
  const settledAtMs = performance.now();
655
673
  const errorCode = actionResultErrorCode(result);
674
+ detailCapture?.emit('provider_settled', () => ({ action_id: actionId, action, caller,
675
+ behavior_id: request.behaviorOriginId, origin_epoch_seq: request.behaviorOriginEpochSeq,
676
+ origin_tick: request.behaviorOriginTick, result, total_duration_ms: elapsedMs(timing.queuedAtMs, settledAtMs) }));
656
677
  this.emitDiagnostic('runtime.action.provider_settled', {
657
678
  ...automatedDiagnosticAttributes(request, {
658
679
  actionId,