import { existsSync, readFileSync, readdirSync, realpathSync, statSync, } from 'node:fs'; import { basename, dirname, isAbsolute, join, relative, } from 'node:path'; export type ModuleCapabilityType = 'behavior' | 'perception' | 'trigger'; export type CapabilitySource = 'hub' | 'local'; export type StaticModuleFailureReason = | 'projection_missing' | 'file_unreadable' | 'source_too_large' | 'public_sdk_import_required' | 'default_export_missing' | 'manifest_missing' | 'static_manifest_invalid'; export interface StaticModuleDiagnostic { readonly reason: StaticModuleFailureReason; readonly path: string; readonly file: string; readonly declaredId?: string; readonly declaredName?: string; readonly expectedImport?: string; readonly receivedImports?: readonly string[]; } export interface CapabilityLoadWarning { readonly code: 'CAPABILITY_NOT_LOADED'; readonly capability_type: 'behavior' | 'perception' | 'trigger' | 'persona'; readonly source: CapabilitySource; readonly reason: string; readonly stage: 'projection' | 'static_discovery' | 'selection'; readonly resource_id?: string; readonly version_id?: string; readonly id?: string; readonly name?: string; readonly file?: string; readonly path?: string | null; readonly expected_import?: string; readonly received_imports?: readonly string[]; } const MAX_SOURCE_BYTES = 2 * 1024 * 1024; const MAX_MODULE_FILES = 512; const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*)["']([^"']+)["']/g; const DECLARED_ID = /\bid\s*:\s*["']([^"']+)["']/; const DECLARED_NAME = /\bname\s*:\s*["']([^"']+)["']/; const MODULE_CONTRACTS: Record = { behavior: { expectedImport: '@myclaw163/clawclaw-cli/strategy-plugin', safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/(?:behavior|strategy)-plugin/, defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+Clawclaw(?:Behavior|Strategy)/, manifest: /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/, }, perception: { expectedImport: '@myclaw163/clawclaw-cli/perception-plugin', safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/perception-plugin/, defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(?:ClawclawPerception|ClawclawParallelPerception|ClawclawReminder|ClawclawReaction)/, manifest: /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/, }, trigger: { expectedImport: '@myclaw163/clawclaw-cli/trigger-plugin', safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/trigger-plugin|[./]trigger-plugin(?:\.[cm]?[jt]s)?["']/, defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+ClawclawTrigger/, manifest: /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/, }, }; function pathInside(root: string, candidate: string): boolean { const child = relative(root, candidate); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } export function listCapabilityModuleCandidates(directory: string): readonly string[] { if (!existsSync(directory)) return []; try { const root = realpathSync(directory); return readdirSync(root) .filter((file) => ( !file.startsWith('_') && !file.endsWith('.d.ts') && !file.endsWith('.test.ts') && /\.(?:ts|js)$/.test(file) )) .sort() .slice(0, MAX_MODULE_FILES) .flatMap((file) => { try { const path = realpathSync(join(root, file)); return pathInside(root, path) && dirname(path) === root ? [path] : []; } catch { return []; } }); } catch { return []; } } export function diagnoseRejectedCapabilityModule( type: ModuleCapabilityType, path: string, ): StaticModuleDiagnostic { const contract = MODULE_CONTRACTS[type]; if (!existsSync(path)) { return { reason: 'projection_missing', path, file: basename(path) }; } let source: string; try { if (!statSync(path).isFile()) throw new Error('not_file'); source = readFileSync(path, 'utf8'); } catch { return { reason: 'file_unreadable', path, file: basename(path) }; } const declaredId = DECLARED_ID.exec(source)?.[1]; const declaredName = DECLARED_NAME.exec(source)?.[1]; const common = { path, file: basename(path), ...(declaredId ? { declaredId } : {}), ...(declaredName ? { declaredName } : {}), }; if (Buffer.byteLength(source, 'utf8') > MAX_SOURCE_BYTES) { return { ...common, reason: 'source_too_large' }; } if (!contract.safeImport.test(source)) { const receivedImports = [...source.matchAll(IMPORT_SPECIFIER)].map((match) => match[1]!); return { ...common, reason: 'public_sdk_import_required', expectedImport: contract.expectedImport, ...(receivedImports.length === 0 ? {} : { receivedImports }), }; } if (!contract.defaultClass.test(source)) { return { ...common, reason: 'default_export_missing' }; } if (!contract.manifest.test(source)) { return { ...common, reason: 'manifest_missing' }; } return { ...common, reason: 'static_manifest_invalid' }; } export function warningFromStaticDiagnostic( type: ModuleCapabilityType, source: CapabilitySource, diagnostic: StaticModuleDiagnostic, metadata: { readonly resourceId?: string; readonly versionId?: string } = {}, ): CapabilityLoadWarning { return { code: 'CAPABILITY_NOT_LOADED', capability_type: type, source, reason: diagnostic.reason, stage: diagnostic.reason === 'projection_missing' ? 'projection' : 'static_discovery', ...(metadata.resourceId ? { resource_id: metadata.resourceId } : {}), ...(metadata.versionId ? { version_id: metadata.versionId } : {}), ...(diagnostic.declaredId ? { id: diagnostic.declaredId } : {}), ...(diagnostic.declaredName ? { name: diagnostic.declaredName } : {}), file: diagnostic.file, path: diagnostic.path, ...(diagnostic.expectedImport ? { expected_import: diagnostic.expectedImport } : {}), ...(diagnostic.receivedImports ? { received_imports: diagnostic.receivedImports } : {}), }; }