import { createHash, randomUUID } from 'node:crypto'; import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs'; import { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'; import type { AuthProfile } from './auth.js'; import { AgentWorkspaceClient, downloadAgentWorkspaceFile, type AgentWorkspaceConfigReader, type AgentWorkspaceRemoteConfig, type AgentWorkspaceRemoteFile, type AgentWorkspaceRemoteItem, } from './agent-workspace-client.js'; import type { ResourceType, WorkspaceResourceSummary } from './hub-client.js'; import { unzip } from './hub-unzip.js'; import { getUserDataAgentWorkspaceCurrentFile, getUserDataAgentWorkspaceDir, getUserDataAgentWorkspaceRevisionsDir, getUserDataAccountDir, getUserDataAccountHubBehaviorsDir, getUserDataAccountHubPerceptionsDir, getUserDataAccountHubPersonasDir, } from './user-data.js'; import { capabilityEntryForHubResource, capabilityWorkspacePath, readCapabilityWorkspaceRegistry, registerDiscoveredCapability, updateCapabilityHubIdentity, writeCapabilityWorkspaceRegistry, } from './capability-workspace.js'; import { inspectClawclawBehaviorSource, behaviorSourceCompatibilityError } from '../runtime/clawclaw/plugins/behavior/behavior-source.js'; import { listClawclawPerceptionSourcesInDirectory } from '../runtime/clawclaw/plugins/perception/perception-source.js'; import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js'; import { isSupportedPerceptionSource } from '../runtime/clawclaw/plugins/perception/perception-source.js'; import { updateGameplayConfig } from './gameplay-config.js'; const RESOURCE_TYPES: readonly ResourceType[] = ['skill', 'strategy', 'persona', 'perception']; const SHA256 = /^[0-9a-f]{64}$/; const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/; export interface LocalAgentWorkspaceFile { relativePath: string; path: string; fileId: string; sha256: string; sizeBytes: number; contentType: string; } export interface LocalAgentWorkspaceItem { workspaceItemId: string; forkedFromResourceId?: string; forkReconciliation?: { parentResourceId: string; parentVersionId?: string; parentOperationName?: string; status: 'linked' | 'unresolved'; reason?: 'multiple_forks' | 'parent_still_equipped' | 'baseline_unrecognized' | 'parent_working_copy_missing' | 'target_working_copy_exists' | 'not_owned' | 'inventory_unavailable'; }; resourceId: string; versionId: string; title?: string; description?: string; versionNumber?: string; versionDescription?: string; resourceType: ResourceType; hub?: { workspaceKind: 'owned' | 'installed'; publisher: 'official' | 'self' | 'community'; ownerId: string; ownerName: string | null; ownerAvatarUrl: string | null; ownerIsOfficial: boolean; }; contentDigest: string; sourceFiles: LocalAgentWorkspaceFile[]; archiveFile?: Omit; workingCopyPath?: string; runtimeEntryPath?: string; skillRootPath?: string; knownVersions?: Array<{ versionId: string; contentDigest: string; sourceSha256: string; }>; resolution?: | 'hub' | 'local_modified' | 'concurrent_difference' | 'known_online_old' | 'local_origin_unrecognized'; localContentDigest?: string; localModifiedAtMs?: number; } export interface LocalAgentWorkspaceSnapshot { metadataVersion?: 1; layoutVersion?: 3; revision: number; syncedAt: string; relativeDir: string; items: Record; } interface CurrentPointer { revision: number; relative_dir: string; } export type AgentWorkspaceSyncStatus = 'updated' | 'unchanged' | 'local_overrides'; export interface AgentWorkspaceSyncResult { status: AgentWorkspaceSyncStatus; snapshot: LocalAgentWorkspaceSnapshot; previous?: LocalAgentWorkspaceSnapshot; forkReplacements?: readonly string[]; } export interface AgentWorkspaceSyncDependencies { client?: AgentWorkspaceConfigReader; download?: (url: string) => Promise; now?: () => Date; workspaceInventory?: readonly WorkspaceResourceSummary[]; } function record(value: unknown): Record | null { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : null; } function safeSegment(value: string, field: string): string { if (!SAFE_SEGMENT.test(value) || value === '.' || value === '..') { throw new Error(`agent_workspace_${field}_invalid`); } return value; } function safeRelativePath(value: string): string { if ( !value || value.includes('\\') || value.startsWith('/') || value.split('/').some((segment) => !segment || segment === '.' || segment === '..') ) throw new Error('agent_workspace_relative_path_invalid'); return value; } function pathInside(root: string, candidate: string): boolean { const child = relative(resolve(root), resolve(candidate)); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } function ensureInside(root: string, candidate: string): string { if (!pathInside(root, candidate)) throw new Error('agent_workspace_path_escape'); return candidate; } function sha256(buffer: Buffer): string { return createHash('sha256').update(buffer).digest('hex'); } function validateRemoteFile(file: AgentWorkspaceRemoteFile, source: boolean): void { if (!SAFE_SEGMENT.test(file.file_id) || !SHA256.test(file.sha256)) { throw new Error('agent_workspace_file_metadata_invalid'); } if (!Number.isSafeInteger(file.size_bytes) || file.size_bytes < 0 || file.size_bytes > 10 * 1024 * 1024) { throw new Error('agent_workspace_file_size_invalid'); } if (typeof file.url !== 'string' || typeof file.content_type !== 'string') { throw new Error('agent_workspace_file_metadata_invalid'); } if (source) safeRelativePath(file.relative_path ?? ''); } function validateRemoteItem(item: AgentWorkspaceRemoteItem, expectedType: ResourceType): void { if (item.resource_type !== expectedType) throw new Error('agent_workspace_resource_type_mismatch'); safeSegment(item.workspace_item_id, 'workspace_item_id'); safeSegment(item.resource_id, 'resource_id'); if (item.forked_from_resource_id != null) safeSegment(item.forked_from_resource_id, 'forked_from_resource_id'); safeSegment(item.version_id, 'version_id'); if ( !['owned', 'installed'].includes(item.workspace_kind) || typeof item.is_created_by_me !== 'boolean' || !record(item.owner) || typeof item.owner.id !== 'string' || !SAFE_SEGMENT.test(item.owner.id) || (item.owner.name !== null && typeof item.owner.name !== 'string') || (item.owner.avatar_url !== null && typeof item.owner.avatar_url !== 'string') || typeof item.owner.is_official !== 'boolean' ) { throw new Error('agent_workspace_owner_metadata_invalid'); } if (!SHA256.test(item.content_digest) || !Array.isArray(item.source_files)) { throw new Error('agent_workspace_item_invalid'); } for (const file of item.source_files) validateRemoteFile(file, true); if (expectedType === 'skill') { if (!item.archive_file) throw new Error('agent_workspace_skill_archive_missing'); validateRemoteFile(item.archive_file, false); } else if (item.archive_file !== undefined) { throw new Error('agent_workspace_archive_unexpected'); } if (expectedType !== 'skill' && item.source_files.length !== 1) { throw new Error(`agent_workspace_${expectedType}_source_count_invalid`); } if (expectedType === 'strategy') { const path = item.source_files[0]?.relative_path ?? ''; if (path.includes('/') || !['.ts', '.js'].includes(extname(path).toLowerCase())) { throw new Error('agent_workspace_strategy_entry_invalid'); } } if (expectedType === 'persona') { const path = item.source_files[0]?.relative_path ?? ''; if (path.includes('/') || extname(path).toLowerCase() !== '.md') { throw new Error('agent_workspace_persona_entry_invalid'); } } if (expectedType === 'perception') { const path = item.source_files[0]?.relative_path ?? ''; if (path.includes('/') || !['.ts', '.js'].includes(extname(path).toLowerCase())) { throw new Error('agent_workspace_perception_entry_invalid'); } } } function validateRemoteConfig(config: AgentWorkspaceRemoteConfig): void { if (!Number.isSafeInteger(config.revision) || config.revision < 0 || !record(config.items)) { throw new Error('agent_workspace_config_invalid'); } for (const type of RESOURCE_TYPES) { const items = config.items[type]; if (!Array.isArray(items)) throw new Error(`agent_workspace_${type}_items_invalid`); for (const item of items) validateRemoteItem(item, type); } if (config.items.persona.length > 1) throw new Error('agent_workspace_persona_multiple'); } function contentDigest(files: readonly LocalAgentWorkspaceFile[]): string { const canonical = [...files] .sort((left, right) => ( left.relativePath < right.relativePath ? -1 : left.relativePath > right.relativePath ? 1 : 0 )) .map((file) => ({ relative_path: file.relativePath, sha256: file.sha256, size_bytes: file.sizeBytes, })); return createHash('sha256').update(JSON.stringify(canonical), 'utf8').digest('hex'); } async function writeVerifiedFile( root: string, relativePath: string, remote: AgentWorkspaceRemoteFile, download: (url: string) => Promise, ): Promise { const bytes = await download(remote.url); if (bytes.length !== remote.size_bytes) throw new Error('agent_workspace_file_size_mismatch'); if (sha256(bytes) !== remote.sha256) throw new Error('agent_workspace_file_hash_mismatch'); const target = ensureInside(root, join(root, ...safeRelativePath(relativePath).split('/'))); mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, bytes); return { relativePath, path: relative(root, target).replaceAll('\\', '/'), fileId: remote.file_id, sha256: remote.sha256, sizeBytes: remote.size_bytes, contentType: remote.content_type, }; } function skillRoot(packageRoot: string): string { if (existsSync(join(packageRoot, 'SKILL.md'))) return packageRoot; const directories = [...new Set( unzipDirectories(packageRoot).filter((directory) => existsSync(join(directory, 'SKILL.md'))), )]; if (directories.length !== 1) throw new Error('agent_workspace_skill_root_invalid'); return directories[0]; } function unzipDirectories(root: string): string[] { const results: string[] = []; const visit = (directory: string): void => { const entries = requireDirectoryEntries(directory); for (const entry of entries) { if (!entry.isDirectory() || entry.name.startsWith('.')) continue; const child = join(directory, entry.name); results.push(child); visit(child); } }; visit(root); return results; } function requireDirectoryEntries(directory: string) { // Kept behind a helper so all recursive traversal stays rooted in the freshly extracted package. return readdirSync(directory, { withFileTypes: true }); } async function materializeItem( stageRoot: string, item: AgentWorkspaceRemoteItem, download: (url: string) => Promise, ): Promise { const itemRoot = join( stageRoot, 'resources', item.resource_type, safeSegment(item.resource_id, 'resource_id'), safeSegment(item.version_id, 'version_id'), ); const sourceRoot = join(itemRoot, 'source'); mkdirSync(sourceRoot, { recursive: true }); const sourceFiles: LocalAgentWorkspaceFile[] = []; for (const source of item.source_files) { sourceFiles.push(await writeVerifiedFile( sourceRoot, source.relative_path!, source, download, )); } if (contentDigest(sourceFiles) !== item.content_digest) { throw new Error('agent_workspace_content_digest_mismatch'); } let archiveFile: LocalAgentWorkspaceItem['archiveFile']; let skillRootPath: string | undefined; if (item.archive_file) { const archive = await writeVerifiedFile(itemRoot, 'package.zip', item.archive_file, download); archiveFile = { path: relative(stageRoot, join(itemRoot, archive.path)).replaceAll('\\', '/'), fileId: archive.fileId, sha256: archive.sha256, sizeBytes: archive.sizeBytes, contentType: archive.contentType, }; const packageRoot = join(itemRoot, 'package'); mkdirSync(packageRoot, { recursive: true }); for (const entry of unzip(readFileSync(join(itemRoot, 'package.zip')))) { const relativePath = safeRelativePath(entry.path); const target = ensureInside(packageRoot, join(packageRoot, ...relativePath.split('/'))); mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, entry.content); } skillRootPath = relative(stageRoot, skillRoot(packageRoot)).replaceAll('\\', '/'); } let runtimeEntryPath: string | undefined; if (item.resource_type === 'strategy' || item.resource_type === 'perception' || item.resource_type === 'persona') { const source = sourceFiles[0]; const extension = extname(source.relativePath).toLowerCase(); const runtimeDir = item.resource_type === 'strategy' ? 'behaviors' : item.resource_type === 'perception' ? 'perceptions' : 'personas'; const runtimePath = join(stageRoot, 'runtime', runtimeDir, `${item.resource_id}${extension}`); mkdirSync(dirname(runtimePath), { recursive: true }); writeFileSync(runtimePath, readFileSync(join(sourceRoot, ...source.path.split('/')))); runtimeEntryPath = relative(stageRoot, runtimePath).replaceAll('\\', '/'); } return { workspaceItemId: item.workspace_item_id, resourceId: item.resource_id, forkedFromResourceId: item.forked_from_resource_id ?? undefined, versionId: item.version_id, title: item.title, description: item.description, versionNumber: item.version_number, versionDescription: item.version_description, resourceType: item.resource_type, hub: { workspaceKind: item.workspace_kind, publisher: item.owner.is_official ? 'official' : item.is_created_by_me ? 'self' : 'community', ownerId: item.owner.id, ownerName: item.owner.name, ownerAvatarUrl: item.owner.avatar_url, ownerIsOfficial: item.owner.is_official, }, contentDigest: item.content_digest, sourceFiles: sourceFiles.map((file) => ({ ...file, path: relative(stageRoot, join(sourceRoot, ...file.path.split('/'))).replaceAll('\\', '/'), })), ...(archiveFile ? { archiveFile } : {}), ...(runtimeEntryPath ? { runtimeEntryPath } : {}), ...(skillRootPath ? { skillRootPath } : {}), }; } function emptyItems(): Record { return { skill: [], strategy: [], persona: [], perception: [] }; } export function localAgentWorkspaceSnapshotRoot( workspaceDir: string, profile: Pick, snapshot: LocalAgentWorkspaceSnapshot, ): string { return join(getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile), snapshot.relativeDir); } export function resolveLocalAgentWorkspacePath( workspaceDir: string, profile: Pick, snapshot: LocalAgentWorkspaceSnapshot, relativePath: string, ): string { const root = localAgentWorkspaceSnapshotRoot(workspaceDir, profile, snapshot); return ensureInside(root, join(root, ...safeRelativePath(relativePath).split('/'))); } interface LocalOverride { bytes: Buffer; sha256: string; contentDigest: string; modifiedAtMs: number; originRecognized: boolean; } interface WorkingCopyMetadata { format: 1; resourceType: 'strategy' | 'persona' | 'perception'; resourceId: string; relativePath: string; knownVersions: NonNullable; forkReconciliation?: LocalAgentWorkspaceItem['forkReconciliation']; } function singleFileContentDigest(relativePath: string, bytes: Buffer): string { return createHash('sha256').update(JSON.stringify([{ relative_path: relativePath, sha256: sha256(bytes), size_bytes: bytes.length, }]), 'utf8').digest('hex'); } function knownVersions(item: LocalAgentWorkspaceItem): NonNullable { const entries = [ ...(item.knownVersions ?? []), ...(item.sourceFiles[0] ? [{ versionId: item.versionId, contentDigest: item.contentDigest, sourceSha256: item.sourceFiles[0].sha256, }] : []), ]; return [...new Map(entries.map((entry) => [entry.versionId, entry])).values()]; } function hubWorkingRoot( workspaceDir: string, profile: Pick, type: 'strategy' | 'persona' | 'perception', ): string { if (type === 'strategy') return getUserDataAccountHubBehaviorsDir(workspaceDir, profile); if (type === 'perception') return getUserDataAccountHubPerceptionsDir(workspaceDir, profile); return getUserDataAccountHubPersonasDir(workspaceDir, profile); } function hubWorkingCopyPath( workspaceDir: string, profile: Pick, type: 'strategy' | 'persona' | 'perception', resourceId: string, relativePath: string, ): string { const root = hubWorkingRoot(workspaceDir, profile, type); return ensureInside( root, join(root, safeSegment(resourceId, 'resource_id'), ...safeRelativePath(relativePath).split('/')), ); } function accountRelativePath( workspaceDir: string, profile: Pick, path: string, ): string { const accountRoot = getUserDataAccountDir(workspaceDir, profile); return relative(accountRoot, ensureInside(accountRoot, path)).replaceAll('\\', '/'); } export function resolveLocalAgentWorkspaceWorkingCopyPath( workspaceDir: string, profile: Pick, item: LocalAgentWorkspaceItem, ): string | undefined { if (!item.workingCopyPath) return undefined; const accountRoot = getUserDataAccountDir(workspaceDir, profile); return ensureInside( accountRoot, join(accountRoot, ...safeRelativePath(item.workingCopyPath).split('/')), ); } function writeFileAtomically(path: string, bytes: Buffer): void { mkdirSync(dirname(path), { recursive: true }); const temporary = `${path}.${randomUUID()}.tmp`; writeFileSync(temporary, bytes); renameSync(temporary, path); } function workingCopyMetadataPath( workspaceDir: string, profile: Pick, type: 'strategy' | 'persona' | 'perception', resourceId: string, ): string { return join( getUserDataAgentWorkspaceDir(workspaceDir, profile), 'working-copies', type, `${safeSegment(resourceId, 'resource_id')}.json`, ); } function readWorkingCopyMetadata( path: string, expected: Pick, ): WorkingCopyMetadata | undefined { if (!existsSync(path)) return undefined; try { const value = JSON.parse(readFileSync(path, 'utf8')) as WorkingCopyMetadata; if ( value.format !== 1 || value.resourceType !== expected.resourceType || value.resourceId !== expected.resourceId || value.relativePath !== expected.relativePath || !Array.isArray(value.knownVersions) || value.knownVersions.some((entry) => ( !entry || typeof entry.versionId !== 'string' || !SHA256.test(entry.contentDigest) || !SHA256.test(entry.sourceSha256) )) ) return undefined; return value; } catch { return undefined; } } function inspectLocalSnapshot( workspaceDir: string, profile: Pick, snapshot: LocalAgentWorkspaceSnapshot, ): { snapshot: LocalAgentWorkspaceSnapshot; overrides: Map; projectionOutdated: boolean; workingMetadataMissing: boolean; } { const resolved = structuredClone(snapshot); const overrides = new Map(); let projectionOutdated = false; let workingMetadataMissing = false; for (const type of ['strategy', 'persona', 'perception'] as const) { for (const item of resolved.items[type]) { const source = item.sourceFiles[0]; if (!source || !item.runtimeEntryPath) continue; const projectionPath = resolveLocalAgentWorkspacePath( workspaceDir, profile, resolved, item.runtimeEntryPath, ); let workingPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, item); if (!workingPath) { workingPath = hubWorkingCopyPath( workspaceDir, profile, type, item.resourceId, source.relativePath, ); item.workingCopyPath = accountRelativePath(workspaceDir, profile, workingPath); if (!existsSync(workingPath)) { const legacyPath = projectionPath; if (existsSync(legacyPath)) writeFileAtomically(workingPath, readFileSync(legacyPath)); } } if (!existsSync(workingPath)) { item.resolution = 'hub'; projectionOutdated = true; continue; } if (!existsSync(workingCopyMetadataPath(workspaceDir, profile, type, item.resourceId))) { workingMetadataMissing = true; } const bytes = readFileSync(workingPath); const localSha = sha256(bytes); const projectionSha = existsSync(projectionPath) ? sha256(readFileSync(projectionPath)) : undefined; item.knownVersions = knownVersions(item); if (localSha === source.sha256) { item.resolution = 'hub'; if (projectionSha !== localSha) projectionOutdated = true; delete item.localContentDigest; delete item.localModifiedAtMs; continue; } if (item.knownVersions.some((entry) => entry.sourceSha256 === localSha)) { item.resolution = 'known_online_old'; const basePath = resolveLocalAgentWorkspacePath( workspaceDir, profile, resolved, source.path, ); if (existsSync(basePath)) { const baseBytes = readFileSync(basePath); writeFileAtomically(workingPath, baseBytes); if (projectionSha !== sha256(baseBytes)) projectionOutdated = true; } delete item.localContentDigest; delete item.localModifiedAtMs; continue; } const localDigest = singleFileContentDigest(source.relativePath, bytes); const modifiedAtMs = statSync(workingPath).mtimeMs; item.resolution = item.resolution === 'local_origin_unrecognized' ? 'local_origin_unrecognized' : item.resolution === 'concurrent_difference' ? 'concurrent_difference' : 'local_modified'; item.localContentDigest = localDigest; item.localModifiedAtMs = modifiedAtMs; if (projectionSha !== localSha) projectionOutdated = true; overrides.set(`${type}:${item.resourceId}`, { bytes, sha256: localSha, contentDigest: localDigest, modifiedAtMs, originRecognized: item.resolution !== 'local_origin_unrecognized', }); } } return { snapshot: resolved, overrides, projectionOutdated, workingMetadataMissing }; } export function resolveLocalAgentWorkspaceSnapshot( workspaceDir: string, profile: Pick, snapshot: LocalAgentWorkspaceSnapshot, ): LocalAgentWorkspaceSnapshot { return inspectLocalSnapshot(workspaceDir, profile, snapshot).snapshot; } export function readLocalAgentWorkspaceSnapshot( workspaceDir: string, profile: Pick, ): LocalAgentWorkspaceSnapshot | undefined { const pointerPath = getUserDataAgentWorkspaceCurrentFile(workspaceDir, profile); if (!existsSync(pointerPath)) return undefined; try { const pointer = JSON.parse(readFileSync(pointerPath, 'utf8')) as CurrentPointer; safeSegment(pointer.relative_dir, 'revision_dir'); const snapshotPath = join( getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile), pointer.relative_dir, 'snapshot.json', ); const snapshot = JSON.parse(readFileSync(snapshotPath, 'utf8')) as LocalAgentWorkspaceSnapshot; if (snapshot.revision !== pointer.revision || snapshot.relativeDir !== pointer.relative_dir) return undefined; return snapshot; } catch { return undefined; } } function writeCurrentPointer( workspaceDir: string, profile: Pick, pointer: CurrentPointer, ): void { const target = getUserDataAgentWorkspaceCurrentFile(workspaceDir, profile); mkdirSync(dirname(target), { recursive: true }); const temporary = `${target}.${randomUUID()}.tmp`; writeFileSync(temporary, `${JSON.stringify(pointer, null, 2)}\n`, 'utf8'); renameSync(temporary, target); } type ForkWorkspaceType = 'behavior' | 'persona' | 'perception'; type ForkParentRetirement = { type: ForkWorkspaceType; resourceId: string; childResourceId: string; path: string; sha256: string; clean: boolean }; function retireReplacedForkParent( workspaceDir: string, profile: Pick, parent: ForkParentRetirement, transferOperationName: boolean, ): void { const entry = capabilityEntryForHubResource(workspaceDir, profile, parent.type, parent.resourceId); if (!entry || !existsSync(parent.path) || sha256(readFileSync(parent.path)) !== parent.sha256) return; const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile); if (registry.entries[entry.key]?.hub?.resourceId !== parent.resourceId) return; const child = Object.values(registry.entries).find(candidate => ( candidate.type === parent.type && candidate.hub?.resourceId === parent.childResourceId )); if (!child) return; // A newly discovered B may inherit A's name. An already named B keeps its // existing name even when A is retired during an upgrade from older CCL. if (transferOperationName && child.declaredId === entry.declaredId && !Object.values(registry.entries).some(candidate => ( candidate.key !== entry.key && candidate.key !== child.key && candidate.type === parent.type && candidate.runtimeId === entry.runtimeId ))) child.runtimeId = entry.runtimeId; const oldOperationName = entry.runtimeId; const newOperationName = child.runtimeId; // Keep unique local edits at A's original path for recovery and the // existing B-targeted conflict flow. A clean copy is redundant. if (parent.clean) rmSync(parent.path, { force: true }); delete registry.entries[entry.key]; writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry); if (oldOperationName !== newOperationName && parent.type !== 'persona') { updateGameplayConfig(config => { if (parent.type === 'behavior') { for (const role of Object.keys(config.fallback_behaviors) as Array) { if (config.fallback_behaviors[role] === oldOperationName) { config.fallback_behaviors[role] = newOperationName; } } config.disabled_behaviors = [...new Set(config.disabled_behaviors.map(id => id === oldOperationName ? newOperationName : id))]; for (const trigger of Object.values(config.triggers)) { if (trigger.behavior === oldOperationName) trigger.behavior = newOperationName; } } else { config.disabled_perception_modules = [...new Set(config.disabled_perception_modules.map(id => id === oldOperationName ? newOperationName : id))]; } }, workspaceDir, profile); } } export async function syncAgentWorkspaceConfig( workspaceDir: string, profile: Pick, dependencies: AgentWorkspaceSyncDependencies = {}, ): Promise { const previousRaw = readLocalAgentWorkspaceSnapshot(workspaceDir, profile); const inspected = previousRaw ? inspectLocalSnapshot(workspaceDir, profile, previousRaw) : undefined; const previous = inspected?.snapshot; const client = dependencies.client ?? new AgentWorkspaceClient(profile); const remote = await client.getConfig(); validateRemoteConfig(remote); if (previous && dependencies.workspaceInventory) { const inventory = dependencies.workspaceInventory; for (const item of Object.values(previous.items).flat()) { const relation = item.forkReconciliation; if (relation?.status !== 'linked' || inventory.some(candidate => candidate.resourceId === relation.parentResourceId) || !inventory.some(candidate => candidate.resourceId === item.resourceId)) continue; const type: ForkWorkspaceType = item.resourceType === 'strategy' ? 'behavior' : item.resourceType as ForkWorkspaceType; if (item.resourceType === 'skill') continue; const parentEntry = capabilityEntryForHubResource(workspaceDir, profile, type, relation.parentResourceId); if (!parentEntry) continue; const path = capabilityWorkspacePath(workspaceDir, profile, parentEntry); if (!existsSync(path)) continue; const digest = sha256(readFileSync(path)); const remoteChild = remote.items[item.resourceType].find(candidate => candidate.resource_id === item.resourceId); const clean = digest === parentEntry.hub?.baseSha256 || digest === remoteChild?.source_files[0]?.sha256; // Older installations may already have a pending A/B conflict. Keep an // unmatched A edit until that existing conflict has been resolved. if (!clean) continue; retireReplacedForkParent(workspaceDir, profile, { type, resourceId: relation.parentResourceId, childResourceId: item.resourceId, path, sha256: digest, clean, }, false); } } const contentUnchanged = previous && RESOURCE_TYPES.every(type => { const items = previous.items[type]; return items.length === remote.items[type].length && remote.items[type].every(item => items.some(old => old.resourceId === item.resource_id && old.versionId === item.version_id && old.workspaceItemId === item.workspace_item_id && old.contentDigest === item.content_digest && old.title === item.title && old.description === item.description && old.forkedFromResourceId === (item.forked_from_resource_id ?? undefined))); }); if ( previous?.revision === remote.revision && contentUnchanged && previous.metadataVersion === 1 && previous.layoutVersion === 3 && inspected?.projectionOutdated !== true && inspected?.workingMetadataMissing !== true ) { return { status: inspected && inspected.overrides.size > 0 ? 'local_overrides' : 'unchanged', snapshot: previous, previous, }; } const revisionsDir = getUserDataAgentWorkspaceRevisionsDir(workspaceDir, profile); mkdirSync(revisionsDir, { recursive: true }); const temporary = join(getUserDataAgentWorkspaceDir(workspaceDir, profile), `.staging-${randomUUID()}`); mkdirSync(temporary, { recursive: true }); try { const items = emptyItems(); const workingUpdates: Array<{ path: string; bytes: Buffer }> = []; const workingMetadataUpdates: Array<{ path: string; value: WorkingCopyMetadata }> = []; const forkReplacements: string[] = []; const forkRegistrations: Array[2]> = []; const replacedForkParents: ForkParentRetirement[] = []; const unresolvedParentKeys = new Set(); const previousByKey = new Map>( RESOURCE_TYPES.map((type) => [ type, new Map((previous?.items[type] ?? []).map((item) => [item.resourceId, item])), ]), ); const selectedResourceIds = new Set(Object.values(remote.items).flat().map(item => item.resource_id)); const forkChildren = new Map>(); const addChild = (parent: string | null | undefined, child: string): void => { if (!parent) return; const children = forkChildren.get(parent) ?? new Set(); children.add(child); forkChildren.set(parent, children); }; for (const item of Object.values(remote.items).flat()) addChild(item.forked_from_resource_id, item.resource_id); for (const item of dependencies.workspaceInventory ?? []) addChild(item.forkedFromResourceId, item.resourceId); for (const type of RESOURCE_TYPES) { for (const item of remote.items[type]) { let materialized: LocalAgentWorkspaceItem; try { materialized = await materializeItem(temporary, item, dependencies.download ?? downloadAgentWorkspaceFile); } catch (error) { 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)}`); } const prior = previousByKey.get(type)?.get(materialized.resourceId); let workingPath: string | undefined; let persistedWorkingMetadata: WorkingCopyMetadata | undefined; let targetAlreadyRegistered = false; let pendingForkConflict = false; if (type !== 'skill' && materialized.sourceFiles[0]) { const workspaceType = type === 'strategy' ? 'behavior' : type; const registered = capabilityEntryForHubResource( workspaceDir, profile, workspaceType, materialized.resourceId, ); targetAlreadyRegistered = registered !== undefined; pendingForkConflict = registered?.hub?.pendingForkConflict === true; workingPath = registered ? capabilityWorkspacePath(workspaceDir, profile, registered) : hubWorkingCopyPath( workspaceDir, profile, type, materialized.resourceId, materialized.sourceFiles[0].relativePath, ); materialized.workingCopyPath = accountRelativePath(workspaceDir, profile, workingPath); persistedWorkingMetadata = readWorkingCopyMetadata( workingCopyMetadataPath(workspaceDir, profile, type, materialized.resourceId), { resourceType: type, resourceId: materialized.resourceId, relativePath: materialized.sourceFiles[0].relativePath, }, ); } materialized.knownVersions = [...new Map([ ...(prior ? knownVersions(prior) : []), ...(persistedWorkingMetadata?.knownVersions ?? []), ...knownVersions(materialized), ].map((entry) => [entry.versionId, entry])).values()]; materialized.forkReconciliation = prior?.forkReconciliation ?? persistedWorkingMetadata?.forkReconciliation; let override = inspected?.overrides.get(`${type}:${materialized.resourceId}`); let forkCloudChanged: boolean | undefined; // Only bridge a newly received, owned, direct replacement. Keep A's // file and operation name intact; B gets a separate working copy/name. const parentId = materialized.forkedFromResourceId; const parent = parentId ? previousByKey.get(type)?.get(parentId) : undefined; if (type !== 'skill' && parent && !prior && !targetAlreadyRegistered && !materialized.forkReconciliation) { if (!dependencies.workspaceInventory) { throw new Error(`agent_workspace_resource_failed:${type}:${item.resource_id}:fork_inventory_unavailable`); } const workspaceType = type === 'strategy' ? 'behavior' : type; const parentEntry = capabilityEntryForHubResource(workspaceDir, profile, workspaceType, parent.resourceId); const relation: NonNullable = { parentResourceId: parent.resourceId, parentVersionId: parent.versionId, parentOperationName: parentEntry?.runtimeId, status: 'unresolved', }; const parentPath = resolveLocalAgentWorkspaceWorkingCopyPath(workspaceDir, profile, parent); const baseline = parent.sourceFiles[0]?.sha256; if (!item.is_created_by_me || item.workspace_kind !== 'owned') relation.reason = 'not_owned'; else if (selectedResourceIds.has(parent.resourceId)) relation.reason = 'parent_still_equipped'; else if (forkChildren.get(parent.resourceId)?.size !== 1) relation.reason = 'multiple_forks'; else if (!baseline || parent.resolution === 'local_origin_unrecognized' || parentEntry?.hub?.localOriginUnrecognized) { relation.reason = 'baseline_unrecognized'; } else if (!parentPath || !existsSync(parentPath)) relation.reason = 'parent_working_copy_missing'; else if (workingPath && existsSync(workingPath)) relation.reason = 'target_working_copy_exists'; else { const bytes = readFileSync(parentPath); const digest = sha256(bytes); relation.status = 'linked'; forkReplacements.push(item.resource_id); const localChanged = digest !== baseline; const childSha256 = materialized.sourceFiles[0]?.sha256; if (!dependencies.workspaceInventory.some(candidate => candidate.resourceId === parent.resourceId)) { replacedForkParents.push({ type: workspaceType, resourceId: parent.resourceId, childResourceId: item.resource_id, path: parentPath, sha256: digest, clean: !localChanged || digest === childSha256 }); } if (localChanged && digest !== childSha256) { override = { bytes, sha256: digest, contentDigest: singleFileContentDigest(materialized.sourceFiles[0]!.relativePath, bytes), modifiedAtMs: statSync(parentPath).mtimeMs, originRecognized: true, }; // A's uncommitted edit must be chosen explicitly before it is // written to the newly owned B, even if B still equals A's base. forkCloudChanged = true; } } materialized.forkReconciliation = relation; if (relation.status === 'unresolved' && parentEntry) unresolvedParentKeys.add(parentEntry.key); } if (!override && !prior && workingPath && existsSync(workingPath)) { const bytes = readFileSync(workingPath); const localSha = sha256(bytes); if (!persistedWorkingMetadata?.knownVersions.some((entry) => entry.sourceSha256 === localSha)) { override = { bytes, sha256: localSha, contentDigest: singleFileContentDigest( materialized.sourceFiles[0]!.relativePath, bytes, ), modifiedAtMs: statSync(workingPath).mtimeMs, originRecognized: persistedWorkingMetadata !== undefined, }; } } let effectiveBytes: Buffer | undefined; if ( override && materialized.runtimeEntryPath && materialized.sourceFiles[0]?.sha256 !== override.sha256 ) { const runtimePath = ensureInside( temporary, join(temporary, ...safeRelativePath(materialized.runtimeEntryPath).split('/')), ); writeFileSync(runtimePath, override.bytes); effectiveBytes = override.bytes; const remoteAdvancedFromLocalBaseline = forkCloudChanged ?? (prior ? prior.versionId !== materialized.versionId : persistedWorkingMetadata !== undefined && !persistedWorkingMetadata.knownVersions.some( (entry) => entry.versionId === materialized.versionId, )); materialized.resolution = !override.originRecognized ? 'local_origin_unrecognized' : remoteAdvancedFromLocalBaseline || prior?.resolution === 'concurrent_difference' || pendingForkConflict ? 'concurrent_difference' : 'local_modified'; materialized.localContentDigest = override.contentDigest; materialized.localModifiedAtMs = override.modifiedAtMs; } else { materialized.resolution = 'hub'; if (materialized.runtimeEntryPath) { effectiveBytes = readFileSync(ensureInside( temporary, join(temporary, ...safeRelativePath(materialized.runtimeEntryPath).split('/')), )); } } // Reject an invalid cloud replacement before touching the working copy // or pointer. Invalid local edits remain visible to load diagnostics. if (prior && materialized.resolution === 'hub' && materialized.runtimeEntryPath) { const path = join(temporary, materialized.runtimeEntryPath); if (type === 'strategy') { const source = inspectClawclawBehaviorSource(path, dirname(path)); if (!source || source.apiVersion !== BEHAVIOR_PLUGIN_API_VERSION || behaviorSourceCompatibilityError(source)) { throw new Error(`agent_workspace_resource_failed:strategy:${item.resource_id}:cloud_module_invalid`); } } else if (type === 'perception') { const source = listClawclawPerceptionSourcesInDirectory(dirname(path)).find(source => source.sourcePath === path); if (!source || !isSupportedPerceptionSource(source)) { throw new Error(`agent_workspace_resource_failed:perception:${item.resource_id}:cloud_module_invalid`); } } } if (materialized.workingCopyPath && effectiveBytes) { const accountRoot = getUserDataAccountDir(workspaceDir, profile); workingUpdates.push({ path: ensureInside( accountRoot, join(accountRoot, ...safeRelativePath(materialized.workingCopyPath).split('/')), ), bytes: effectiveBytes, }); workingMetadataUpdates.push({ path: workingCopyMetadataPath( workspaceDir, profile, type as 'strategy' | 'persona' | 'perception', materialized.resourceId, ), value: { format: 1, resourceType: type as 'strategy' | 'persona' | 'perception', resourceId: materialized.resourceId, relativePath: materialized.sourceFiles[0]!.relativePath, knownVersions: materialized.knownVersions, forkReconciliation: materialized.forkReconciliation, }, }); if (materialized.forkReconciliation?.status === 'linked' && forkReplacements.includes(item.resource_id)) { const workspaceType = type === 'strategy' ? 'behavior' : type as 'persona' | 'perception'; const stagedPath = join(temporary, materialized.runtimeEntryPath!); const source = type === 'strategy' ? inspectClawclawBehaviorSource(stagedPath, dirname(stagedPath)) : type === 'perception' ? listClawclawPerceptionSourcesInDirectory(dirname(stagedPath)) .find(source => source.sourcePath === stagedPath) : undefined; const parentEntry = capabilityEntryForHubResource(workspaceDir, profile, workspaceType, materialized.forkReconciliation.parentResourceId); const runtimeId = source?.id ?? (type === 'persona' ? materialized.sourceFiles[0]!.relativePath.replace(/\.md$/i, '') : parentEntry?.declaredId ?? parentEntry?.runtimeId); if (runtimeId) forkRegistrations.push({ type: workspaceType, path: workingPath!, runtimeId, title: item.title ?? parentEntry?.title ?? source?.id, description: item.description ?? parentEntry?.description ?? source?.description, selectedByHub: true, hub: { resourceId: item.resource_id, versionId: item.version_id, workspaceItemId: item.workspace_item_id, publisher: 'self', baseSha256: materialized.sourceFiles[0]!.sha256, pendingForkConflict: materialized.resolution === 'concurrent_difference' || undefined }, }); } } items[type].push(materialized); } } const relativeDir = `revision-${remote.revision}-${randomUUID()}`; const snapshot: LocalAgentWorkspaceSnapshot = { metadataVersion: 1, layoutVersion: 3, revision: remote.revision, syncedAt: (dependencies.now ?? (() => new Date()))().toISOString(), relativeDir, items, }; writeFileSync(join(temporary, 'snapshot.json'), `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8'); for (const update of workingUpdates) writeFileAtomically(update.path, update.bytes); for (const update of workingMetadataUpdates) { writeFileAtomically(update.path, Buffer.from(`${JSON.stringify(update.value, null, 2)}\n`, 'utf8')); } const target = join(revisionsDir, relativeDir); renameSync(temporary, target); writeCurrentPointer(workspaceDir, profile, { revision: remote.revision, relative_dir: relativeDir }); for (const registration of forkRegistrations) registerDiscoveredCapability(workspaceDir, profile, registration); for (const parent of replacedForkParents) retireReplacedForkParent(workspaceDir, profile, parent, true); for (const key of unresolvedParentKeys) { const parent = Object.values(previous?.items ?? {}).flat().find(item => { const type = item.resourceType === 'strategy' ? 'behavior' : item.resourceType; return capabilityEntryForHubResource(workspaceDir, profile, type, item.resourceId)?.key === key; }); if (!parent) continue; const type = parent.resourceType === 'strategy' ? 'behavior' : parent.resourceType; const entry = capabilityEntryForHubResource(workspaceDir, profile, type, parent.resourceId)!; updateCapabilityHubIdentity(workspaceDir, profile, key, { ...entry.hub!, forkRelationshipUnresolved: true }); } return { status: 'updated', snapshot, ...(previous ? { previous } : {}), ...(forkReplacements.length ? { forkReplacements } : {}) }; } catch (error) { rmSync(temporary, { recursive: true, force: true }); throw error; } }