import { startupSpan, timeStartup } from '../../bin/startup-trace.mjs'; import { isPackageManagedSkill } from '../lib/package-skills.js'; import { Command } from 'commander'; import { readFileSync } from 'node:fs'; import { basename, extname, resolve } from 'node:path'; import { formatLoadReport, loadContext } from '../lib/load-context.js'; import { summarizeStartupBlockers } from '../lib/load-startup.js'; import { saveStartupContext } from '../lib/load-startup-context.js'; import { AuthStore } from '../lib/auth.js'; import { noAccountMessage } from '../lib/account-guidance.js'; import { runAutoUpgradeOnLoad } from '../runtime/auto-upgrade.js'; import { CLAWCLAW_ROLE_IDS, readGameplayConfig, } from '../lib/gameplay-config.js'; import { getWorkspaceDir } from '../lib/init-command.js'; import { ensureAccountUserDataLayout, getUserDataAccountBehaviorsDir, getUserDataAccountPerceptionsDir, getUserDataAccountTriggersDir, } from '../lib/user-data.js'; import { behaviorSourceCompatibilityError, } from '../runtime/clawclaw/plugins/behavior/behavior-source.js'; import { listClawclawTriggerSources } from '../runtime/clawclaw/plugins/trigger/trigger-source.js'; import { GameClient } from '../lib/game-client.js'; import { GAME_STATUS_SCHEMA, queryGameParticipationStatus, type ParticipationStatusClient, } from '../lib/participation-status.js'; import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js'; import { TRIGGER_PLUGIN_API_VERSION } from '../sdk/trigger-plugin/index.js'; import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js'; import { expectedPerceptionApiVersion, isSupportedPerceptionSource } from '../runtime/clawclaw/plugins/perception/perception-source.js'; import { strategyActivationMode } from '../runtime/clawclaw/behavior-trigger.js'; import { resolveReactionBehavior } from '../runtime/clawclaw/reaction-behavior-resolution.js'; import { pluginApiVersionStatus } from '../runtime/clawclaw/plugins/plugin-api-version.js'; import { readLocalAgentWorkspaceSnapshot, resolveLocalAgentWorkspacePath, resolveLocalAgentWorkspaceWorkingCopyPath, resolveLocalAgentWorkspaceSnapshot, syncAgentWorkspaceConfig, type AgentWorkspaceSyncResult, type LocalAgentWorkspaceSnapshot, } from '../lib/agent-workspace-sync.js'; import { inspectSkillNameConflicts, syncAgentWorkspaceSkills } from '../lib/agent-workspace-skills.js'; import { skillConflictNames, skillNameKey } from '../lib/skill-name-conflicts.js'; import { listAgentWorkspaceBehaviorSources, listAgentWorkspacePerceptionSources, mergeAgentWorkspaceBehaviorSources, mergeAgentWorkspacePerceptionSources, } from '../lib/agent-workspace-runtime.js'; import { diagnoseRejectedCapabilityModule, listCapabilityModuleCandidates, warningFromStaticDiagnostic, type CapabilityLoadWarning, type ModuleCapabilityType, } from '../lib/capability-load-diagnostics.js'; import { resolveClawclawResourceMetadata } from '../sdk/resource-metadata.js'; import { discoverLocalCapabilities } from '../lib/capability-discovery.js'; import { capabilitySelectionRef, capabilityWorkspacePath, classifyStrategyLifecycle, pendingCapabilitySelections, readCapabilityWorkspaceRegistry, registerDiscoveredCapability, capabilityEntryForPath, capabilityEntryForHubResource, } from '../lib/capability-workspace.js'; import { syncCapabilitiesToCloud } from '../lib/capability-cloud-sync.js'; import { refreshCapabilitiesFromCloud, syncInstalledCapabilityUpdates, } from '../lib/capability-cloud-refresh.js'; import { filterInactiveAgentWorkspaceSnapshot, reconcileCapabilityWorkspacePresence, reconcileCapabilityLoadout, type CapabilityPresenceResult, } from '../lib/capability-cloud-presence.js'; const PREPARE_SCHEMA = 'ccl.prepare.v1'; const LOAD_DISPLAY_LOCALE = 'en-US'; export interface PrepareCommandDependencies { clientFactory?: () => ParticipationStatusClient; authStore?: AuthStore; workspaceSync?: typeof syncAgentWorkspaceConfig; skillSync?: typeof syncAgentWorkspaceSkills; cloudWorkspaceUpdates?: typeof syncInstalledCapabilityUpdates; cloudRefresh?: typeof refreshCapabilitiesFromCloud; cloudSync?: typeof syncCapabilitiesToCloud; } interface WorkspaceVersionUpdate { type: string; resource_id: string; workspace_item_id: string; version_id: string; from_version?: string; } function inferredWorkspaceVersionUpdates( current: LocalAgentWorkspaceSnapshot | undefined, previous: LocalAgentWorkspaceSnapshot | undefined, ): WorkspaceVersionUpdate[] { if (!current || !previous) return []; const previousByResource = new Map( Object.values(previous.items).flat().map((item) => [ `${item.resourceType}:${item.resourceId}`, item, ]), ); return Object.values(current.items).flat().flatMap((item) => { const before = previousByResource.get(`${item.resourceType}:${item.resourceId}`); if ( !before || before.versionId === item.versionId || (item.resolution !== 'hub' && item.resolution !== 'known_online_old') ) return []; return [{ type: item.resourceType, resource_id: item.resourceId, workspace_item_id: item.workspaceItemId, from_version: before.versionId, version_id: item.versionId, }]; }); } function mergeWorkspaceVersionUpdates( reported: readonly WorkspaceVersionUpdate[], inferred: readonly WorkspaceVersionUpdate[], ): WorkspaceVersionUpdate[] { const merged = new Map(); for (const item of inferred) merged.set(`${item.type}:${item.resource_id}`, { ...item }); for (const item of reported) { const key = `${item.type}:${item.resource_id}`; merged.set(key, { ...merged.get(key), ...item }); } return [...merged.values()]; } function compatibilityWarning( type: ModuleCapabilityType, source: 'hub' | 'local', value: { readonly id: string; readonly name: string; readonly sourcePath: string; readonly management?: { readonly resourceId?: string; readonly versionId?: string; }; }, reason: string, ): CapabilityLoadWarning { return { code: 'CAPABILITY_NOT_LOADED', capability_type: type, source, reason, stage: 'static_discovery', id: value.id, name: value.name, file: basename(value.sourcePath), path: value.sourcePath, ...(value.management?.resourceId ? { resource_id: value.management.resourceId } : {}), ...(value.management?.versionId ? { version_id: value.management.versionId } : {}), }; } function missingProjectionWarning( type: ModuleCapabilityType, item: { readonly resourceId: string; readonly versionId: string; readonly sourceFiles: readonly Readonly<{ relativePath: string }>[]; }, ): CapabilityLoadWarning { return { code: 'CAPABILITY_NOT_LOADED', capability_type: type, source: 'hub', reason: 'projection_missing', stage: 'projection', resource_id: item.resourceId, version_id: item.versionId, file: item.sourceFiles[0]?.relativePath ?? item.resourceId, path: null, }; } function compactCapabilityWarning(warning: CapabilityLoadWarning): Record { const keys = [ 'code', 'capability_type', 'source', 'reason', 'stage', 'id', 'file', 'expected_import', 'received_imports', ] as const; return Object.fromEntries(keys.flatMap((key) => ( warning[key] === undefined ? [] : [[key, warning[key]]] ))); } function compactSkillChanges(changes: ReturnType) { const keys = ['added', 'updated', 'removed', 'preservedModified', 'failed', 'skipped', 'conflicts'] as const; const value = Object.fromEntries(keys.flatMap((key) => ( !changes[key]?.length ? [] : [[key, changes[key]]] ))); return Object.keys(value).length > 0 || changes.requiresUserConfirmation ? { ...value, ...(changes.requiresUserConfirmation ? { requires_user_confirmation: true } : {}), } : undefined; } function compactConfigurationWarnings(warnings: readonly Record[]) { return warnings.map((warning) => { if ( warning.code !== 'DEFAULT_LONG_BEHAVIOR_UNAVAILABLE' || typeof warning.behavior_id !== 'string' || typeof warning.role !== 'string' ) { return { ...warning }; } return { code: 'FALLBACK_BEHAVIOR_NOT_LOADED', role: warning.role, behavior_id: warning.behavior_id, message: `Fallback Behavior ${warning.behavior_id} configured for role ${warning.role} is not loaded.`, }; }); } function compactParticipation(value: object): Record { const { schema: _schema, ...participation } = value as Record; return participation; } export function createPrepareCommand(dependencies: PrepareCommandDependencies = {}): Command { return new Command('prepare') .description('Prepare gameplay resources, resolve startup blockers, and query participation') .option('--full', 'Include persona, memory and the full synchronization and capability report') .action(async ({ full }: { full?: boolean }) => { timeStartup('prepare.auto_upgrade', () => runAutoUpgradeOnLoad({ notify: (message) => console.error(message) })); const accountReady = startupSpan('prepare.account'); const workspaceDir = getWorkspaceDir(); const authStore = dependencies.authStore ?? new AuthStore(); const profile = authStore.getActive(); if (!profile) throw new Error(noAccountMessage('prepare')); ensureAccountUserDataLayout(workspaceDir, profile); accountReady?.(); let cloudWorkspaceUpdates = { updated: [], failed: [], inventory: [], inventoryComplete: false, } as Awaited>; let inventoryReadFailed = false; try { cloudWorkspaceUpdates = await timeStartup('prepare.hub_inventory', () => ( dependencies.cloudWorkspaceUpdates ?? syncInstalledCapabilityUpdates )(profile)); } catch (error) { inventoryReadFailed = true; console.error(`[clawclaw-cli] Hub workspace update check unavailable: ${ error instanceof Error ? error.message : String(error) }`); } let workspaceResult: AgentWorkspaceSyncResult | undefined; const storedWorkspace = readLocalAgentWorkspaceSnapshot(workspaceDir, profile); let activeWorkspace = storedWorkspace ? resolveLocalAgentWorkspaceSnapshot(workspaceDir, profile, storedWorkspace) : undefined; let workspaceSyncStatus: 'updated' | 'unchanged' | 'local_overrides' | 'stale_fallback' | 'unavailable'; let workspaceSyncError: string | undefined; try { workspaceResult = await timeStartup('prepare.workspace_sync', () => (dependencies.workspaceSync ?? syncAgentWorkspaceConfig)(workspaceDir, profile, { workspaceInventory: cloudWorkspaceUpdates.inventoryComplete ? cloudWorkspaceUpdates.inventory : undefined, })); activeWorkspace = workspaceResult.snapshot; workspaceSyncStatus = workspaceResult.status; } catch (error) { workspaceSyncStatus = activeWorkspace ? 'stale_fallback' : 'unavailable'; workspaceSyncError = error instanceof Error ? error.message : String(error); console.error(`[clawclaw-cli] Agent workspace sync unavailable: ${workspaceSyncError}`); } let cloudPresence: CapabilityPresenceResult = cloudWorkspaceUpdates.inventoryComplete ? reconcileCapabilityWorkspacePresence(workspaceDir, profile, cloudWorkspaceUpdates.inventory, workspaceResult?.snapshot) : workspaceResult?.snapshot ? reconcileCapabilityLoadout(workspaceDir, profile, workspaceResult.snapshot) : { deactivated: [], restored: [], inactiveResourceIds: [] }; activeWorkspace = filterInactiveAgentWorkspaceSnapshot( workspaceDir, profile, activeWorkspace, cloudPresence.inactiveResourceIds, ); const cloudRefreshChanges = inventoryReadFailed ? { downloaded: [], conflicts: [], failed: [], unchanged: [] } : await timeStartup('prepare.cloud_refresh', () => (dependencies.cloudRefresh ?? refreshCapabilitiesFromCloud)( workspaceDir, profile, activeWorkspace, )); const newForkReplacements = activeWorkspace ? Object.values(activeWorkspace.items).flat().filter(item => workspaceResult?.forkReplacements?.includes(item.resourceId)) : []; let firstSkillChanges: ReturnType | undefined; const renderFinalContext = async (completedSync?: Awaited>): Promise => { const inspectDone = startupSpan('prepare.local_inspection'); let snapshot; try { snapshot = loadContext(authStore, { includeContent: false }); } catch (error) { if (error instanceof Error && error.message === 'Not logged in.') { throw new Error(noAccountMessage('prepare')); } throw error; } if ( snapshot.persona.source === 'hub' && snapshot.persona.resource_id && cloudPresence.inactiveResourceIds.includes(snapshot.persona.resource_id) ) { snapshot.persona = { path: null, exists: false, content: '', source: 'none' }; } const gameplay = readGameplayConfig(workspaceDir, profile); const discoveredLocal = timeStartup('prepare.capability_scan', () => discoverLocalCapabilities(workspaceDir, profile)); const strategyLifecycles = new Map>(); const strategyLifecycle = (path: string) => { const known = strategyLifecycles.get(path); if (known !== undefined) return known; const lifecycle = classifyStrategyLifecycle(readFileSync(path, 'utf8')); strategyLifecycles.set(path, lifecycle); return lifecycle; }; const capabilityWarnings: CapabilityLoadWarning[] = []; const disabledBehaviors = new Set(gameplay.disabled_behaviors); const hubBehaviors = activeWorkspace ? listAgentWorkspaceBehaviorSources(workspaceDir, profile, activeWorkspace) : []; if (activeWorkspace) { for (const source of hubBehaviors) { const item = activeWorkspace.items.strategy.find((candidate) => ( candidate.resourceId === source.management.resourceId )); const workingPath = item ? resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item) : undefined; if (!item || !workingPath) continue; registerDiscoveredCapability(workspaceDir, profile, { type: 'behavior', path: workingPath, runtimeId: source.declaredId ?? source.id, title: source.name, description: source.description, strategyLifecycle: strategyLifecycle(workingPath), selectedByHub: true, hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId, publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256, localOriginUnrecognized: item.resolution === 'local_origin_unrecognized' ? true : undefined, }, }); } } const localBehaviorDir = getUserDataAccountBehaviorsDir(workspaceDir, profile); const allLocalBehaviors = discoveredLocal.behaviors.map(({ source }) => source); const localBehaviors = discoveredLocal.behaviors .filter(({ source, entry }) => ( entry.selection === 'equipped' && !disabledBehaviors.has(source.id) && !activeWorkspace?.items.strategy.some(item => item.resourceId === entry.hub?.resourceId) )) .map(({ source }) => source); const localBehaviorSourcePaths = new Set(allLocalBehaviors.map(({ sourcePath }) => resolve(sourcePath))); let expectedLocalBehaviors = localBehaviors.length; for (const path of listCapabilityModuleCandidates(localBehaviorDir)) { if (localBehaviorSourcePaths.has(resolve(path))) continue; const diagnostic = diagnoseRejectedCapabilityModule('behavior', path); const operationName = capabilityEntryForPath(workspaceDir, profile, 'behavior', path)?.runtimeId ?? diagnostic.declaredId; if (operationName && disabledBehaviors.has(operationName)) continue; expectedLocalBehaviors += 1; capabilityWarnings.push({ ...warningFromStaticDiagnostic('behavior', 'local', diagnostic), ...(operationName ? { id: operationName } : {}) }); } if (activeWorkspace) { const discoveredResources = new Set(hubBehaviors.map(source => source.management.resourceId)); for (const item of activeWorkspace.items.strategy) { if (!item.runtimeEntryPath) { capabilityWarnings.push(missingProjectionWarning('behavior', item)); continue; } if (discoveredResources.has(item.resourceId)) continue; const path = resolveLocalAgentWorkspacePath( workspaceDir, profile, activeWorkspace, item.runtimeEntryPath, ); capabilityWarnings.push(warningFromStaticDiagnostic( 'behavior', 'hub', diagnoseRejectedCapabilityModule('behavior', path), { resourceId: item.resourceId, versionId: item.versionId }, )); } } const enabledBehaviors = mergeAgentWorkspaceBehaviorSources( localBehaviors, hubBehaviors, disabledBehaviors, ); const behaviorEntry = (source: typeof enabledBehaviors[number]) => { const compatibilityError = behaviorSourceCompatibilityError(source); const versionCompatible = source.apiVersion === BEHAVIOR_PLUGIN_API_VERSION; const loadable = versionCompatible && compatibilityError === undefined; return { id: source.id, name: source.name, description: source.description, api_version: source.apiVersion ?? null, expected_api_version: BEHAVIOR_PLUGIN_API_VERSION, loadable, activation_mode: strategyActivationMode(source), ...(loadable ? {} : { compatibility_error: versionCompatible ? compatibilityError : `behavior_api_version_unsupported:expected=${BEHAVIOR_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`, }), source: source.management.source, managed_by: source.management.managedBy, ...(source.management.publisher ? { publisher: source.management.publisher } : {}), ...(source.management.resourceId ? { resource_id: source.management.resourceId } : {}), ...(source.management.versionId ? { version_id: source.management.versionId } : {}), ...(source.management.resolution ? { resolution: source.management.resolution } : {}), }; }; const behaviorEntries = enabledBehaviors.map(behaviorEntry); const behaviors = behaviorEntries.filter(({ loadable }) => loadable); const incompatibleBehaviors = behaviorEntries.filter(({ loadable }) => !loadable); for (const source of enabledBehaviors) { const compatibilityError = behaviorSourceCompatibilityError(source); const reason = source.apiVersion === BEHAVIOR_PLUGIN_API_VERSION ? compatibilityError : `behavior_api_version_unsupported:expected=${BEHAVIOR_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`; if (!reason) continue; capabilityWarnings.push(compatibilityWarning( 'behavior', source.management.source, source, reason, )); } const selectedLocalBehaviorPaths = new Set(localBehaviors.map(({ sourcePath }) => resolve(sourcePath))); for (const source of allLocalBehaviors) { if (selectedLocalBehaviorPaths.has(resolve(source.sourcePath))) continue; const compatibilityError = behaviorSourceCompatibilityError(source); const reason = source.apiVersion === BEHAVIOR_PLUGIN_API_VERSION ? compatibilityError : `behavior_api_version_unsupported:expected=${BEHAVIOR_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`; if (!reason) continue; capabilityWarnings.push(compatibilityWarning('behavior', 'local', source, reason)); } const configurationWarnings: Array> = []; for (const item of Object.values(activeWorkspace?.items ?? {}).flat()) { const relation = item.forkReconciliation; if (relation?.status !== 'unresolved') continue; configurationWarnings.push({ code: 'FORK_RECONCILIATION_SKIPPED', resource_id: item.resourceId, forked_from_resource_id: relation.parentResourceId, reason: relation.reason, message: 'Fork relationship was not automatically merged. Original local files are preserved; review the resource relationship before synchronizing edits.', }); } if (workspaceSyncError) configurationWarnings.push({ code: 'WORKSPACE_SYNC_FAILED', message: workspaceSyncError, using_previous_snapshot: !!activeWorkspace, }); if (inventoryReadFailed) configurationWarnings.push({ code: 'WORKSPACE_INVENTORY_UNAVAILABLE', message: 'Backpack could not be verified; automatic cloud writes and inactive-resource refresh were skipped.', }); for (const role of CLAWCLAW_ROLE_IDS) { const fallback = gameplay.fallback_behaviors[role]; if (fallback === null) continue; const entry = behaviors.find(({ id }) => id === fallback); if (!entry || entry.activation_mode === 'automatic_only') { const unavailableReason = disabledBehaviors.has(fallback) ? 'local_disabled_or_unselected' : 'not_loaded'; configurationWarnings.push({ code: 'DEFAULT_LONG_BEHAVIOR_UNAVAILABLE', role, behavior_id: fallback, reason: entry ? 'strategy_automatic_only' : unavailableReason, }); } } const disabledPerceptions = new Set(gameplay.disabled_perception_modules); const hubPerceptions = activeWorkspace ? listAgentWorkspacePerceptionSources(workspaceDir, profile, activeWorkspace) : []; if (activeWorkspace) { for (const source of hubPerceptions) { const item = activeWorkspace.items.perception.find(candidate => candidate.resourceId === source.resourceId); const workingPath = item ? resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item) : undefined; if (!item || !workingPath) continue; registerDiscoveredCapability(workspaceDir, profile, { type: 'perception', path: workingPath, runtimeId: source.declaredId ?? source.id, title: source.name, description: source.description, selectedByHub: true, hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId, publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256, localOriginUnrecognized: item.resolution === 'local_origin_unrecognized' ? true : undefined, }, }); } } const hubPerceptionIds = new Set(hubPerceptions.map(({ id }) => id)); const localPerceptionDir = getUserDataAccountPerceptionsDir(workspaceDir, profile); const allLocalPerceptions = discoveredLocal.perceptions.map(({ source }) => source); const localPerceptions = discoveredLocal.perceptions .filter(({ source, entry }) => ( entry.selection === 'equipped' && !disabledPerceptions.has(source.id) && !activeWorkspace?.items.perception.some(item => item.resourceId === entry.hub?.resourceId) )) .map(({ source }) => source); const localPerceptionSourcePaths = new Set( allLocalPerceptions.map(({ sourcePath }) => resolve(sourcePath)), ); let expectedLocalPerceptions = localPerceptions.length; for (const path of listCapabilityModuleCandidates(localPerceptionDir)) { if (localPerceptionSourcePaths.has(resolve(path))) continue; const diagnostic = diagnoseRejectedCapabilityModule('perception', path); const operationName = capabilityEntryForPath(workspaceDir, profile, 'perception', path)?.runtimeId ?? diagnostic.declaredId; if (operationName && disabledPerceptions.has(operationName)) continue; expectedLocalPerceptions += 1; capabilityWarnings.push({ ...warningFromStaticDiagnostic('perception', 'local', diagnostic), ...(operationName ? { id: operationName } : {}) }); } if (activeWorkspace) { const discoveredResources = new Set(hubPerceptions.map(source => source.resourceId)); for (const item of activeWorkspace.items.perception) { if (!item.runtimeEntryPath) { capabilityWarnings.push(missingProjectionWarning('perception', item)); continue; } if (discoveredResources.has(item.resourceId)) continue; const path = resolveLocalAgentWorkspacePath( workspaceDir, profile, activeWorkspace, item.runtimeEntryPath, ); capabilityWarnings.push(warningFromStaticDiagnostic( 'perception', 'hub', diagnoseRejectedCapabilityModule('perception', path), { resourceId: item.resourceId, versionId: item.versionId }, )); } } const enabledPerceptions = mergeAgentWorkspacePerceptionSources( localPerceptions, hubPerceptions, disabledPerceptions, ); const reminderTopics = new Map(); for (const source of enabledPerceptions) { if (!source.reminder || source.apiVersion !== PERCEPTION_PLUGIN_API_VERSION) continue; const ids = reminderTopics.get(source.reminder.topic) ?? []; ids.push(source.id); reminderTopics.set(source.reminder.topic, ids); } const conflictingPerceptions = new Set([...reminderTopics.values()].filter(ids => ids.length > 1).flat()); for (const source of enabledPerceptions.filter(source => conflictingPerceptions.has(source.id))) { capabilityWarnings.push({ code: 'CAPABILITY_NOT_LOADED', capability_type: 'perception', source: hubPerceptionIds.has(source.id) ? 'hub' : 'local', stage: 'selection', id: source.id, reason: `perception_topic_conflict:${source.reminder!.topic}:${reminderTopics.get(source.reminder!.topic)!.join(',')}` }); } const reflexBindings = enabledPerceptions.filter(isSupportedPerceptionSource).flatMap(source => Object.entries(source.module?.behaviors ?? {}).map(([key,binding]) => { const id = resolveReactionBehavior(binding,behaviorEntries.map(entry => ({ id: entry.id, declaredId: enabledBehaviors.find(source => source.id === entry.id)?.declaredId, resourceId: entry.resource_id, loadable: entry.loadable }))); if (!id) configurationWarnings.push({ code: 'PERCEPTION_BEHAVIOR_NOT_LOADED', perception_id: source.id, binding: key, behavior_name: binding.name, message: `Equip the paired strategy ${binding.name}; perception observation and notifications remain available.` }); const target = behaviors.find(entry => entry.id === id); const available = !!target && target.activation_mode !== 'automatic_only'; return { perception_id: source.id, binding: key, behavior_id: id ?? binding.name, available, default_enabled: available, ...(available ? {} : { reason: target ? 'strategy_automatic_only' : 'behavior_not_loaded' }) }; })); const perceptionEntry = (source: typeof enabledPerceptions[number]) => ({ id: source.id, name: source.name, description: source.description, source: hubPerceptionIds.has(source.id) ? 'hub' : 'workspace', ...pluginApiVersionStatus('perception', expectedPerceptionApiVersion(source), source.apiVersion), ...(source.compatibilityError ? { loadable: false, compatibility_error: source.compatibilityError } : {}), }); const perceptions = enabledPerceptions .filter(source => isSupportedPerceptionSource(source) && !conflictingPerceptions.has(source.id)) .map(perceptionEntry); const incompatiblePerceptions = enabledPerceptions .filter(source => !isSupportedPerceptionSource(source)) .map(perceptionEntry); for (const source of enabledPerceptions) { if (isSupportedPerceptionSource(source)) continue; capabilityWarnings.push(compatibilityWarning( 'perception', hubPerceptionIds.has(source.id) ? 'hub' : 'local', source, source.compatibilityError ?? `perception_api_version_unsupported:expected=${expectedPerceptionApiVersion(source)}:received=${source.apiVersion ?? 'missing'}`, )); } const selectedLocalPerceptionPaths = new Set(localPerceptions.map(({ sourcePath }) => resolve(sourcePath))); for (const source of allLocalPerceptions) { if ( selectedLocalPerceptionPaths.has(resolve(source.sourcePath)) || isSupportedPerceptionSource(source) ) continue; capabilityWarnings.push(compatibilityWarning( 'perception', 'local', source, source.compatibilityError ?? `perception_api_version_unsupported:expected=${expectedPerceptionApiVersion(source)}:received=${source.apiVersion ?? 'missing'}`, )); } const disabledTriggers = new Set(gameplay.disabled_triggers); const localTriggerDir = getUserDataAccountTriggersDir(workspaceDir, profile); const triggerSources = listClawclawTriggerSources(localTriggerDir); const enabledTriggers = triggerSources.filter((source) => !disabledTriggers.has(source.id)); const triggerSourcePaths = new Set(triggerSources.map(({ sourcePath }) => resolve(sourcePath))); let expectedLocalTriggers = enabledTriggers.length; for (const path of listCapabilityModuleCandidates(localTriggerDir)) { if (triggerSourcePaths.has(resolve(path))) continue; const diagnostic = diagnoseRejectedCapabilityModule('trigger', path); if (diagnostic.declaredId && disabledTriggers.has(diagnostic.declaredId)) continue; expectedLocalTriggers += 1; capabilityWarnings.push(warningFromStaticDiagnostic('trigger', 'local', diagnostic)); } const availableBehaviorIds = new Set(behaviors.map(({ id }) => id)); const triggerEntry = (source: typeof enabledTriggers[number]) => { const behaviorId = gameplay.triggers[source.id]?.behavior ?? source.manifest.defaultBehavior; const versionCompatible = source.apiVersion === TRIGGER_PLUGIN_API_VERSION; const bindingAvailable = availableBehaviorIds.has(behaviorId); const loadable = versionCompatible && bindingAvailable; return { id: source.id, name: source.name, description: source.description, api_version: source.apiVersion, expected_api_version: TRIGGER_PLUGIN_API_VERSION, loadable, ...(loadable ? {} : { compatibility_error: versionCompatible ? `trigger_binding_unavailable:${behaviorId}` : `trigger_api_version_unsupported:expected=${TRIGGER_PLUGIN_API_VERSION}:received=${source.apiVersion}`, }), behavior_id: behaviorId, source: 'local', }; }; const triggerEntries = enabledTriggers.map(triggerEntry); const triggers = triggerEntries.filter(({ loadable }) => loadable); const incompatibleTriggers = triggerEntries.filter(({ loadable }) => !loadable); for (const entry of incompatibleTriggers) { const source = enabledTriggers.find(({ id }) => id === entry.id)!; capabilityWarnings.push(compatibilityWarning( 'trigger', 'local', source, String(entry.compatibility_error), )); } // Mutate Agent-facing Skill/Persona targets only after every non-Skill // source has been parsed and Hub/local identity conflicts have passed. inspectDone?.(); const projectDone = startupSpan('prepare.skill_persona_projection'); const skillChanges = activeWorkspace ? (dependencies.skillSync ?? syncAgentWorkspaceSkills)(workspaceDir, profile, activeWorkspace) : { added: [], updated: [], removed: [], unchanged: [], failed: [], preservedModified: [], conflicts: inspectSkillNameConflicts(workspaceDir, profile), requiresUserConfirmation: false, }; const hubPersonaItem = activeWorkspace?.items.persona[0]; if (hubPersonaItem && snapshot.persona.source !== 'local' && ( snapshot.persona.source !== 'hub' || snapshot.persona.resource_id !== hubPersonaItem.resourceId || snapshot.persona.exists !== true )) { capabilityWarnings.push({ code: 'CAPABILITY_NOT_LOADED', capability_type: 'persona', source: 'hub', reason: 'persona_file_unavailable', stage: 'selection', resource_id: hubPersonaItem.resourceId, version_id: hubPersonaItem.versionId, path: snapshot.persona.path, }); } else if (snapshot.persona.source === 'local' && snapshot.persona.exists !== true) { capabilityWarnings.push({ code: 'CAPABILITY_NOT_LOADED', capability_type: 'persona', source: 'local', reason: 'persona_file_unavailable', stage: 'selection', ...(snapshot.persona.id ? { id: snapshot.persona.id } : {}), path: snapshot.persona.path, }); } if ( hubPersonaItem && snapshot.persona.source === 'hub' && snapshot.persona.path && snapshot.persona.exists ) { registerDiscoveredCapability(workspaceDir, profile, { type: 'persona', path: snapshot.persona.path, runtimeId: basename(snapshot.persona.path, extname(snapshot.persona.path)), title: hubPersonaItem.title, description: hubPersonaItem.description, initialDescription: `Persona ${basename(snapshot.persona.path)}`, selectedByHub: true, hub: { resourceId: hubPersonaItem.resourceId, versionId: hubPersonaItem.versionId, workspaceItemId: hubPersonaItem.workspaceItemId, publisher: hubPersonaItem.hub?.publisher ?? 'community', baseSha256: hubPersonaItem.sourceFiles[0]?.sha256, localOriginUnrecognized: hubPersonaItem.resolution === 'local_origin_unrecognized' ? true : undefined, }, }); } projectDone?.(); const cloudChanges = completedSync ?? (activeWorkspace && !inventoryReadFailed ? await timeStartup('prepare.cloud_upload', () => (dependencies.cloudSync ?? syncCapabilitiesToCloud)( workspaceDir, profile, activeWorkspace!, )) : undefined); if (!completedSync && cloudChanges && ( cloudChanges.uploaded.length > 0 || cloudChanges.equipmentChanged || cloudChanges.failed.some(item => item.action === 'equipment') )) { firstSkillChanges = skillChanges; try { strategyLifecycles.clear(); const updatedInventory = await timeStartup('prepare.hub_inventory', () => (dependencies.cloudWorkspaceUpdates ?? syncInstalledCapabilityUpdates)(profile)); workspaceResult = await timeStartup('prepare.workspace_sync', () => (dependencies.workspaceSync ?? syncAgentWorkspaceConfig)(workspaceDir, profile, { workspaceInventory: updatedInventory.inventoryComplete ? updatedInventory.inventory : undefined, })); activeWorkspace = workspaceResult.snapshot; workspaceSyncStatus = workspaceResult.status; if (updatedInventory.inventoryComplete) { const presence = reconcileCapabilityWorkspacePresence(workspaceDir, profile, updatedInventory.inventory, activeWorkspace); cloudPresence = { deactivated: [...cloudPresence.deactivated, ...presence.deactivated], restored: [...cloudPresence.restored, ...presence.restored], inactiveResourceIds: presence.inactiveResourceIds, }; } activeWorkspace = filterInactiveAgentWorkspaceSnapshot(workspaceDir, profile, activeWorkspace, cloudPresence.inactiveResourceIds); } catch (error) { workspaceSyncStatus = 'stale_fallback'; workspaceSyncError = `post_upload_workspace_refresh_failed:${error instanceof Error ? error.message : String(error)}`; console.error(`[clawclaw-cli] ${workspaceSyncError}`); } return renderFinalContext(cloudChanges); } let participation; try { const client = (dependencies.clientFactory ?? (() => GameClient.fromAuth()))(); participation = await timeStartup('prepare.participation', () => queryGameParticipationStatus(client)); } catch (error) { participation = { schema: GAME_STATUS_SCHEMA, status: 'unknown' as const, queue_status: null, }; const message = error instanceof Error ? error.message : String(error); console.error(`[clawclaw-cli] participation status unavailable: ${message}`); } const capabilitySummary = { behavior: { selected_hub: activeWorkspace?.items.strategy.length ?? 0, eligible_local: expectedLocalBehaviors, available: behaviors.length, warnings: capabilityWarnings.filter(({ capability_type }) => ( capability_type === 'behavior' )).length, }, perception: { selected_hub: activeWorkspace?.items.perception.length ?? 0, eligible_local: expectedLocalPerceptions, available: perceptions.length, warnings: capabilityWarnings.filter(({ capability_type }) => ( capability_type === 'perception' )).length, }, trigger: { selected_hub: 0, eligible_local: expectedLocalTriggers, available: triggers.length, warnings: capabilityWarnings.filter(({ capability_type }) => ( capability_type === 'trigger' )).length, }, persona: { selected_hub: activeWorkspace?.items.persona.length ?? 0, selected_local: snapshot.persona.source === 'local' ? 1 : 0, available: snapshot.persona.exists ? 1 : 0, warnings: capabilityWarnings.filter(({ capability_type }) => ( capability_type === 'persona' )).length, }, }; const behaviorSourceById = new Map(enabledBehaviors.map((source) => [source.id, source])); const perceptionSourceById = new Map(enabledPerceptions.map((source) => [source.id, source])); const triggerSourceById = new Map(enabledTriggers.map((source) => [source.id, source])); const skillChangeSummary = compactSkillChanges(firstSkillChanges ? { ...skillChanges, added: [...new Set([...firstSkillChanges.added, ...skillChanges.added])], updated: [...new Set([...firstSkillChanges.updated, ...skillChanges.updated])], removed: [...new Set([...firstSkillChanges.removed, ...skillChanges.removed])], failed: [...firstSkillChanges.failed, ...skillChanges.failed], skipped: skillChanges.skipped, } : skillChanges); const cloudConflicts = [...cloudRefreshChanges.conflicts, ...(cloudChanges?.conflicts ?? [])] .filter((value, index, values) => values.findIndex((candidate) => ( candidate.type === value.type && candidate.id === value.id && candidate.resource_id === value.resource_id )) === index).map(value => { const entry = capabilityEntryForHubResource(workspaceDir, profile, value.type, value.resource_id); return { ...value, ...(entry ? { selection_ref: capabilitySelectionRef(entry), working_copy_path: capabilityWorkspacePath(workspaceDir, profile, entry) } : {}) }; }); const cloudFailures = [...cloudRefreshChanges.failed, ...(cloudChanges?.failed ?? [])]; const forkReplacements = newForkReplacements.map(item => { const type = item.resourceType === 'strategy' ? 'behavior' : item.resourceType; const entry = capabilityEntryForHubResource(workspaceDir, profile, type, item.resourceId); const finalItem = Object.values(activeWorkspace?.items ?? {}).flat().find(current => current.resourceId === item.resourceId); return { type, id: entry?.runtimeId, resource_id: item.resourceId, ...(entry ? { selection_ref: capabilitySelectionRef(entry) } : {}), forked_from_resource_id: item.forkReconciliation!.parentResourceId, from_id: item.forkReconciliation!.parentOperationName, resolution: finalItem?.resolution ?? item.resolution, }; }); const workspaceVersionUpdates = mergeWorkspaceVersionUpdates( cloudWorkspaceUpdates.updated, inferredWorkspaceVersionUpdates(activeWorkspace, workspaceResult?.previous), ); const cloudChangeSummary = ( workspaceVersionUpdates.length > 0 || cloudWorkspaceUpdates.failed.length > 0 || cloudRefreshChanges.downloaded.length > 0 || (cloudChanges?.uploaded.length ?? 0) > 0 || (cloudChanges?.skipped.length ?? 0) > 0 || cloudConflicts.length > 0 || cloudFailures.length > 0 || cloudPresence.deactivated.length > 0 || cloudPresence.restored.length > 0 || forkReplacements.length > 0 ) ? { workspace_updated: workspaceVersionUpdates, workspace_update_failed: cloudWorkspaceUpdates.failed, downloaded: cloudRefreshChanges.downloaded, uploaded: cloudChanges?.uploaded ?? [], skipped: cloudChanges?.skipped ?? [], conflicts: cloudConflicts, failed: cloudFailures, deactivated: cloudPresence.deactivated, restored: cloudPresence.restored, ...(forkReplacements.length ? { fork_replacements: forkReplacements } : {}), unchanged: cloudChanges?.unchanged ?? [], } : undefined; const selectionRequired = pendingCapabilitySelections(workspaceDir, profile); const blockedSkillNames = skillConflictNames(skillChanges.conflicts ?? []); const reservedSkillPaths = new Set(discoveredLocal.reservedSkills.map(skill => skill.path)); const skills = [...new Set(Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .filter((entry) => entry.type === 'skill' && entry.selection === 'equipped' && !blockedSkillNames.has(skillNameKey(entry.runtimeId)) && !entry.hub?.cloudStatus && !isPackageManagedSkill(entry.runtimeId) && !reservedSkillPaths.has(capabilityWorkspacePath(workspaceDir, profile, entry))) .map((entry) => entry.runtimeId).concat((skillChanges.conflicts ?? []) .flatMap(item => item.active ? [item.active.id ?? item.active.name] : [])))].sort(); const output = { startup: summarizeStartupBlockers(selectionRequired.map(entry => ({ type: entry.type, id: entry.runtimeId, selection_ref: capabilitySelectionRef(entry), })), cloudConflicts, cloudFailures), sync: { status: workspaceSyncStatus, revision: activeWorkspace?.revision ?? null, ...(workspaceSyncError ? { error: workspaceSyncError } : {}), }, ...(skillChangeSummary || cloudChangeSummary || discoveredLocal.reservedSkills.length ? { changes: { ...(discoveredLocal.reservedSkills.length ? { skipped_local_skills: discoveredLocal.reservedSkills } : {}), ...(skillChangeSummary ? { skills: skillChangeSummary } : {}), ...(cloudChangeSummary ? { cloud_sync: cloudChangeSummary } : {}), }, } : {}), capabilities: { summary: capabilitySummary, skills, behaviors: behaviors.map((entry) => { const source = behaviorSourceById.get(entry.id)!; const localized = resolveClawclawResourceMetadata(source, LOAD_DISPLAY_LOCALE); return { id: entry.id, name: localized.name, description: source.description, source: entry.source, activation_mode: entry.activation_mode, strategy_type: strategyLifecycle(source.sourcePath), ...(source.trigger ? { reflex: { available: true } } : source.triggerError ? { reflex: { available: false, reason: source.triggerError } } : {}), ...(source.management.versionNumber ? { version_number: source.management.versionNumber, version_description: source.management.versionDescription ?? '' } : {}), }; }), perceptions: perceptions.map((entry) => { const source = perceptionSourceById.get(entry.id)!; const localized = resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, LOAD_DISPLAY_LOCALE); return { id: entry.id, name: localized.name, description: source.description, source: entry.source, ...(reflexBindings.some(binding => binding.perception_id === entry.id) ? { reflex_bindings: reflexBindings.filter(binding => binding.perception_id === entry.id) } : {}), }; }), triggers: triggers.map((entry) => { const source = triggerSourceById.get(entry.id)!; const localized = resolveClawclawResourceMetadata(source.manifest, LOAD_DISPLAY_LOCALE); return { id: entry.id, name: localized.name, description: localized.description, source: entry.source, behavior_id: entry.behavior_id, }; }), warnings: capabilityWarnings.map(compactCapabilityWarning), selection_required: selectionRequired.map((entry) => ({ type: entry.type, id: entry.runtimeId, declared_id: entry.declaredId ?? entry.runtimeId, selection_ref: capabilitySelectionRef(entry), working_copy_path: capabilityWorkspacePath(workspaceDir, profile, entry), title: entry.title, ...(entry.hub ? { resource_id: entry.hub.resourceId, publisher: entry.hub.publisher, owner_id: entry.hub.ownerId, owner_name: entry.hub.ownerName } : {}), strategy_type: entry.strategyLifecycle, action: `Choose once with ccl capability equip ${capabilitySelectionRef(entry)} or ccl capability unequip ${capabilitySelectionRef(entry)}.`, })), }, configuration_warnings: compactConfigurationWarnings(configurationWarnings), participation: compactParticipation(participation), }; const report = { sync: output.sync, changes: output.changes, capabilities: output.capabilities, configuration_warnings: output.configuration_warnings, persona_available: snapshot.persona.exists, }; const { prepared_at } = timeStartup('prepare.save_report', () => saveStartupContext(workspaceDir, profile, report)); const startup = { schema: PREPARE_SCHEMA, startup: output.startup, participation: output.participation }; if (full) { console.log(JSON.stringify({ ...startup, ...formatLoadReport(loadContext(authStore), { ...report, prepared_at }) }, null, 2)); return; } const equipmentConflicts = cloudFailures.filter(value => value.action === 'equipment' && 'code' in value && value.code === 'SKILL_NAME_CONFLICT'); const unavailableHosts = skillChanges.skipped?.filter(item => item.reason === 'skill_host_directory_unavailable') ?? []; const startupChanges = { ...(unavailableHosts.length ? { skills: { skipped: unavailableHosts } } : {}), ...(cloudConflicts.length || equipmentConflicts.length ? { cloud_sync: { conflicts: cloudConflicts, failed: equipmentConflicts } } : {}), }; console.log(JSON.stringify({ ...startup, ...(selectionRequired.length ? { capabilities: { selection_required: output.capabilities.selection_required } } : {}), ...(Object.keys(startupChanges).length ? { changes: startupChanges } : {}), }, null, 2)); }; await renderFinalContext(); }); }