@williambeto/ai-workflow 2.6.4 → 2.6.7

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/commands/init.ts","../../src/core/install-plan.ts","../../src/core/templates.ts","../../src/core/filesystem.ts","../../src/core/backup.ts","../../src/core/opencode-merge.ts","../../src/core/symlink-layout.ts","../../src/adapters/platforms/claude.ts","../../src/adapters/platforms/codex.ts","../../src/adapters/platforms/antigravity.ts","../../src/cli/commands/doctor.ts","../../src/core/validation/canonical-finalization.ts","../../src/cli/commands/collect-evidence.ts","../../src/core/healing/cli-remediation-executor.ts","../../src/cli/commands/run.ts","../../src/core/healing/runtime-remediation-executor.ts","../../src/cli/commands/execute.ts","../../src/cli/commands/clean.ts","../../src/cli/index.ts"],"sourcesContent":["import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createInstallPlan } from \"../../core/install-plan.js\";\nimport { buildAiWorkflowConfig, getTemplateFiles, isValidProfile } from \"../../core/templates.js\";\nimport { exists, writeFileSafe, readJson } from \"../../core/filesystem.js\";\nimport { createManagedBackup, createManagedPathBackup } from \"../../core/backup.js\";\nimport { mergeOpencodeConfig } from \"../../core/opencode-merge.js\";\nimport { buildSymlinkEntries, isSymlinkTo, setupInternalSymlinks } from \"../../core/symlink-layout.js\";\nimport { ClaudeAdapter, CodexAdapter, AntigravityAdapter } from \"../../adapters/index.js\";\n\nfunction summarize(actions: any[]) {\n const createCount = actions.filter((a) => a.type === \"create\").length;\n const conflictCount = actions.filter((a) => a.type === \"conflict\").length;\n\n return { createCount, conflictCount };\n}\n\nfunction printPlan(actions: any[]) {\n for (const action of actions) {\n console.log(`- ${action.type.padEnd(8)} ${action.relativePath}`);\n }\n}\n\nfunction toIgnoreEntries(linkPath: string): string[] {\n if (linkPath === \"README.workflow.md\") {\n return [linkPath];\n }\n\n const normalized = linkPath.endsWith(\"/\") ? linkPath.slice(0, -1) : linkPath;\n return [normalized, `${normalized}/`];\n}\n\nfunction buildGitignoreBlock(entries: string[]): string {\n const unique = Array.from(new Set(entries));\n const sorted = unique.sort((a, b) => a.localeCompare(b));\n\n return [\n \"# BEGIN AI WORKFLOW KIT\",\n \"# AI Workflow Kit generated files\",\n ...sorted,\n \"# END AI WORKFLOW KIT\"\n ].join(\"\\n\");\n}\n\nasync function upsertGitignoreBlock(cwd: string, entries: string[]): Promise<string> {\n const gitignorePath = path.join(cwd, \".gitignore\");\n const block = buildGitignoreBlock(entries);\n const beginMarker = \"# BEGIN AI WORKFLOW KIT\";\n const endMarker = \"# END AI WORKFLOW KIT\";\n\n const hasGitignore = await exists(gitignorePath);\n if (!hasGitignore) {\n await writeFileSafe(gitignorePath, `${block}\\n`);\n return \"created\";\n }\n\n const current = await fs.readFile(gitignorePath, \"utf8\");\n const beginIndex = current.indexOf(beginMarker);\n const endIndex = current.indexOf(endMarker);\n\n if (beginIndex >= 0 && endIndex > beginIndex) {\n const before = current\n .slice(0, beginIndex)\n .replace(/\\n?# AI Workflow Kit generated files\\n?$/, \"\\n\")\n .replace(/[ \\t]+$/gm, \"\")\n .replace(/\\n*$/, \"\\n\");\n const afterStart = endIndex + endMarker.length;\n const after = current.slice(afterStart).replace(/^\\n*/, \"\\n\");\n const next = `${before}${block}${after}`;\n if (next !== current) {\n await writeFileSafe(gitignorePath, next);\n return \"updated\";\n }\n return \"unchanged\";\n }\n\n const separator = current.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = `${current}${separator}${block}\\n`;\n await writeFileSafe(gitignorePath, next);\n return \"updated\";\n}\n\nasync function injectScripts(cwd: string): Promise<boolean> {\n const pkgPath = path.join(cwd, \"package.json\");\n if (!(await exists(pkgPath))) return false;\n\n try {\n const pkg = await readJson(pkgPath);\n if (!pkg.scripts) pkg.scripts = {};\n\n if (!pkg.scripts.validate) {\n pkg.scripts.validate = \"ai-workflow collect-evidence\";\n await writeFileSafe(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n return true;\n }\n } catch {\n // Ignore invalid package.json\n }\n return false;\n}\n\nexport interface InitOptions {\n cwd: string;\n yes?: boolean;\n force?: boolean;\n dryRun?: boolean;\n noInstall?: boolean;\n noOverwrite?: boolean;\n claude?: boolean;\n codex?: boolean;\n antigravity?: boolean;\n \"dev-mode\"?: boolean;\n profile?: string;\n}\n\nasync function verifySelfExecutionGuard(cwd: string, devMode?: boolean): Promise<void> {\n if (!devMode) {\n try {\n const pkgPath = path.join(cwd, \"package.json\");\n if (await exists(pkgPath)) {\n const pkg = await readJson(pkgPath);\n if (pkg.name === \"@williambeto/ai-workflow\") {\n console.error(\"\\nFATAL: Cannot run 'ai-workflow init' inside its own development repository.\");\n console.error(\"This would corrupt the development environment. Aborting.\");\n console.error(\"Use the --dev-mode flag if you are developing the kit itself and need to test the init command.\\n\");\n process.exit(1);\n }\n }\n } catch {\n // Ignore if package.json is unreadable. The guard is a safety net.\n }\n }\n}\n\nfunction resolveProfile(profile?: string): string {\n const selectedProfile = profile || \"standard\";\n if (!isValidProfile(selectedProfile)) {\n console.error(`Invalid profile: \"${selectedProfile}\". Valid profiles: standard, full`);\n process.exit(1);\n }\n return selectedProfile;\n}\n\nasync function writeInstallFiles(\n cwd: string,\n actions: any[],\n selectedProfile: string,\n force?: boolean,\n noOverwrite?: boolean,\n backupRoot = \".ai-workflow-backups\"\n): Promise<{ skipped: string[]; backups: string[] }> {\n const skipped: string[] = [];\n const backups: string[] = [];\n\n for (const action of actions) {\n if (action.type === \"conflict\" && (noOverwrite || !force)) {\n skipped.push(action.relativePath);\n continue;\n }\n\n if (action.type === \"conflict\" && force) {\n const backupPath = await createManagedBackup(action.absolutePath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n backups.push(backupPath);\n }\n\n const content =\n action.relativePath === \".ai-workflow/config.json\"\n ? `${JSON.stringify(buildAiWorkflowConfig({ profile: selectedProfile }), null, 2)}\\n`\n : action.content;\n\n await writeFileSafe(action.absolutePath, content || \"\");\n }\n\n return { skipped, backups };\n}\n\nasync function writeSymlinks(\n cwd: string,\n linkEntries: any[],\n force?: boolean,\n backupRoot = \".ai-workflow-backups\"\n): Promise<{ linkBackups: string[]; linkCreated: string[] }> {\n const linkBackups: string[] = [];\n const linkCreated: string[] = [];\n\n for (const { linkPath, targetPath } of linkEntries) {\n const absoluteLinkPath = path.join(cwd, linkPath);\n const absoluteTargetPath = path.join(cwd, targetPath);\n\n if (!(await exists(absoluteTargetPath))) {\n throw new Error(`missing link target: ${targetPath}`);\n }\n\n if (await isSymlinkTo(absoluteLinkPath, absoluteTargetPath)) {\n continue;\n }\n\n if (await exists(absoluteLinkPath)) {\n if (!force) {\n throw new Error(\n `cannot create symlink '${linkPath}' because path already exists. Re-run with --force to backup and replace. If symlink creation fails, see troubleshooting in docs/npm-consumer-quickstart.md.`\n );\n }\n const backupPath = await createManagedPathBackup(absoluteLinkPath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n linkBackups.push(backupPath);\n await fs.rm(absoluteLinkPath, { recursive: true, force: true });\n }\n\n const stat = await fs.lstat(absoluteTargetPath);\n const type = process.platform === \"win32\"\n ? (stat.isDirectory() ? \"junction\" : \"file\")\n : (stat.isDirectory() ? \"dir\" : \"file\");\n const linkTarget = process.platform === \"win32\"\n ? absoluteTargetPath\n : path.relative(path.dirname(absoluteLinkPath), absoluteTargetPath);\n\n try {\n await fs.mkdir(path.dirname(absoluteLinkPath), { recursive: true });\n await fs.symlink(linkTarget, absoluteLinkPath, type);\n } catch (error: any) {\n throw new Error(\n `failed to create symlink '${linkPath}' -> '${targetPath}' (${error.message}). ` +\n \"For Windows, enable Developer Mode or run terminal as Administrator. \" +\n \"For Linux/macOS, verify write permissions in project root.\"\n );\n }\n linkCreated.push(linkPath);\n }\n\n return { linkBackups, linkCreated };\n}\n\nasync function executePlatformMigrations(\n cwd: string,\n installRoot: string,\n platforms: string[],\n claude?: boolean,\n codex?: boolean,\n antigravity?: boolean\n): Promise<void> {\n if (platforms.length === 0) return;\n\n console.log(\"ai-workflow: migrating to native platforms...\");\n const agentsDir = path.join(cwd, installRoot, \"opencode/agents\");\n const skillsDir = path.join(cwd, installRoot, \"opencode/skills\");\n\n const agentFiles = (await fs.readdir(agentsDir).catch(() => []))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => path.join(agentsDir, f));\n\n if (claude) {\n const adapter = new ClaudeAdapter({ cwd });\n await adapter.deploy(installRoot);\n console.log(\"- claude: deployed AI Workflow Kit agents to CLAUDE.md and .claude/rules/ (native discovery enabled)\");\n }\n\n if (codex) {\n const adapter = new CodexAdapter({ cwd });\n await adapter.deploy(installRoot);\n console.log(\"- codex: deployed AI Workflow Kit agents to .agents/, .codex/, and .github/ (native discovery enabled)\");\n }\n\n if (antigravity) {\n const adapter = new AntigravityAdapter({ cwd });\n const skillFolders = await fs.readdir(skillsDir).catch(() => []);\n const skillFiles: string[] = [];\n for (const folder of skillFolders) {\n const skillPath = path.join(skillsDir, folder, \"SKILL.md\");\n if (await exists(skillPath)) {\n skillFiles.push(skillPath);\n }\n }\n\n const allFiles = [...agentFiles, ...skillFiles];\n const transformed = await Promise.all(allFiles.map((f) => adapter.transform(f)));\n await adapter.deploy(transformed, installRoot);\n console.log(`- antigravity: deployed AI Workflow Kit agents to .agents/ (native discovery enabled)`);\n }\n}\n\nfunction printInstallationSummary({\n selectedProfile,\n opencodeResult,\n gitignoreResult,\n scriptInjected,\n linkCreated,\n backups,\n linkBackups,\n skipped,\n noInstall\n}: {\n selectedProfile: string;\n opencodeResult: any;\n gitignoreResult: string;\n scriptInjected: boolean;\n linkCreated: string[];\n backups: string[];\n linkBackups: string[];\n skipped: string[];\n noInstall?: boolean;\n}): void {\n console.log(\"Installation complete.\");\n console.log(`- profile: ${selectedProfile}`);\n console.log(`- opencode.jsonc: ${opencodeResult.reason}`);\n console.log(`- .gitignore: ${gitignoreResult}`);\n console.log(`- scripts: ${scriptInjected ? \"injected 'validate'\" : \"already-up-to-date\"}`);\n console.log(`- symlink layout: ${linkCreated.length > 0 ? `created ${linkCreated.length}` : \"already-up-to-date\"}`);\n\n if (backups.length > 0) {\n console.log(`- backups created: ${backups.length}`);\n for (const filePath of backups) {\n console.log(` ${filePath}`);\n }\n }\n if (linkBackups.length > 0) {\n console.log(`- symlink backups created: ${linkBackups.length}`);\n for (const filePath of linkBackups) {\n console.log(` ${filePath}`);\n }\n }\n if (skipped.length > 0) {\n console.log(`- conflicts skipped: ${skipped.length}`);\n for (const relativePath of skipped) {\n console.log(` ${relativePath}`);\n }\n }\n console.log(`- dependency install: ${noInstall ? \"skipped (--no-install)\" : \"not managed in this step\"}`);\n console.log(\"Next steps:\");\n console.log(\" npx @williambeto/ai-workflow doctor\");\n}\n\nexport async function runInit({\n cwd, yes, force, dryRun, noInstall, noOverwrite, claude, codex, antigravity, \"dev-mode\": devMode, profile\n}: InitOptions): Promise<void> {\n await verifySelfExecutionGuard(cwd, devMode);\n\n const selectedProfile = resolveProfile(profile);\n const installRoot = \".ai-workflow\";\n const backupRoot = \".ai-workflow-backups\";\n\n const platforms: string[] = [];\n if (claude) platforms.push(\"claude\");\n if (codex) platforms.push(\"codex\");\n if (antigravity) platforms.push(\"antigravity\");\n\n console.log(`ai-workflow: initializing in ${cwd}`);\n console.log(`Profile: ${selectedProfile}`);\n if (platforms.length > 0) {\n console.log(`Platforms: ${platforms.join(\", \")}`);\n }\n\n const actions = await createInstallPlan({ cwd, exists, profile: selectedProfile });\n const linkEntries = buildSymlinkEntries({ templateFiles: getTemplateFiles(selectedProfile), installRoot });\n const { createCount, conflictCount } = summarize(actions);\n\n console.log(`Plan: ${createCount} create, ${conflictCount} conflict`);\n printPlan(actions);\n\n if (!yes && conflictCount > 0 && !force && !noOverwrite) {\n throw new Error(\n \"conflicts detected. Re-run with --force to replace managed files or resolve conflicts manually\"\n );\n }\n\n if (dryRun) {\n console.log(\"Dry-run enabled. No files were written.\");\n if (platforms.length > 0) {\n console.log(\"ai-workflow: (dry-run) platform migration would be executed after file writing.\");\n }\n return;\n }\n\n const { skipped, backups } = await writeInstallFiles(cwd, actions, selectedProfile, force, noOverwrite, backupRoot);\n const { linkBackups, linkCreated } = await writeSymlinks(cwd, linkEntries, force, backupRoot);\n\n await setupInternalSymlinks(cwd, installRoot);\n\n const opencodeResult = await mergeOpencodeConfig(cwd, { force, backupRoot });\n\n const generatedIgnoreEntries = [\n \"node_modules/\",\n \".ai-workflow/\",\n \".ai-workflow-backups/\",\n \"opencode.jsonc.backup.*\",\n \"EVIDENCE.json\",\n \"*.tgz\",\n ...linkEntries.flatMap((entry) => toIgnoreEntries(entry.linkPath))\n ];\n\n if (codex) {\n generatedIgnoreEntries.push(\".agents/\", \".codex/\");\n }\n if (claude) {\n generatedIgnoreEntries.push(\".claude/\");\n }\n if (antigravity) {\n generatedIgnoreEntries.push(\".agents/\");\n }\n\n const gitignoreResult = await upsertGitignoreBlock(cwd, generatedIgnoreEntries);\n const scriptInjected = await injectScripts(cwd);\n\n await executePlatformMigrations(cwd, installRoot, platforms, claude, codex, antigravity);\n\n printInstallationSummary({\n selectedProfile,\n opencodeResult,\n gitignoreResult,\n scriptInjected,\n linkCreated,\n backups,\n linkBackups,\n skipped,\n noInstall\n });\n}\n","import path from \"node:path\";\nimport { getTemplateFiles } from \"./templates.js\";\n\nexport interface InstallAction {\n type: \"conflict\" | \"create\";\n relativePath: string;\n absolutePath: string;\n content: string | null;\n}\n\nexport interface CreateInstallPlanOptions {\n cwd: string;\n exists: (filePath: string) => Promise<boolean> | boolean;\n profile?: string;\n}\n\nexport async function createInstallPlan({\n cwd,\n exists,\n profile = \"standard\"\n}: CreateInstallPlanOptions): Promise<InstallAction[]> {\n const actions: InstallAction[] = [];\n const templateFiles = getTemplateFiles(profile);\n const installRoot = \".ai-workflow\";\n\n for (const [relativePath, content] of Object.entries(templateFiles)) {\n if (relativePath === \"opencode.jsonc\") {\n continue;\n }\n\n const installedRelativePath = path.join(installRoot, relativePath);\n const absolutePath = path.join(cwd, installedRelativePath);\n const action = (await exists(absolutePath)) ? \"conflict\" : \"create\";\n actions.push({\n type: action,\n relativePath: installedRelativePath,\n absolutePath,\n content\n });\n }\n\n const configPath = path.join(cwd, \".ai-workflow/config.json\");\n actions.push({\n type: (await exists(configPath)) ? \"conflict\" : \"create\",\n relativePath: \".ai-workflow/config.json\",\n absolutePath: configPath,\n content: null\n });\n\n return actions;\n}\n","import { getFullAgentContent, getFullSkillFiles, discoverPackageFiles, readPackageFile, getPackageVersion } from \"./package-assets.js\";\nimport { getCanonicalAgentName } from \"./identity.js\";\n\nconst COMMON_FILES: Record<string, string> = {\n \"opencode/README.md\": `# OpenCode Setup\\n\\nThis directory is managed by \\`ai-workflow\\` init.\\nAdd agent and command files required by your project workflow.\\n`\n};\n\nconst FULL_PRIMARY_AGENTS: string[] = [\n \"atlas\",\n \"nexus\",\n \"orion\",\n \"astra\",\n \"sage\",\n \"phoenix\"\n];\n\nconst FULL_SKILLS: string[] = [\n \"project-memory\",\n \"optimize-tokens\",\n \"documentation\",\n \"architecture\",\n \"technical-leadership\",\n \"product-discovery\",\n \"product-planning\",\n \"spec-driven-development\",\n \"pr-workflow\",\n \"qa-workflow\",\n \"release-workflow\",\n \"deployment\",\n \"ui-ux-design\",\n \"design-principles\",\n \"frontend-development\",\n \"backend-development\",\n \"full-stack-development\",\n \"refactoring\",\n \"prompt-engineer\"\n];\n\nfunction buildRuntimeFiles({ includeFormalEvidence = false }: { includeFormalEvidence?: boolean } = {}): Record<string, string> {\n const files: Record<string, string> = {};\n\n for (const agent of FULL_PRIMARY_AGENTS) {\n const content = getFullAgentContent(agent);\n if (content === null) {\n throw new Error(`CRITICAL FAILURE: Missing required agent asset: dist-assets/agents/${agent}.md`);\n }\n files[`opencode/agents/${agent}.md`] = content;\n }\n\n for (const skill of FULL_SKILLS) {\n const skillFiles = getFullSkillFiles(skill);\n if (Object.keys(skillFiles).length === 0) {\n continue;\n }\n for (const [relPath, content] of Object.entries(skillFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n }\n\n // Copy governance policy into opencode/docs/policies/ so the relative link\n // ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md resolves correctly from\n // opencode/skills/{skill}/SKILL.md for OpenCode and all platform adapters.\n const opencodeGovernancePolicy = readPackageFile(\"dist-assets/docs/policies/SKILLS_COMMON_GOVERNANCE.md\");\n if (opencodeGovernancePolicy !== null) {\n files[\"opencode/docs/policies/SKILLS_COMMON_GOVERNANCE.md\"] = opencodeGovernancePolicy;\n }\n\n const commandFiles = discoverPackageFiles(\"dist-assets/commands\");\n for (const [relPath, content] of Object.entries(commandFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n\n const opencodeSkillFiles = discoverPackageFiles(\"dist-assets/skills\");\n for (const [relPath, content] of Object.entries(opencodeSkillFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n\n const harnessWorkflowFiles = discoverPackageFiles(\"dist-assets/harness/workflows\");\n for (const [relPath, content] of Object.entries(harnessWorkflowFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const harnessHandoffFiles = discoverPackageFiles(\"dist-assets/harness/handoffs\");\n for (const [relPath, content] of Object.entries(harnessHandoffFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const agentsContent = readPackageFile(\"dist-assets/AGENTS.md\");\n if (agentsContent !== null) files[\"AGENTS.md\"] = agentsContent;\n\n const consumerQuickstart = readPackageFile(\"dist-assets/docs/QUICKSTART.md\");\n if (consumerQuickstart !== null) files[\"QUICKSTART.md\"] = consumerQuickstart;\n\n const policyContent = readPackageFile(\"dist-assets/docs/architecture-policy.md\");\n if (policyContent !== null) files[\"opencode/docs/architecture-policy.md\"] = policyContent;\n\n const dpContent = readPackageFile(\"dist-assets/docs/design-patterns-policy.md\");\n if (dpContent !== null) files[\"opencode/docs/design-patterns-policy.md\"] = dpContent;\n\n const visualValidationGuide = readPackageFile(\"dist-assets/docs/visual-validation-guide.md\");\n if (visualValidationGuide !== null) files[\"opencode/docs/visual-validation-guide.md\"] = visualValidationGuide;\n\n const governancePolicies = discoverPackageFiles(\"dist-assets/docs/policies\");\n for (const [relPath, content] of Object.entries(governancePolicies)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const compatibilityDocs = discoverPackageFiles(\"dist-assets/docs/compatibility\");\n for (const [relPath, content] of Object.entries(compatibilityDocs)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const qualityReferenceFiles = discoverPackageFiles(\"dist-assets/docs/references\");\n for (const [relPath, content] of Object.entries(qualityReferenceFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const workflowProfileFiles = discoverPackageFiles(\"dist-assets/docs/profiles\");\n for (const [relPath, content] of Object.entries(workflowProfileFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const templateFiles = discoverPackageFiles(\"dist-assets/templates\");\n for (const [relPath, content] of Object.entries(templateFiles)) {\n if (!includeFormalEvidence && relPath.includes(\"/owner-evidence/\")) continue;\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const schemaFiles = discoverPackageFiles(\"dist-assets/schemas\");\n for (const [relPath, content] of Object.entries(schemaFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n return files;\n}\n\nfunction buildExtraFiles(): Record<string, string> {\n const files: Record<string, string> = {};\n const exampleFiles = discoverPackageFiles(\"dist-assets/examples\");\n for (const [relPath, content] of Object.entries(exampleFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n return files;\n}\n\nconst STANDARD_FILES = buildRuntimeFiles();\nconst FULL_FILES = { ...buildRuntimeFiles({ includeFormalEvidence: true }), ...buildExtraFiles() };\n\nexport const PROFILE_FILES: Record<string, Record<string, string>> = {\n standard: {\n ...COMMON_FILES,\n ...STANDARD_FILES\n },\n full: {\n ...COMMON_FILES,\n ...FULL_FILES\n }\n};\n\nexport function isValidProfile(profile: any): boolean {\n return profile === \"standard\" || profile === \"full\";\n}\n\nexport function getTemplateFiles(profile: string = \"standard\"): Record<string, string> {\n return PROFILE_FILES[profile] ?? PROFILE_FILES.standard;\n}\n\nexport function getManagedBlocks(): string[] {\n return [\n ...FULL_PRIMARY_AGENTS.map((agent) => `opencode.jsonc:agent.${getCanonicalAgentName(agent)}`),\n ...FULL_SKILLS.map((skill) => `opencode.jsonc:agent.${getCanonicalAgentName(skill)}`),\n \"opencode.jsonc:command.atlas\",\n \"opencode.jsonc:command.run\",\n \"opencode.jsonc:command.discover\",\n \"opencode.jsonc:command.spec-create\",\n \"opencode.jsonc:command.spec-review\",\n \"opencode.jsonc:command.spec-implement\",\n \"opencode.jsonc:command.plan\",\n \"opencode.jsonc:command.implement\",\n \"opencode.jsonc:command.validate\",\n \"opencode.jsonc:command.audit\",\n \"opencode.jsonc:command.optimize-tokens\",\n \"opencode.jsonc:command.update-memory\",\n \"opencode.jsonc:command.release\",\n \"opencode.jsonc:command.deploy\"\n ];\n}\n\nexport interface BuildAiWorkflowConfigOptions {\n profile: string;\n managedFiles?: any;\n managedLinks?: any[];\n}\n\nexport interface AiWorkflowConfig {\n package: string;\n version: string | null;\n runtime: string;\n profile: string;\n installMode: string;\n generatedAt: string;\n paths: {\n agents: string;\n commands: string;\n skills: string;\n policies: string;\n harness: string;\n schemas: string;\n };\n}\n\nexport function buildAiWorkflowConfig({ profile }: BuildAiWorkflowConfigOptions): AiWorkflowConfig {\n const version = getPackageVersion();\n const now = new Date().toISOString();\n\n return {\n package: \"@williambeto/ai-workflow\",\n version,\n runtime: \"opencode\",\n profile,\n installMode: \"project-local\",\n generatedAt: now,\n paths: {\n agents: \".ai-workflow/opencode/agents\",\n commands: \".ai-workflow/opencode/commands\",\n skills: \".ai-workflow/opencode/skills\",\n policies: \".ai-workflow/opencode/docs/policies\",\n harness: \".ai-workflow/harness\",\n schemas: \".ai-workflow/schemas\"\n }\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function exists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nimport { execSync } from \"node:child_process\";\n\n/**\n * Safe wrapper for writing files that enforces branch guards on protected branches.\n * NOTE: This branch guard only protects write operations performed through this kit wrapper\n * (or the kit's runtime executions). It does not intercept external shell commands or processes.\n */\nexport async function writeFileSafe(filePath: string, content: string): Promise<void> {\n const absolutePath = path.resolve(filePath);\n const repoCwd = path.resolve(process.cwd());\n const relativeToRepo = path.relative(repoCwd, absolutePath).replaceAll(\"\\\\\", \"/\");\n \n // Normalized precise allowlist\n const isOperational = relativeToRepo === \"EVIDENCE.json\" ||\n relativeToRepo.startsWith(\".ai-workflow/\") ||\n relativeToRepo.startsWith(\".ai-workflow\\\\\");\n \n if (!isOperational) {\n let currentBranch = \"\";\n const fileCwd = path.dirname(absolutePath);\n try {\n currentBranch = execSync(\"git branch --show-current\", { cwd: fileCwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n // ignore\n }\n const protectedBranches = [\"main\", \"master\"];\n const isInitCommand = process.argv.includes(\"init\");\n if (protectedBranches.includes(currentBranch) && !isInitCommand) {\n if (process.env.AI_WORKFLOW_BYPASS_PROTECTED_BRANCH !== \"true\") {\n throw new Error(\"FAIL_PROTECTED_BRANCH: Direct writes to protected branch are prohibited.\");\n }\n }\n }\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf8\");\n}\n\nexport async function readJson(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(content);\n}\n\nfunction stripJsonComments(content: string): string {\n let output = \"\";\n let inString = false;\n let quote = \"\";\n let escaped = false;\n let inLineComment = false;\n let inBlockComment = false;\n\n for (let index = 0; index < content.length; index += 1) {\n const char = content[index];\n const next = content[index + 1];\n\n if (inLineComment) {\n if (char === \"\\n\" || char === \"\\r\") {\n inLineComment = false;\n output += char;\n }\n continue;\n }\n\n if (inBlockComment) {\n if (char === \"*\" && next === \"/\") {\n inBlockComment = false;\n index += 1;\n continue;\n }\n if (char === \"\\n\" || char === \"\\r\") {\n output += char;\n }\n continue;\n }\n\n if (inString) {\n output += char;\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === quote) {\n inString = false;\n quote = \"\";\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n quote = char;\n output += char;\n continue;\n }\n\n if (char === \"/\" && next === \"/\") {\n inLineComment = true;\n index += 1;\n continue;\n }\n\n if (char === \"/\" && next === \"*\") {\n inBlockComment = true;\n index += 1;\n continue;\n }\n\n output += char;\n }\n\n return output;\n}\n\nfunction stripTrailingCommas(content: string): string {\n let output = \"\";\n let inString = false;\n let quote = \"\";\n let escaped = false;\n\n for (let index = 0; index < content.length; index += 1) {\n const char = content[index];\n\n if (inString) {\n output += char;\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === quote) {\n inString = false;\n quote = \"\";\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n quote = char;\n output += char;\n continue;\n }\n\n if (char === \",\") {\n let nextIndex = index + 1;\n while (/\\s/.test(content[nextIndex] ?? \"\")) {\n nextIndex += 1;\n }\n if (content[nextIndex] === \"}\" || content[nextIndex] === \"]\") {\n continue;\n }\n }\n\n output += char;\n }\n\n return output;\n}\n\nexport async function readJsonc(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(stripTrailingCommas(stripJsonComments(content)));\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { BackupOptions } from \"./types.js\";\n\nexport function buildBackupPath(filePath: string, now: Date = new Date()): string {\n const stamp = now.toISOString().replace(/[:.]/g, \"-\");\n return `${filePath}.bak.${stamp}`;\n}\n\nexport async function createBackup(filePath: string): Promise<string> {\n const backupPath = buildBackupPath(filePath);\n await fs.copyFile(filePath, backupPath);\n return backupPath;\n}\n\nfunction escapeRelativePath(relativePath: string): string {\n return relativePath.replace(/[\\\\/]/g, \"__\");\n}\n\nexport async function createManagedBackup(\n filePath: string,\n { cwd, backupRoot, maxPerFile = 20 }: BackupOptions\n): Promise<string> {\n const relativePath = path.relative(cwd, filePath);\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const backupName = `${escapeRelativePath(relativePath)}.${stamp}.bak`;\n const absoluteBackupRoot = path.join(cwd, backupRoot);\n const backupPath = path.join(absoluteBackupRoot, backupName);\n\n await fs.mkdir(absoluteBackupRoot, { recursive: true });\n await fs.copyFile(filePath, backupPath);\n\n const prefix = `${escapeRelativePath(relativePath)}.`;\n const entries = await fs.readdir(absoluteBackupRoot);\n const matching = entries\n .filter((entry) => entry.startsWith(prefix) && entry.endsWith(\".bak\"))\n .sort();\n\n if (matching.length > maxPerFile) {\n const excess = matching.slice(0, matching.length - maxPerFile);\n await Promise.all(excess.map((entry) => fs.unlink(path.join(absoluteBackupRoot, entry))));\n }\n\n return backupPath;\n}\n\nexport async function createManagedPathBackup(\n targetPath: string,\n { cwd, backupRoot, maxPerFile = 20 }: BackupOptions\n): Promise<string> {\n const relativePath = path.relative(cwd, targetPath);\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const backupName = `${escapeRelativePath(relativePath)}.${stamp}.bak`;\n const absoluteBackupRoot = path.join(cwd, backupRoot);\n const backupPath = path.join(absoluteBackupRoot, backupName);\n\n await fs.mkdir(absoluteBackupRoot, { recursive: true });\n await fs.rename(targetPath, backupPath);\n\n const prefix = `${escapeRelativePath(relativePath)}.`;\n const entries = await fs.readdir(absoluteBackupRoot);\n const matching = entries\n .filter((entry) => entry.startsWith(prefix) && entry.endsWith(\".bak\"))\n .sort();\n\n if (matching.length > maxPerFile) {\n const excess = matching.slice(0, matching.length - maxPerFile);\n await Promise.all(excess.map((entry) => fs.rm(path.join(absoluteBackupRoot, entry), { recursive: true, force: true })));\n }\n\n return backupPath;\n}\n","import path from \"node:path\";\nimport { exists, readJsonc, writeFileSafe } from \"./filesystem.js\";\nimport { createManagedBackup } from \"./backup.js\";\nimport { getTemplateFiles } from \"./templates.js\";\n\n/**\n * @file opencode-merge.ts\n * @description Architecture & Registry for OpenCode configuration synthesis (`opencode.jsonc`).\n *\n * ## Architecture Overview\n * This module is responsible for initializing, updating, and merging the project's\n * `opencode.jsonc` file when `aw init` is executed in a consumer repository.\n *\n * ### Core Responsibilities:\n * 1. **Primary Agents Registry (`AGENTS`)**: Defines the 6 core workflow actors (Atlas, Nexus, Orion, Astra, Sage, Phoenix)\n * and maps their instructions to `.ai-workflow/agents/<name>.md`.\n * 2. **Subagents Registry (`SUBAGENTS`)**: Registers domain-specific subagents mapped 1-to-1 with skills installed\n * in `.ai-workflow/skills/<skill>/SKILL.md`. These subagents can be activated by OpenCode runtimes.\n * 3. **Commands Registry (`COMMANDS`)**: Maps slash-commands (e.g. `/atlas`, `/spec-create`, `/validate`) to their respective agent owners.\n * 4. **Safe JSONC Merging**: Merges AIWK configuration blocks into consumer repositories while preserving existing custom user\n * settings in `opencode.jsonc` and managing backups.\n *\n * ### Registering a New Subagent:\n * To add a new subagent to the OpenCode runtime registry:\n * - Ensure a corresponding skill exists in `dist-assets/skills/<skill-name>/SKILL.md`.\n * - Add a new entry to the `SUBAGENTS` object with a PascalCase/Kebab name, a concise `description`, and the matching `skill` directory name.\n * - Note: 5 auxiliary skills (`cyber-security`, `database`, `devops`, `localization`, `performance`) are intentionally excluded\n * from subagent registration as they serve as contextual lenses for existing agents (see `dist-assets/AGENTS.md`).\n */\n\nconst LEGACY_MARKER = \"_aiWorkflowManaged\";\n\ninterface AgentDef {\n description: string;\n}\n\nconst AGENTS: Record<string, AgentDef> = {\n Atlas: { description: \"Router and workflow coordinator for AI Workflow Kit\" },\n Nexus: { description: \"Discovery, requirement, scope, and specification owner\" },\n Orion: { description: \"Planning, PR sequencing, release, and deployment strategy owner\" },\n Astra: { description: \"Implementation owner for incremental, scoped changes\" },\n Sage: { description: \"Audit, validation, evidence, and quality gate owner\" },\n Phoenix: { description: \"Remediation and regression recovery owner\" }\n};\n\ninterface SubagentDef {\n description: string;\n skill: string;\n}\n\nconst SUBAGENTS: Record<string, SubagentDef> = {\n \"Architecture-Specialist\": { description: \"Select the simplest architecture that safely satisfies current requirements\", skill: \"architecture\" },\n \"Backend-Engineer\": { description: \"Support safe PHP/Node/Python backend changes for APIs and persistence\", skill: \"backend-development\" },\n \"Deployment-Specialist\": { description: \"Plan, review, or validate deployment, release, and production-readiness\", skill: \"deployment\" },\n \"Design-Specialist\": { description: \"Apply practical design principles to keep solutions simple and maintainable\", skill: \"design-principles\" },\n \"Docs-Engineer\": { description: \"Write or improve project documentation, READMEs, guides, and prompts\", skill: \"documentation\" },\n \"Frontend-Engineer\": { description: \"Implement or review frontend changes involving UI, state, routing, and accessibility\", skill: \"frontend-development\" },\n \"Frontend-Design-System-Specialist\": { description: \"Enforce CSS/HTML tokens, semantic elements, typography, and premium atmosphere constraints for frontend quality\", skill: \"frontend-design-system\" },\n \"Full-Stack-Engineer\": { description: \"Coordinate frontend and backend changes as one coherent, testable increment\", skill: \"full-stack-development\" },\n \"Token-Economist\": { description: \"Reduce context size while preserving information required for safe execution\", skill: \"optimize-tokens\" },\n \"PR-Manager\": { description: \"Plan, implement, review, or validate small pull requests while preserving scope\", skill: \"pr-workflow\" },\n \"Discovery-Analyst\": { description: \"Clarify ambiguous requests into actionable problem statements and success outcomes\", skill: \"product-discovery\" },\n \"Product-Planner\": { description: \"Turn clarified needs into scoped requirements with acceptance-ready outcomes\", skill: \"product-planning\" },\n \"Memory-Guardian\": { description: \"Manage discoverable project memory for durable decisions and recurring corrections\", skill: \"project-memory\" },\n \"Prompt-Engineer\": { description: \"Expert in creating and refining prompts for AI agents and workflows\", skill: \"prompt-engineer\" },\n \"QA-Engineer\": { description: \"Design, review, or improve tests, acceptance criteria, and validation evidence\", skill: \"qa-workflow\" },\n \"Refactoring-Specialist\": { description: \"Improve code/document structure safely while preserving behavior\", skill: \"refactoring\" },\n \"Release-Specialist\": { description: \"Prepare release readiness decisions with explicit gates and evidence\", skill: \"release-workflow\" },\n \"SDD-Specialist\": { description: \"Convert approved requirements into explicit, testable specification artifacts\", skill: \"spec-driven-development\" },\n \"Technical-Leader\": { description: \"Make technical decisions, review architecture, and identify trade-offs\", skill: \"technical-leadership\" },\n \"UI-UX-Engineer\": { description: \"Improve usability and interface clarity without introducing unnecessary complexity\", skill: \"ui-ux-design\" }\n};\n\ninterface CommandDef {\n description: string;\n agent: string;\n}\n\nconst COMMANDS: Record<string, CommandDef> = {\n atlas: { description: \"Decide safest next step and delegate to the appropriate workflow or agent\", agent: \"Atlas\" },\n run: { description: \"Execute the master orchestration pipeline (Gates, SDD, Implementation, Validation, Healing)\", agent: \"Atlas\" },\n discover: { description: \"Understand the project, gather context, and create initial documentation\", agent: \"Nexus\" },\n \"spec-create\": { description: \"Create a clear specification before implementation\", agent: \"Nexus\" },\n \"spec-review\": { description: \"Review a specification and validate scope, risks, criteria, and gaps\", agent: \"Nexus\" },\n \"spec-implement\": { description: \"Implement an approved specification incrementally\", agent: \"Astra\" },\n plan: { description: \"Plan a task or change, defining steps, risks, and validation\", agent: \"Orion\" },\n implement: { description: \"Implement a small task with defined scope\", agent: \"Astra\" },\n validate: { description: \"Run project validations and collect evidence\", agent: \"Sage\" },\n audit: { description: \"Audit the project, identify issues, and suggest prioritized improvements\", agent: \"Sage\" },\n \"optimize-tokens\": { description: \"Analyze workflow and context usage; suggest reductions without losing quality or evidence\", agent: \"Sage\" },\n \"update-memory\": { description: \"Update durable project memory with relevant decisions, constraints, and reusable context\", agent: \"Nexus\" },\n release: { description: \"Prepare delivery with commit, push, PR/merge readiness, changelog, and evidence\", agent: \"Orion\" },\n deploy: { description: \"Publish the project to the defined environment after validation and release readiness\", agent: \"Orion\" }\n};\n\ninterface ManagedAgentConfig {\n mode: \"primary\" | \"subagent\";\n description: string;\n prompt: string;\n}\n\ninterface ManagedCommandConfig {\n description: string;\n agent: string;\n template: string;\n}\n\ninterface ManagedConfig {\n $schema: string;\n default_agent: string;\n agent: Record<string, ManagedAgentConfig>;\n skills: {\n paths: string[];\n };\n command: Record<string, ManagedCommandConfig>;\n mcp?: Record<string, any>;\n}\n\nfunction buildManagedConfig(): ManagedConfig {\n const agent: Record<string, ManagedAgentConfig> = {};\n for (const [name, def] of Object.entries(AGENTS)) {\n agent[name] = {\n mode: \"primary\",\n description: def.description,\n prompt: `{file:./.ai-workflow/opencode/agents/${name.toLowerCase()}.md}`\n };\n }\n\n for (const [name, def] of Object.entries(SUBAGENTS)) {\n agent[name] = {\n mode: \"subagent\",\n description: def.description,\n prompt: `{file:./.ai-workflow/opencode/skills/${def.skill}/SKILL.md}`\n };\n }\n\n const command: Record<string, ManagedCommandConfig> = {};\n for (const [name, def] of Object.entries(COMMANDS)) {\n command[name] = {\n description: def.description,\n agent: def.agent,\n template: `{file:./.ai-workflow/opencode/commands/${name}.md}`\n };\n }\n\n return {\n $schema: \"https://opencode.ai/config.json\",\n default_agent: \"Atlas\",\n agent,\n skills: {\n paths: [\"./.ai-workflow/opencode/skills\"]\n },\n command\n };\n}\n\nexport interface MergeOpencodeConfigOptions {\n force?: boolean;\n backupRoot?: string;\n}\n\nexport interface MergeOpencodeConfigResult {\n changed: boolean;\n reason: string;\n}\n\nexport async function mergeOpencodeConfig(\n cwd: string,\n { force = false, backupRoot = \".ai-workflow-backups\" }: MergeOpencodeConfigOptions = {}\n): Promise<MergeOpencodeConfigResult> {\n const targetPath = path.join(cwd, \"opencode.jsonc\");\n const managed = buildManagedConfig();\n\n if (!(await exists(targetPath))) {\n await writeFileSafe(targetPath, `${JSON.stringify(managed, null, 2)}\\n`);\n return { changed: true, reason: \"created\" };\n }\n\n let current: any;\n try {\n current = await readJsonc(targetPath);\n } catch {\n if (!force) {\n return { changed: false, reason: \"invalid-json (skipped)\" };\n }\n await createManagedBackup(targetPath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n await writeFileSafe(targetPath, `${JSON.stringify(managed, null, 2)}\\n`);\n return { changed: true, reason: \"invalid-json (replaced with --force)\" };\n }\n\n const { [LEGACY_MARKER]: _legacyManaged, ...currentWithoutLegacy } = current;\n\n const next = {\n ...currentWithoutLegacy,\n $schema: current.$schema ?? managed.$schema,\n ...(managed.mcp\n ? {\n mcp: {\n ...(current.mcp ?? {}),\n ...managed.mcp\n }\n }\n : {}),\n agent: {\n ...(current.agent ?? {}),\n ...managed.agent\n },\n command: {\n ...(current.command ?? {}),\n ...managed.command\n }\n };\n\n const changed = JSON.stringify(current) !== JSON.stringify(next);\n if (!changed) {\n return { changed: false, reason: \"already-up-to-date\" };\n }\n\n await writeFileSafe(targetPath, `${JSON.stringify(next, null, 2)}\\n`);\n return { changed: true, reason: \"merged-managed-sections\" };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nfunction normalize(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/**\n * For v3.0.0 \"Elite Governance\", we want an ULTRA-CLEAN root.\n * Only \"opencode\" is symlinked to the root (required for OpenCode discovery).\n * All other assets stay inside .ai-workflow/.\n */\nconst LINKABLE_ROOTS = new Set([\n \"opencode\",\n \".agents\"\n]);\n\nconst LINKABLE_FILES = new Set<string>([]);\n\nexport interface BuildSymlinkEntriesOptions {\n templateFiles: Record<string, string>;\n installRoot?: string;\n}\n\nexport interface SymlinkEntry {\n linkPath: string;\n targetPath: string;\n}\n\nexport function buildSymlinkEntries({ templateFiles, installRoot = \".ai-workflow\" }: BuildSymlinkEntriesOptions): SymlinkEntry[] {\n const entries = new Map<string, string>();\n\n for (const relativePath of Object.keys(templateFiles)) {\n if (relativePath === \"opencode.jsonc\") continue;\n\n const normalized = normalize(relativePath);\n\n if (LINKABLE_FILES.has(normalized)) {\n entries.set(normalized, `${installRoot}/${normalized}`);\n continue;\n }\n\n // Match composite paths in LINKABLE_ROOTS (e.g., \"docs/policies\")\n for (const rootPath of LINKABLE_ROOTS) {\n if (normalized === rootPath || normalized.startsWith(`${rootPath}/`)) {\n entries.set(rootPath, `${installRoot}/${rootPath}`);\n break;\n }\n }\n }\n\n return Array.from(entries.entries()).map(([linkPath, targetPath]) => ({ linkPath, targetPath }));\n}\n\nexport async function isSymlinkTo(absoluteLinkPath: string, absoluteTargetPath: string): Promise<boolean> {\n try {\n const stat = await fs.lstat(absoluteLinkPath);\n if (!stat.isSymbolicLink()) return false;\n const currentTarget = await fs.readlink(absoluteLinkPath);\n const resolved = path.resolve(path.dirname(absoluteLinkPath), currentTarget);\n return resolved === absoluteTargetPath;\n } catch {\n return false;\n }\n}\n\n/**\n * Internal symlink to satisfy opencode.jsonc paths without polluting the root.\n * Creates .ai-workflow/opencode/skills -> ../.agents/skills\n */\nexport async function setupInternalSymlinks(cwd: string, installRoot: string = \".ai-workflow\"): Promise<void> {\n const skillsLink = path.join(cwd, installRoot, \"opencode/skills\");\n const skillsTarget = path.join(cwd, installRoot, \".agents/skills\");\n\n if (!(await exists(skillsTarget))) return;\n\n try {\n const stat = await fs.lstat(skillsLink).catch(() => null);\n if (stat) {\n if (stat.isSymbolicLink()) {\n const current = await fs.readlink(skillsLink);\n if (current === \"../.agents/skills\") return;\n await fs.unlink(skillsLink);\n } else {\n return; // File exists, skip\n }\n }\n\n const type = process.platform === \"win32\" ? \"junction\" : \"dir\";\n await fs.symlink(\"../.agents/skills\", skillsLink, type);\n } catch {\n // Silent fail for internal symlink\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\n\n/**\n * Claude Adapter - Transforms OpenCode agents and skills into CLAUDE.md and .claude/rules/.\n */\nexport class ClaudeAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent or skill into a Claude rule with completion contract.\n */\n async transformToRule(filePath: string, type: \"agent\" | \"skill\" = \"agent\"): Promise<{ content: string; name: string }> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\") === \"SKILL\" \n ? path.basename(path.dirname(filePath)) \n : path.basename(filePath, \".md\");\n \n const ruleName = `${type}-${fileName.toLowerCase()}`;\n \n const hardenedContent = `---\nname: ${ruleName}\ndescription: ${type === \"agent\" ? \"Persona\" : \"Skill\"} rule for ${fileName}\n---\n# ${fileName} ${type === \"agent\" ? \"Persona\" : \"Skill\"}\n\n${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: hardenedContent,\n name: ruleName\n };\n }\n\n /**\n * Deploys agents, skills, and root CLAUDE.md.\n */\n async deploy(installRoot: string = \".ai-workflow\"): Promise<void> {\n const rulesDir = path.join(this.cwd, \".claude/rules\");\n await fs.mkdir(rulesDir, { recursive: true });\n\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n\n // 1. Deploy Agents to .claude/rules/agent-*.md\n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const transformed = await this.transformToRule(path.join(sourceAgentsDir, file), \"agent\");\n await fs.writeFile(path.join(rulesDir, `${transformed.name}.md`), transformed.content);\n }\n\n // 2. Deploy Skills to .claude/rules/skill-*.md\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n const transformed = await this.transformToRule(skillSource, \"skill\");\n await fs.writeFile(path.join(rulesDir, `${transformed.name}.md`), transformed.content);\n }\n }\n\n // 3. Create root CLAUDE.md\n await this.deployRootClaudeMd(sourceCommandsDir);\n }\n\n async deployRootClaudeMd(sourceCommandsDir: string): Promise<void> {\n const targetPath = path.join(this.cwd, \"CLAUDE.md\");\n \n // Collect commands to document them in CLAUDE.md\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n let commandsDoc = \"\";\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\")) continue;\n const name = path.basename(file, \".md\");\n commandsDoc += `- \\`ai-workflow run --spec-path=...\\` (Target: ${name})\\n`;\n }\n\n const instructions = `# CLAUDE.md - AI Workflow Kit Governance\n\nThis project uses the **AI Workflow Kit** (OpenCode-first) workflow.\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority** (./specs).\n\n## Common Commands\n${commandsDoc}\n- \\`ai-workflow doctor\\`: Verify installation.\n- \\`ai-workflow collect-evidence\\`: Generate EVIDENCE.json.\n\n## Rules & Personas\nAdhere to the specific rules and personas defined in \\`.claude/rules/\\`. \n- Always follow the **Branch Gate** policy (never work on \\`main\\`).\n- Always follow the **SDD Workflow** (Spec -> Plan -> PR -> Evidence).\n\n## Completion Contract\nEvery task completion MUST follow the payload format defined in the individual rule files.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\n\n/**\n * Codex Adapter - Transforms OpenCode agents, skills, and commands into Codex-native formats.\n */\nexport class CodexAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent into a Codex prompt with completion contract.\n */\n async transformAgent(filePath: string): Promise<{ content: string; name: string }> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\");\n \n const hardenedContent = `${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: hardenedContent,\n name: fileName\n };\n }\n\n /**\n * Deploys agents, skills, and commands to Codex-native directories.\n * Mapping:\n * - Agents -> .github/agents/\n * - Skills -> .agents/skills/\n * - Commands -> .codex/prompts/\n */\n async deploy(installRoot: string = \".ai-workflow\"): Promise<void> {\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n\n // 1. Deploy Agents to .github/agents/\n const codexAgentsDir = path.join(this.cwd, \".github/agents\");\n await fs.mkdir(codexAgentsDir, { recursive: true });\n \n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const transformed = await this.transformAgent(path.join(sourceAgentsDir, file));\n await fs.writeFile(path.join(codexAgentsDir, `${transformed.name}.md`), transformed.content);\n }\n\n // 2. Deploy Skills to .agents/skills/\n const codexSkillsDir = path.join(this.cwd, \".agents/skills\");\n await fs.mkdir(codexSkillsDir, { recursive: true });\n\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n const targetDir = path.join(codexSkillsDir, folder);\n await fs.mkdir(targetDir, { recursive: true });\n const content = await fs.readFile(skillSource, \"utf8\");\n await fs.writeFile(path.join(targetDir, \"SKILL.md\"), content);\n }\n }\n\n // 3. Deploy Commands to .codex/prompts/\n const codexPromptsDir = path.join(this.cwd, \".codex/prompts\");\n await fs.mkdir(codexPromptsDir, { recursive: true });\n\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".toml\")) continue;\n // Codex prompts work best as .md\n const targetFileName = file.endsWith(\".toml\") ? `${path.basename(file, \".toml\")}.md` : file;\n const content = await fs.readFile(path.join(sourceCommandsDir, file), \"utf8\");\n await fs.writeFile(path.join(codexPromptsDir, targetFileName), content);\n }\n\n // 4. Copy governance policy into .agents/docs/policies/ so the relative\n // link ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md in each\n // .agents/skills/{skill}/SKILL.md resolves correctly.\n const codexPoliciesDir = path.join(this.cwd, \".agents\", \"docs\", \"policies\");\n await fs.mkdir(codexPoliciesDir, { recursive: true });\n const sourcePoliciesDir = path.join(this.cwd, installRoot, \"opencode\", \"docs\", \"policies\");\n const policyFiles = await fs.readdir(sourcePoliciesDir).catch(() => []);\n for (const file of policyFiles) {\n if (!file.endsWith(\".md\")) continue;\n const policyContent = await fs.readFile(path.join(sourcePoliciesDir, file), \"utf8\");\n await fs.writeFile(path.join(codexPoliciesDir, file), policyContent);\n }\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\nexport interface TransformedItem {\n content: string;\n name: string;\n}\n\n/**\n * Maps OpenCode agent names to primary agent roles.\n */\nconst PERSONA_MAPPING: Record<string, string> = {\n \"atlas\": \"Atlas\",\n \"orion\": \"Orion\",\n \"sage\": \"Sage\",\n \"nexus\": \"Nexus\",\n \"astra\": \"Astra\",\n \"sage-validation\": \"Sage\",\n \"orion-release\": \"Orion\",\n \"orion-deploy\": \"Orion\",\n \"nexus-discovery\": \"Nexus\",\n \"phoenix\": \"Phoenix\"\n};\n\n/**\n * Antigravity Adapter - Transforms OpenCode .md to Antigravity Skill format and manages .agents/ integration.\n */\nexport class AntigravityAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent or specialized skill file to an Antigravity Skill.\n */\n async transform(filePath: string): Promise<TransformedItem> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\") === \"SKILL\" \n ? path.basename(path.dirname(filePath)) \n : path.basename(filePath, \".md\");\n \n const persona = PERSONA_MAPPING[fileName.toLowerCase()] || \"Astra\";\n \n // Check if already has frontmatter\n if (content.trim().startsWith(\"---\")) {\n return { content, name: fileName };\n }\n\n // Extract description from the first paragraph after the title\n const descriptionMatch = content.match(/^# .*\\n\\n(.*)/m);\n const description = descriptionMatch ? descriptionMatch[1].trim() : `Specialized agent for ${fileName}.`;\n\n const skillContent = `---\nname: ${fileName}\ndescription: ${description}\n---\n# ${persona} Persona\n\n${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: skillContent,\n name: fileName\n };\n }\n\n /**\n * Deploys transformed skills and agents to their respective directories.\n * Also orchestrates the .antigravity/ native integration.\n */\n async deploy(transformedItems: TransformedItem[], installRoot: string = \".ai-workflow\"): Promise<void> {\n const agentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const skillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n \n await fs.mkdir(agentsDir, { recursive: true });\n await fs.mkdir(skillsDir, { recursive: true });\n\n for (const item of transformedItems) {\n const isAgent = PERSONA_MAPPING[item.name.toLowerCase()];\n const targetDir = isAgent ? agentsDir : path.join(skillsDir, item.name);\n const fileName = isAgent ? `${item.name}.md` : \"SKILL.md\";\n \n const absoluteTargetDir = isAgent ? agentsDir : targetDir;\n await fs.mkdir(absoluteTargetDir, { recursive: true });\n await fs.writeFile(path.join(absoluteTargetDir, fileName), item.content);\n }\n \n // Deploy native Antigravity extensions (.antigravity/)\n await this.deployNativeExtensions(installRoot);\n\n // Also deploy root ANTIGRAVITY.md if it doesn't exist\n await this.deployInstructions();\n }\n\n /**\n * Orchestrates the .agents/ directory with copies of .ai-workflow/ assets.\n * Using hard copies instead of symlinks ensures native discovery across all platforms.\n */\n async deployNativeExtensions(installRoot: string = \".ai-workflow\"): Promise<void> {\n const antigravityDir = path.join(this.cwd, \".agents\");\n const antigravityAgents = path.join(antigravityDir, \"agents\");\n const antigravitySkills = path.join(antigravityDir, \"skills\");\n const antigravityCommands = path.join(antigravityDir, \"commands\");\n\n await fs.mkdir(antigravityAgents, { recursive: true });\n await fs.mkdir(antigravitySkills, { recursive: true });\n await fs.mkdir(antigravityCommands, { recursive: true });\n\n const getUrls = (targetPath: string) => {\n const linuxUrl = pathToFileURL(targetPath).href;\n const urls = [linuxUrl];\n \n if (process.platform === \"linux\" && process.env.WSL_DISTRO_NAME) {\n const distro = process.env.WSL_DISTRO_NAME;\n const normalizedPath = targetPath.replaceAll(\"\\\\\", \"/\");\n urls.push(`file://wsl.localhost/${distro}${normalizedPath}`);\n urls.push(`file:///wsl.localhost/${distro}${normalizedPath}`);\n }\n \n return urls.join(\"\\n\");\n };\n\n const toolNames = [\n \"send_message\",\n \"find_by_name\",\n \"grep_search\",\n \"view_file\",\n \"list_dir\",\n \"read_url_content\",\n \"search_web\",\n \"schedule\",\n \"multi_replace_file_content\",\n \"replace_file_content\",\n \"write_to_file\",\n \"run_command\",\n \"manage_task\",\n \"define_subagent\",\n \"invoke_subagent\",\n \"manage_subagents\",\n \"call_mcp_tool\"\n ];\n\n const systemPromptConfig = {\n \"includeSections\": [\n \"user_information\",\n \"mcp_servers\",\n \"skills\",\n \"subagent_reminder\",\n \"messaging\",\n \"artifacts\",\n \"user_rules\"\n ]\n };\n\n // 1. Deploy Primary Agents to .agents/agents/{agent_name}/\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n\n const AGENTS_INFO: Record<string, { name: string; description: string }> = {\n \"atlas\": { name: \"Atlas\", description: \"Router and workflow coordinator for AI Workflow Kit\" },\n \"nexus\": { name: \"Nexus\", description: \"Discovery, requirement, scope, and specification owner\" },\n \"orion\": { name: \"Orion\", description: \"Planning, PR sequencing, release, and deployment strategy owner\" },\n \"astra\": { name: \"Astra\", description: \"Implementation owner for incremental, scoped changes\" },\n \"sage\": { name: \"Sage\", description: \"Audit, validation, evidence, and quality gate owner\" },\n \"phoenix\": { name: \"Phoenix\", description: \"Remediation and regression recovery owner\" }\n };\n\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const lowercaseName = path.basename(file, \".md\").toLowerCase();\n const info = AGENTS_INFO[lowercaseName];\n if (!info) continue;\n\n const agentFolder = path.join(antigravityAgents, lowercaseName);\n await fs.mkdir(agentFolder, { recursive: true });\n\n // Copy Markdown file to the agent's folder\n const content = await fs.readFile(path.join(sourceAgentsDir, file), \"utf8\");\n const mdTarget = path.join(agentFolder, `${lowercaseName}.md`);\n await fs.writeFile(mdTarget, content);\n\n // Generate agent.json\n const agentJson = {\n name: lowercaseName,\n description: info.description,\n hidden: false,\n config: {\n customAgent: {\n systemPromptSections: [\n {\n title: \"Agent System Instructions\",\n content: `You are ${info.name}, the ${lowercaseName === \"astra\" ? \"implementation\" : lowercaseName} owner.\\n\\nFollow the contract instructions in:\\n${getUrls(mdTarget)}`\n }\n ],\n toolNames,\n systemPromptConfig\n }\n }\n };\n await fs.writeFile(path.join(agentFolder, \"agent.json\"), JSON.stringify(agentJson, null, 2));\n }\n\n // 2. Deploy Subagents to .agents/agents/{subagent_name}/\n const SUBAGENTS_INFO: Record<string, { description: string; skill: string }> = {\n \"Architecture-Specialist\": { description: \"Select the simplest architecture that safely satisfies current requirements\", skill: \"architecture\" },\n \"Backend-Engineer\": { description: \"Support safe PHP/Node/Python backend changes for APIs and persistence\", skill: \"backend-development\" },\n \"Deployment-Specialist\": { description: \"Plan, review, or validate deployment, release, and production-readiness\", skill: \"deployment\" },\n \"Design-Specialist\": { description: \"Apply practical design principles to keep solutions simple and maintainable\", skill: \"design-principles\" },\n \"Docs-Engineer\": { description: \"Write or improve project documentation, READMEs, guides, and prompts\", skill: \"documentation\" },\n \"Frontend-Engineer\": { description: \"Implement or review frontend changes involving UI, state, routing, and accessibility\", skill: \"frontend-development\" },\n \"Full-Stack-Engineer\": { description: \"Coordinate frontend and backend changes as one coherent, testable increment\", skill: \"full-stack-development\" },\n \"Token-Economist\": { description: \"Reduce context size while preserving information required for safe execution\", skill: \"optimize-tokens\" },\n \"PR-Manager\": { description: \"Plan, implement, review, or validate small pull requests while preserving scope\", skill: \"pr-workflow\" },\n \"Discovery-Analyst\": { description: \"Clarify ambiguous requests into actionable problem statements and success outcomes\", skill: \"product-discovery\" },\n \"Product-Planner\": { description: \"Turn clarified needs into scoped requirements with acceptance-ready outcomes\", skill: \"product-planning\" },\n \"Memory-Guardian\": { description: \"Manage discoverable project memory for durable decisions and recurring corrections\", skill: \"project-memory\" },\n \"Prompt-Engineer\": { description: \"Expert in creating and refining prompts for AI agents and workflows\", skill: \"prompt-engineer\" },\n \"QA-Engineer\": { description: \"Design, review, or improve tests, acceptance criteria, and validation evidence\", skill: \"qa-workflow\" },\n \"Refactoring-Specialist\": { description: \"Improve code/document structure safely while preserving behavior\", skill: \"refactoring\" },\n \"Release-Specialist\": { description: \"Prepare release readiness decisions with explicit gates and evidence\", skill: \"release-workflow\" },\n \"SDD-Specialist\": { description: \"Convert approved requirements into explicit, testable specification artifacts\", skill: \"spec-driven-development\" },\n \"Technical-Leader\": { description: \"Make technical decisions, review architecture, and identify trade-offs\", skill: \"technical-leadership\" },\n \"UI-UX-Engineer\": { description: \"Improve usability and interface clarity without introducing unnecessary complexity\", skill: \"ui-ux-design\" }\n };\n\n for (const [name, subInfo] of Object.entries(SUBAGENTS_INFO)) {\n const lowercaseSubagentName = name.toLowerCase();\n const subagentFolder = path.join(antigravityAgents, lowercaseSubagentName);\n await fs.mkdir(subagentFolder, { recursive: true });\n\n const skillPath = path.join(antigravitySkills, subInfo.skill, \"SKILL.md\");\n\n const subagentJson = {\n name: lowercaseSubagentName,\n description: subInfo.description,\n hidden: false,\n config: {\n customAgent: {\n systemPromptSections: [\n {\n title: \"Agent System Instructions\",\n content: `You are ${name}.\\n\\nFollow the contract instructions in:\\n${getUrls(skillPath)}`\n }\n ],\n toolNames,\n systemPromptConfig\n }\n }\n };\n await fs.writeFile(path.join(subagentFolder, \"agent.json\"), JSON.stringify(subagentJson, null, 2));\n }\n\n // 3. Copy Skills\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n await fs.mkdir(path.join(antigravitySkills, folder), { recursive: true });\n const content = await fs.readFile(skillSource, \"utf8\");\n await fs.writeFile(path.join(antigravitySkills, folder, \"SKILL.md\"), content);\n }\n }\n\n // 4. Copy Commands (from dist-assets/commands)\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n if (await this.exists(sourceCommandsDir)) {\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".toml\")) continue;\n const content = await fs.readFile(path.join(sourceCommandsDir, file), \"utf8\");\n await fs.writeFile(path.join(antigravityCommands, file), content);\n }\n }\n\n // 5. Copy governance policy into .agents/docs/policies/ so the relative\n // link ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md in each\n // .agents/skills/{skill}/SKILL.md resolves correctly.\n const sourcePoliciesDir = path.join(this.cwd, installRoot, \"opencode\", \"docs\", \"policies\");\n const antigravityPolicies = path.join(antigravityDir, \"docs\", \"policies\");\n if (await this.exists(sourcePoliciesDir)) {\n await fs.mkdir(antigravityPolicies, { recursive: true });\n const policyFiles = await fs.readdir(sourcePoliciesDir).catch(() => []);\n for (const file of policyFiles) {\n if (!file.endsWith(\".md\")) continue;\n const content = await fs.readFile(path.join(sourcePoliciesDir, file), \"utf8\");\n await fs.writeFile(path.join(antigravityPolicies, file), content);\n }\n }\n\n // 6. Inject project settings.json\n const settingsPath = path.join(antigravityDir, \"settings.json\");\n if (!(await this.exists(settingsPath))) {\n const settings = {\n model: { name: \"auto\" },\n ui: { theme: \"Ayu\" }\n };\n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));\n }\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Deploys the main ANTIGRAVITY.md and .antigravityignore instructions to the project root.\n */\n async deployInstructions(): Promise<void> {\n const targetPath = path.join(this.cwd, \"ANTIGRAVITY.md\");\n const ignorePath = path.join(this.cwd, \".antigravityignore\");\n \n // Deploy ANTIGRAVITY.md if it doesn't exist\n try {\n await fs.access(targetPath);\n } catch {\n const instructions = `# AI Workflow Kit - Engineering Governance\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority** (./specs).\n\n## Ternary Architecture\n- **Root:** Orchestration and config.\n- **.ai-workflow/:** Implementation (The Muscle).\n- **./specs:** Specifications (The Brain).\n\n## Branch Gates\n- **main Branch:** READ-ONLY.\n- **Validation:** Merges require successful observed validation; full/release workflows may persist EVIDENCE.json.\n\n## Primary Agents\n- **Atlas (Orchestrator)**\n- **Orion (Strategist)**\n- **Sage (Auditor)**\n- **Nexus (Spec Architect)**\n- **Astra (Developer)**\n- **Phoenix (Healer)**\n\n## Operational Preferences\n- Use \\`token-economy\\` and \\`minimal-context\\` skills.\n- **Native Discovery**: This project uses workspace-specific extensions in \\`.agents/\\`.\n- **Workflow Entry**: Use \\`/atlas\\` to begin any task.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n // Deploy .antigravityignore if it doesn't exist\n try {\n await fs.access(ignorePath);\n } catch {\n const ignoreContent = `.ai-workflow/\n.ai-workflow-backups/\nnode_modules/\n.git/\nEVIDENCE.json\n*.tgz\n*.zip\n*.tar\n.agents/tmp/\n.agents/history/\n`;\n await fs.writeFile(ignorePath, ignoreContent);\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { exists, readJson, readJsonc } from \"../../core/filesystem.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\n\nconst REQUIRED_FILES = [\n \".ai-workflow\",\n \"opencode/README.md\"\n];\n\nasync function isSymlink(filePath: string): Promise<boolean> {\n try {\n const stat = await fs.lstat(filePath);\n return stat.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport interface DoctorOptions {\n cwd: string;\n}\n\nexport async function runDoctor({ cwd }: DoctorOptions): Promise<void> {\n let hasFailure = false;\n let hasWarning = false;\n let managedBlocks: string[] = [];\n\n console.log(\"Doctor report:\");\n\n // Check OpenCode runtime\n const adapter = new OpenCodeAdapter({ cwd });\n const inspection = await adapter.inspect();\n if (inspection.available) {\n console.log(\"PASS opencode CLI is available\");\n const supportedStr = Object.entries(inspection.supports)\n .filter(([_, v]) => v)\n .map(([k, _]) => k)\n .join(\", \");\n console.log(`PASS opencode capabilities detected: ${supportedStr || \"none\"}`);\n if (inspection.supports.agent) {\n console.log(\"PASS opencode --agent selection is supported\");\n } else {\n hasWarning = true;\n console.log(\"WARN opencode --agent selection is not supported; prompt fallback is available\");\n }\n } else {\n hasFailure = true;\n console.log(\"FAIL opencode CLI is not installed or not available in PATH\");\n }\n\n for (const relativePath of REQUIRED_FILES) {\n const ok = await exists(path.join(cwd, relativePath));\n\n if (ok) {\n console.log(`PASS ${relativePath}`);\n } else {\n hasFailure = true;\n console.log(`FAIL ${relativePath} missing`);\n }\n }\n\n const configPathV2 = path.join(cwd, \".ai-workflow/config.json\");\n const configPathLegacy = path.join(cwd, \".ai-workflow.json\");\n let configPath: string | null = null;\n\n if (await exists(configPathV2)) {\n configPath = configPathV2;\n } else if (await exists(configPathLegacy)) {\n configPath = configPathLegacy;\n }\n\n if (configPath) {\n try {\n const config = await readJson(configPath);\n\n if (config.installMode === \"project-local\" || config.mode === \"standalone\") {\n console.log(\"PASS install mode is project-local/standalone\");\n } else {\n hasWarning = true;\n console.log(`WARN install mode is not project-local/standalone in ${path.basename(configPath)}`);\n }\n\n if (config.profile) {\n console.log(`PASS profile detected: ${config.profile}`);\n } else {\n hasWarning = true;\n console.log(`WARN profile is missing in ${path.basename(configPath)}`);\n }\n\n if (config.runtime) {\n console.log(`PASS runtime: ${config.runtime}`);\n } else {\n console.log(`NOTE runtime field not present in ${path.basename(configPath)}`);\n }\n\n if (Array.isArray(config.managedBlocks)) {\n managedBlocks = config.managedBlocks;\n } else {\n console.log(`NOTE managedBlocks not present in ${path.basename(configPath)} (legacy field)`);\n }\n\n if (Array.isArray(config.managedFiles)) {\n for (const relativePath of config.managedFiles) {\n const fileExists = await exists(path.join(cwd, relativePath));\n if (!fileExists) {\n hasWarning = true;\n console.log(`WARN managed file missing: ${relativePath}`);\n }\n }\n }\n\n if (Array.isArray(config.managedLinks)) {\n for (const relativePath of config.managedLinks) {\n const absolutePath = path.join(cwd, relativePath);\n const linkExists = await exists(absolutePath);\n if (!linkExists) {\n hasWarning = true;\n console.log(`WARN managed link missing: ${relativePath}`);\n continue;\n }\n\n const isLink = await isSymlink(absolutePath);\n if (!isLink) {\n hasWarning = true;\n console.log(`WARN managed link is not a symlink: ${relativePath}`);\n }\n }\n }\n } catch {\n hasFailure = true;\n console.log(`FAIL ${path.basename(configPath)} is not valid JSON`);\n }\n }\n\n const opencodePath = path.join(cwd, \"opencode.jsonc\");\n if (!(await exists(opencodePath))) {\n hasFailure = true;\n console.log(\"FAIL opencode.jsonc missing\");\n } else {\n try {\n const opencodeConfig = await readJsonc(opencodePath);\n console.log(\"PASS opencode.jsonc is valid JSONC\");\n\n const needsAgentDefault = managedBlocks.includes(\"opencode.jsonc:agent.default\");\n if (!needsAgentDefault || opencodeConfig.agent?.default) {\n console.log(\"PASS opencode agent.default available\");\n } else {\n hasFailure = true;\n console.log(\"FAIL opencode agent.default missing\");\n }\n\n const requiredCommands = managedBlocks\n .filter((block) => block.startsWith(\"opencode.jsonc:command.\"))\n .map((block) => block.replace(\"opencode.jsonc:command.\", \"\"));\n\n if (requiredCommands.length === 0) {\n console.log(\"PASS no managed opencode commands required\");\n } else {\n const missingCommands = requiredCommands.filter((command) => !opencodeConfig.command?.[command]);\n if (missingCommands.length === 0) {\n console.log(`PASS opencode managed commands available (${requiredCommands.length})`);\n } else {\n hasFailure = true;\n console.log(`FAIL opencode command entries missing: ${missingCommands.join(\", \")}`);\n }\n }\n\n const requiredAgents = managedBlocks\n .filter((block) => block.startsWith(\"opencode.jsonc:agent.\") && !block.endsWith(\".default\"))\n .map((block) => block.replace(\"opencode.jsonc:agent.\", \"\"));\n\n if (requiredAgents.length === 0) {\n console.log(\"PASS no managed opencode agents required\");\n } else {\n const missingAgents = requiredAgents.filter((agent) => !opencodeConfig.agent?.[agent]);\n if (missingAgents.length === 0) {\n console.log(`PASS opencode managed agents available (${requiredAgents.length})`);\n } else {\n hasFailure = true;\n console.log(`FAIL opencode agent entries missing: ${missingAgents.join(\", \")}`);\n }\n }\n } catch {\n hasFailure = true;\n console.log(\"FAIL opencode.jsonc is not valid JSONC\");\n }\n }\n\n const packageJsonPath = path.join(cwd, \"package.json\");\n if (await exists(packageJsonPath)) {\n try {\n const packageJson = await readJson(packageJsonPath);\n const scripts = packageJson.scripts ?? {};\n\n if (!scripts.validate) {\n hasWarning = true;\n console.log(\"WARN package.json has no validate script\");\n }\n } catch {\n hasFailure = true;\n console.log(\"FAIL package.json is not valid JSON\");\n }\n }\n\n const finalStatus = hasFailure ? \"FAIL\" : hasWarning ? \"PASS_WITH_NOTES\" : \"PASS\";\n console.log(`Final status: ${finalStatus}`);\n\n if (hasFailure) {\n process.exitCode = 1;\n }\n}\n","export const DELIVERY_SUMMARY_FIELDS = Object.freeze([\n \"Status\",\n \"Branch\",\n \"Changes\",\n \"Validation\",\n \"Known limitations\"\n] as const);\n\nexport function buildDeliverySummary({ evidence }: { evidence: any }): Record<string, string> {\n const commands = (evidence?.commands || []).map((item: any) => `${item.command || item.name}: ${item.status}`).join(\"; \") || \"No validation commands recorded\";\n return {\n Status: evidence?.status || \"BLOCKED\",\n Branch: evidence?.branch || \"unknown\",\n Changes: (evidence?.changedFiles || []).join(\", \") || \"No changed files recorded\",\n Validation: commands,\n \"Known limitations\": (evidence?.limitations || []).join(\"; \") || \"None recorded\"\n };\n}\n\nexport interface ValidationSummaryResult {\n status: \"PASS\" | \"FAIL\";\n missing: string[];\n invalid: string[];\n}\n\nexport function validateDeliverySummary(summary: any): ValidationSummaryResult {\n const missing = DELIVERY_SUMMARY_FIELDS.filter((field) => !String(summary?.[field] || \"\").trim());\n const status = String(summary?.Status || \"\").trim();\n const invalid: string[] = [];\n if (![\"COMPLETED\", \"COMPLETED_WITH_NOTES\", \"BLOCKED\"].includes(status)) invalid.push(\"Status\");\n if (status !== \"BLOCKED\" && /FAIL|BLOCKED/.test(String(summary?.Validation || \"\"))) invalid.push(\"successful status with failed validation\");\n return { status: missing.length || invalid.length ? \"FAIL\" : \"PASS\", missing, invalid };\n}\n\nexport function formatDeliverySummary(summary: any): string {\n return DELIVERY_SUMMARY_FIELDS.map((field) => `${field}: ${summary?.[field] || \"NOT_RECORDED\"}`).join(\"\\n\");\n}\n\n// Backward-compatible aliases for integrations that imported the previous API.\nexport const CANONICAL_FINALIZATION_FIELDS = DELIVERY_SUMMARY_FIELDS;\nexport const buildCanonicalFinalization = ({ collectorStatus = \"BLOCKED\", branchRecovery = \"unknown\" } = {}): Record<string, string> => ({\n Status: collectorStatus === \"PASS\" ? \"COMPLETED\" : collectorStatus === \"PASS_WITH_NOTES\" ? \"COMPLETED_WITH_NOTES\" : \"BLOCKED\",\n Branch: branchRecovery,\n Changes: \"See observed diff\",\n Validation: collectorStatus,\n \"Known limitations\": \"See evidence\"\n});\nexport const validateCanonicalFinalization = validateDeliverySummary;\nexport const formatCanonicalFinalization = formatDeliverySummary;\n","import { EvidenceCollector } from \"../../core/validation/evidence-collector.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { ValidationPlanner } from \"../../core/validation/validation-planner.js\";\nimport { buildDeliverySummary, formatDeliverySummary } from \"../../core/validation/canonical-finalization.js\";\n\nexport interface CollectEvidenceOptions {\n cwd: string;\n exitOnError?: boolean;\n taskSlug?: string | null;\n mode?: string | null;\n evidencePolicy?: \"optional\" | \"required\" | null;\n dryRun?: boolean;\n profile?: string;\n branchRecovery?: string;\n userRequest?: string | null;\n explicitApprovals?: string[];\n visualDist?: string | null;\n port?: number | string | null;\n}\n\n/**\n * @deprecated Boundary helper to translate legacy CLI mode options to modern policies.\n */\nexport function resolvePoliciesFromLegacyMode(mode: string | null, evidencePolicy: \"optional\" | \"required\" | null): {\n evidencePolicy: \"optional\" | \"required\";\n riskLevel: \"low\" | \"medium\" | \"high\";\n} {\n const activePolicy = evidencePolicy || (mode === \"full\" ? \"required\" : \"optional\");\n \n let risk: \"low\" | \"medium\" | \"high\" = \"medium\";\n if (mode === \"full\") {\n risk = \"high\";\n } else if (mode === \"quick\") {\n risk = activePolicy === \"required\" ? \"medium\" : \"low\";\n } else if (activePolicy === \"required\") {\n risk = \"high\";\n }\n \n return { evidencePolicy: activePolicy, riskLevel: risk };\n}\n\nexport async function runCollectEvidence({\n cwd, exitOnError = true, taskSlug = null, mode = null, evidencePolicy = null, dryRun = false, profile = \"generic\", branchRecovery = \"NOT_RECORDED\", userRequest = null, explicitApprovals = [], visualDist = null, port = null\n}: CollectEvidenceOptions): Promise<any> {\n const policies = resolvePoliciesFromLegacyMode(mode, evidencePolicy);\n const qualityGuard = new QualityGuard({ cwd, taskSlug, evidencePolicy: policies.evidencePolicy, riskLevel: policies.riskLevel });\n const planner = new ValidationPlanner({ cwd, qualityGuard });\n const tasks = await planner.plan(profile);\n\n const persist = !dryRun && policies.evidencePolicy === \"required\";\n const collector = new EvidenceCollector({\n cwd,\n timeout: 60000,\n taskSlug,\n evidencePolicy: policies.evidencePolicy,\n profile,\n branchRecovery,\n userRequest,\n explicitApprovals,\n visualDist,\n port: port || 8080\n });\n const evidence = await collector.collect(tasks, { writeArtifact: persist });\n const summary = buildDeliverySummary({ evidence });\n\n console.log(\"\\n--- Delivery Summary ---\");\n console.log(formatDeliverySummary(summary));\n console.log(persist ? \"\\nArtifact: EVIDENCE.json\" : \"\\nArtifact: NOT_REQUIRED for optional evidence policy\");\n console.log(`Commands processed: ${evidence.commands.length}\\n`);\n\n if (evidence.status === \"BLOCKED\" && exitOnError) process.exit(1);\n return evidence;\n}\n","import { spawnSync, execSync } from \"node:child_process\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Determines which npm scripts are available in the consumer project.\n */\nasync function readScripts(cwd: string): Promise<Record<string, string>> {\n try {\n const pkg = JSON.parse(await fs.readFile(path.join(cwd, \"package.json\"), \"utf8\"));\n return pkg.scripts || {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns the list of files changed since the last commit.\n * Used to detect whether remediation produced any observable change.\n */\nfunction getChangedFiles(cwd: string): string[] {\n try {\n const output = execSync(\"git status --short\", { cwd, encoding: \"utf8\" });\n return output\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => line.slice(3).trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n}\n\n/**\n * Maps an affectedCheck source string to likely npm script names to re-run.\n */\nfunction resolveRetryScripts(affectedChecks: string[], scripts: Record<string, string>): string[] {\n const retry = new Set<string>();\n\n for (const check of affectedChecks) {\n // Evidence failures → re-run the failing validation scripts\n if (check === \"evidence\" || check === \"result\") {\n if (scripts.test) retry.add(\"test\");\n if (scripts.lint) retry.add(\"lint\");\n if (scripts.build) retry.add(\"build\");\n if (scripts.typecheck) retry.add(\"typecheck\");\n }\n // Specific check types\n if (check.includes(\"test\")) retry.add(\"test\");\n if (check.includes(\"lint\")) retry.add(\"lint\");\n if (check.includes(\"build\")) retry.add(\"build\");\n if (check.includes(\"typecheck\")) retry.add(\"typecheck\");\n }\n\n // Filter to only scripts that actually exist\n return [...retry].filter((name) => !!scripts[name]);\n}\n\nexport interface RemediationExecutorContext {\n attempt: number;\n maxAttempts: number;\n mode: string;\n taskSlug: string;\n result: any;\n affectedChecks: string[];\n requestPath: string;\n}\n\nexport interface RemediationExecutorResult {\n applied: boolean;\n changedFiles?: string[];\n evidenceAdded?: string[];\n reason?: string;\n}\n\n/**\n * CLI Remediation Executor — default implementation for `ai-workflow run`.\n */\nexport function createCliRemediationExecutor(cwd: string) {\n return async function remediationExecutor({\n attempt,\n maxAttempts,\n mode,\n affectedChecks,\n requestPath\n }: RemediationExecutorContext): Promise<RemediationExecutorResult> {\n console.log(`\\n[HEALER] Attempt ${attempt}/${maxAttempts} — mode: ${mode}`);\n console.log(`[HEALER] Affected: ${affectedChecks.join(\", \")}`);\n\n const scripts = await readScripts(cwd);\n const filesBefore = getChangedFiles(cwd);\n const toRetry = resolveRetryScripts(affectedChecks, scripts);\n\n if (toRetry.length === 0) {\n console.log(\"[HEALER] No retryable scripts found for the affected checks.\");\n console.log(`[HEALER] Review ${requestPath} for details.`);\n return {\n applied: false,\n reason: `No npm scripts available to address: ${affectedChecks.join(\", \")}. Manual remediation required.`\n };\n }\n\n console.log(`[HEALER] Re-running: ${toRetry.map((s) => `npm run ${s}`).join(\", \")}`);\n\n const results: any[] = [];\n let anyPassed = false;\n\n for (const scriptName of toRetry) {\n process.stdout.write(` → npm run ${scriptName} ... `);\n const isWin32 = process.platform === \"win32\";\n const cmd = isWin32 ? \"npm.cmd\" : \"npm\";\n const result = spawnSync(cmd, [\"run\", scriptName], {\n cwd,\n shell: false,\n encoding: \"utf8\",\n timeout: 120000\n });\n const passed = result.status === 0;\n if (passed) anyPassed = true;\n console.log(passed ? \"PASS\" : \"FAIL\");\n results.push({ script: scriptName, passed, exitCode: result.status });\n }\n\n const filesAfter = getChangedFiles(cwd);\n const changedFiles = filesAfter.filter((f) => !filesBefore.includes(f));\n\n if (!anyPassed && changedFiles.length === 0) {\n console.log(\"[HEALER] No scripts passed and no files changed — remediation had no effect.\");\n return {\n applied: false,\n reason: `Re-ran ${toRetry.join(\", \")} — all failed. Structural fix required by the implementing agent.`\n };\n }\n\n console.log(`[HEALER] Applied: ${results.filter((r) => r.passed).map((r) => r.script).join(\", \") || \"none passed\"}`);\n if (changedFiles.length) console.log(`[HEALER] Changed files: ${changedFiles.join(\", \")}`);\n\n return {\n applied: true,\n changedFiles,\n evidenceAdded: anyPassed ? [\"validation-output\"] : []\n };\n };\n}\n","import { BranchGate } from \"../../core/gates/branch-gate.js\";\nimport { SpecValidator } from \"../../core/sdd/validator.js\";\nimport { HandoffEngine } from \"../../core/handoff/handoff-engine.js\";\nimport { runCollectEvidence } from \"./collect-evidence.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { HealerEngine } from \"../../core/healing/healer-engine.js\";\nimport { createCliRemediationExecutor } from \"../../core/healing/cli-remediation-executor.js\";\nimport { isRecoverableGateFailure, isTerminalFailure } from \"../../core/statuses.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { getWorkflowProfile, resolveWorkflowProfile } from \"../../core/workflow-profiles.js\";\n\nfunction normalizeTaskSlugFromSpec(specPath: string): string {\n const normalized = String(specPath).replaceAll(\"\\\\\", \"/\");\n const marker = \"/docs/workflows/\";\n const index = normalized.includes(marker)\n ? normalized.indexOf(marker) + marker.length\n : normalized.startsWith(\"docs/workflows/\") ? \"docs/workflows/\".length : -1;\n if (index >= 0) {\n const slug = normalized.slice(index).split(\"/\")[0];\n if (slug) return slug;\n }\n return path.basename(specPath, path.extname(specPath));\n}\n\nexport function combineValidation(evidence: any, quality: any): any {\n const statuses = [evidence.internalStatus, quality.overallStatus];\n let overallStatus = \"PASS\";\n if (statuses.includes(\"BLOCKED\")) overallStatus = \"BLOCKED\";\n else if (statuses.includes(\"FAIL\")) overallStatus = \"FAIL\";\n else if (statuses.includes(\"FAIL_DELEGATION_GATE\")) overallStatus = \"FAIL_DELEGATION_GATE\";\n else if (statuses.includes(\"FAIL_QUALITY_GATE\")) overallStatus = \"FAIL_QUALITY_GATE\";\n else if (statuses.includes(\"PASS_WITH_NOTES\")) overallStatus = \"PASS_WITH_NOTES\";\n return { overallStatus, evidence, quality };\n}\n\nexport interface runMasterOrchestratorOptions {\n cwd: string;\n specPath?: string;\n override?: string;\n remediationExecutor?: any;\n}\n\n/**\n * Coordinates branch safety, specification validation, observed validation, bounded remediation, and handoff.\n * Failed required validation can never be promoted to success.\n */\nexport async function runMasterOrchestrator({ cwd, specPath, override, remediationExecutor = null }: runMasterOrchestratorOptions): Promise<any> {\n console.log(\"\\n[AI WORKFLOW] Starting evidence-backed orchestration...\\n\");\n\n const branchGate = new BranchGate({ memoryDir: path.join(cwd, \".ai-workflow\"), cwd });\n const taskSlug = specPath ? normalizeTaskSlugFromSpec(specPath) : \"implementation\";\n const gateResult = branchGate.check(override, { taskSlug });\n if (gateResult.blocked) throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);\n console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);\n\n if (!specPath) throw new Error(\"[SDD BLOCKED] Missing --spec-path. An approved specification is required.\");\n\n const validator = new SpecValidator();\n const absoluteSpecPath = path.isAbsolute(specPath) ? specPath : path.join(cwd, specPath);\n const validation = await validator.validate(absoluteSpecPath);\n if (!validation.valid) throw new Error(`[SDD BLOCKED] Specification is not ready: ${validation.reason}`);\n\n const specTier = validation.tier || \"standard\";\n const riskLevel = specTier === \"deep\" ? \"high\" : specTier === \"tiny\" ? \"low\" : \"medium\";\n const evidencePolicy = specTier === \"deep\" ? \"required\" : \"optional\";\n const remediationLimit = specTier === \"deep\" ? 3 : specTier === \"tiny\" ? 1 : 2;\n\n const specContent = await fs.readFile(absoluteSpecPath, \"utf8\");\n const workflowProfile = resolveWorkflowProfile({ request: specContent });\n const profileDefinition = getWorkflowProfile(workflowProfile);\n console.log(`[PASS] Specification: ${specTier.toUpperCase()} spec is APPROVED.`);\n console.log(`[PROFILE] ${workflowProfile} -> ${profileDefinition.owner}; skills: ${profileDefinition.skills.join(\", \") || \"none\"}.`);\n\n const validateWorkflow = async () => {\n const evidence = await runCollectEvidence({\n cwd,\n exitOnError: false,\n taskSlug,\n evidencePolicy,\n profile: workflowProfile,\n branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : \"NOT_REQUIRED\"\n });\n const quality = await new QualityGuard({ cwd, taskSlug, evidencePolicy, riskLevel }).verify();\n return combineValidation(evidence, quality);\n };\n\n let result = await validateWorkflow();\n if (isRecoverableGateFailure(result.overallStatus)) {\n console.log(`\\n[REMEDIATION REQUIRED] ${result.overallStatus}. Starting bounded remediation (limit: ${remediationLimit}).`);\n // Use the provided executor (programmatic API) or fall back to the default CLI executor.\n // The CLI executor re-runs failed npm scripts; it does not modify source code.\n const executor = typeof remediationExecutor === \"function\"\n ? remediationExecutor\n : createCliRemediationExecutor(cwd);\n const healer = new HealerEngine({ cwd, remediationLimit, taskSlug });\n result = await healer.run({ initialResult: result, validate: validateWorkflow, remediate: executor });\n }\n\n if (isTerminalFailure(result.overallStatus)) {\n throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: ${result.reason || \"Validation could not be resolved safely.\"}`);\n }\n if (isRecoverableGateFailure(result.overallStatus)) {\n throw new Error(`[WORKFLOW BLOCKED] Unresolved gate status after remediation: ${result.overallStatus}`);\n }\n\n console.log(\"\\n--- Final Handoff ---\");\n const handoffEngine = new HandoffEngine({ cwd });\n const handoffPath = await handoffEngine.generate({\n taskId: path.basename(specPath, \".md\"),\n status: result.overallStatus,\n specPaths: [specPath],\n evidence: result.evidence,\n nextActions: `Profile ${workflowProfile}. Observed validation completed. Ready for review or explicitly approved release actions.`\n });\n\n console.log(`\\n[AI WORKFLOW COMPLETE] ${result.overallStatus}`);\n if (result.remediation?.attempts) console.log(`Remediation attempts: ${result.remediation.attempts}`);\n console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\\n`);\n return { ...result, workflowProfile };\n}\n","import { OpenCodeAdapter } from \"../runtime/opencode-adapter.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { EvidenceLedger } from \"../evidence/evidence-ledger.js\";\n\nexport function createRuntimeRemediationExecutor(cwd: string, ledger: EvidenceLedger | null = null) {\n const adapter = new OpenCodeAdapter({ cwd });\n\n function getChangedFiles(): string[] {\n try {\n const output = execSync(\"git status --short\", { cwd, encoding: \"utf8\" });\n return output\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => line.slice(3).trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n }\n\n return async function runtimeRemediationExecutor({\n attempt,\n maxAttempts,\n mode,\n affectedChecks,\n requestPath,\n result\n }: {\n attempt: number;\n maxAttempts: number;\n mode: string;\n affectedChecks: string[];\n requestPath: string;\n result: any;\n }): Promise<{ applied: boolean; changedFiles?: string[]; evidenceAdded?: string[]; reason?: string }> {\n console.log(`\\n[HEALER] Running Runtime/Phoenix Structural Remediation [Attempt ${attempt}/${maxAttempts}]`);\n console.log(`[HEALER] Affected checks: ${affectedChecks.join(\", \")}`);\n\n if (ledger) {\n ledger.logEvent({\n actor: \"Phoenix\",\n actorType: \"runtime-agent\",\n observed: true,\n runtime: \"opencode\",\n eventType: \"remediation_start\",\n provenance: \"opencode-adapter\",\n data: {\n attempt,\n affectedChecks,\n event: \"remediation.started\"\n }\n });\n }\n\n let requestContent: any = {};\n try {\n requestContent = JSON.parse(await fs.readFile(requestPath, \"utf8\"));\n } catch {\n // ignore/fallback\n }\n\n const filesBefore = getChangedFiles();\n const fileContentsBefore: Record<string, string | null> = {};\n for (const file of filesBefore) {\n try {\n fileContentsBefore[file] = await fs.readFile(path.join(cwd, file), \"utf8\");\n } catch {\n fileContentsBefore[file] = null;\n }\n }\n \n // Extract concrete command outputs for failing checks\n const failedCommands = (result?.evidence?.commands || [])\n .filter((cmd: any) => [\"FAIL\", \"BLOCKED\"].includes(cmd.status));\n \n let concreteOutput = \"\";\n if (failedCommands.length > 0) {\n concreteOutput = failedCommands.map((cmd: any) => {\n return `Command: ${cmd.name} (${Array.isArray(cmd.command) ? cmd.command.join(\" \") : cmd.command})\nExit Code: ${cmd.exitCode}\nOutput:\n${cmd.output}`;\n }).join(\"\\n\\n\");\n } else {\n concreteOutput = JSON.stringify(result?.quality || result || {}, null, 2);\n }\n\n const promptMsg = `We are in remediation mode (attempt ${attempt}/${maxAttempts}).\nThe following validation checks have failed:\n${affectedChecks.join(\", \")}\n\nDetails of the failure:\n\\`\\`\\`\n${concreteOutput}\n\\`\\`\\`\n\nPlease inspect the code, identify the root cause of these failures (e.g. failing tests, syntax issues, build errors), and write a correction to the relevant files in the workspace to make the tests/validations pass.`;\n\n console.log(`[HEALER] Sending structural healing request to Phoenix agent...`);\n const runResult = await adapter.execute(promptMsg, {\n agent: \"Phoenix\"\n });\n\n const filesAfter = getChangedFiles();\n const changedFiles: string[] = [];\n for (const file of filesAfter) {\n if (!filesBefore.includes(file)) {\n changedFiles.push(file);\n } else {\n try {\n const contentAfter = await fs.readFile(path.join(cwd, file), \"utf8\");\n if (contentAfter !== fileContentsBefore[file]) {\n changedFiles.push(file);\n }\n } catch {\n if (fileContentsBefore[file] !== null) {\n changedFiles.push(file);\n }\n }\n }\n }\n const success = runResult.success && changedFiles.length > 0;\n\n if (!runResult.success) {\n console.log(`[HEALER] Phoenix remediation failed: ${runResult.error || \"Unknown error\"}`);\n return {\n applied: false,\n reason: `Phoenix runtime execution failed: ${runResult.error || \"Unknown error\"}`\n };\n }\n\n if (changedFiles.length === 0) {\n console.log(`[HEALER] Phoenix execution succeeded but no files were modified.`);\n return {\n applied: false,\n reason: \"Phoenix runtime executed but did not modify any files in the workspace.\"\n };\n }\n\n console.log(`[HEALER] Phoenix successfully executed remediation commands.`);\n console.log(`[HEALER] Files modified: ${changedFiles.join(\", \")}`);\n\n return {\n applied: true,\n changedFiles,\n evidenceAdded: [\"phoenix-healing-run\"]\n };\n };\n}\n","import { RequestClassifier, RequestClassifierResult } from \"../../core/request-classifier.js\";\nimport { ExecutionPlanner, ExecutionPlan } from \"../../core/execution-planner.js\";\nimport { WorkflowStateMachine } from \"../../core/workflow-state-machine.js\";\nimport { BranchGate } from \"../../core/gates/branch-gate.js\";\nimport { EvidenceLedger } from \"../../core/evidence/evidence-ledger.js\";\nimport { DelegationController } from \"../../core/delegation-controller.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\nimport { runCollectEvidence } from \"./collect-evidence.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { HandoffEngine } from \"../../core/handoff/handoff-engine.js\";\nimport { HealerEngine } from \"../../core/healing/healer-engine.js\";\nimport { createRuntimeRemediationExecutor } from \"../../core/healing/runtime-remediation-executor.js\";\nimport { isRecoverableGateFailure, isTerminalFailure } from \"../../core/statuses.js\";\nimport { Finalizer } from \"../../core/finalization/finalizer.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\n\n/** Snapshot of workspace state before/after read-only execution. */\ninterface ReadOnlyWorkspaceState {\n snapshot: { files: Record<string, { sha256: string }> };\n head: string;\n branch: string;\n indexTree: string;\n porcelainStatus: string;\n}\n\n/** Combined result from evidence collection and quality guard. */\ninterface ValidationResult {\n overallStatus: string;\n evidence: Record<string, unknown>;\n quality: Record<string, unknown>;\n}\n\n/** Result returned by BranchGate.check(). */\ninterface BranchGateResult {\n blocked: boolean;\n reason: string;\n branch: string;\n branchBefore: string;\n recovered: boolean;\n}\n\nasync function captureReadOnlyState(cwd: string, fastTrack = false) {\n const finalizer = new Finalizer({ cwd, fastTrack });\n const snapshot = await finalizer.snapshotManager.capture();\n \n const execGit = (args: string) => {\n try {\n return execSync(`git ${args}`, { cwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n return \"\";\n }\n };\n\n const head = execGit(\"rev-parse HEAD\");\n const branch = execGit(\"rev-parse --abbrev-ref HEAD\");\n const indexTree = execGit(\"write-tree\");\n const porcelainStatus = execGit(\"status --porcelain\");\n\n return {\n snapshot,\n head,\n branch,\n indexTree,\n porcelainStatus\n };\n}\n\nfunction compareReadOnlyState(before: ReadOnlyWorkspaceState, after: ReadOnlyWorkspaceState) {\n const violations: string[] = [];\n\n // 1. Compare branch\n if (before.branch !== after.branch) {\n violations.push(`Branch changed from '${before.branch}' to '${after.branch}'`);\n }\n\n // 2. Compare HEAD\n if (before.head !== after.head) {\n violations.push(`Git HEAD changed from '${before.head}' to '${after.head}' (commit or reset made inside read-only task)`);\n }\n\n // 3. Compare index tree\n if (before.indexTree !== after.indexTree) {\n violations.push(`Git index tree changed from '${before.indexTree}' to '${after.indexTree}'`);\n }\n\n // 4. Compare porcelain status\n if (before.porcelainStatus !== after.porcelainStatus) {\n violations.push(`Git status changed. Before:\\n${before.porcelainStatus}\\nAfter:\\n${after.porcelainStatus}`);\n }\n\n // 5. Compare workspace files (SHA-256 hashes)\n const beforeFiles = before.snapshot.files || {};\n const afterFiles = after.snapshot.files || {};\n\n for (const [file, info] of Object.entries(afterFiles)) {\n const prevInfo = beforeFiles[file];\n if (!prevInfo) {\n violations.push(`File added: ${file}`);\n } else if (prevInfo.sha256 !== (info as any).sha256) {\n violations.push(`File content modified: ${file}`);\n }\n }\n for (const file of Object.keys(beforeFiles)) {\n if (!afterFiles[file]) {\n violations.push(`File deleted: ${file}`);\n }\n }\n\n return violations;\n}\n\nfunction slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 32) || \"task\";\n}\n\nfunction combineValidation(evidence: Record<string, unknown>, quality: Record<string, unknown>): ValidationResult {\n const statuses = [evidence.internalStatus, quality.overallStatus];\n let overallStatus = \"PASS\";\n if (statuses.includes(\"BLOCKED\")) overallStatus = \"BLOCKED\";\n else if (statuses.includes(\"FAIL\")) overallStatus = \"FAIL\";\n else if (statuses.includes(\"FAIL_DELEGATION_GATE\")) overallStatus = \"FAIL_DELEGATION_GATE\";\n else if (statuses.includes(\"FAIL_QUALITY_GATE\")) overallStatus = \"FAIL_QUALITY_GATE\";\n else if (statuses.includes(\"PASS_WITH_NOTES\")) overallStatus = \"PASS_WITH_NOTES\";\n return { overallStatus, evidence, quality };\n}\n\nexport interface ExecuteOptions {\n cwd: string;\n naturalRequest: string;\n taskSlug?: string;\n}\n\n/**\n * classifyAndPlanExecution - Intake analysis and contract formulation.\n */\nasync function classifyAndPlanExecution(\n naturalRequest: string,\n cwd: string,\n taskSlug: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<{ plan: ExecutionPlan; classification: RequestClassifierResult }> {\n const classifier = new RequestClassifier();\n const classification = classifier.classify(naturalRequest, { cwd });\n console.log(`[CLASSIFIED] Intent: ${classification.intent}, Mode: ${classification.mode}, Profile: ${classification.profile}`);\n stateMachine.transitionTo(\"CLASSIFIED\");\n\n await delegationController.route(naturalRequest, classification);\n\n const routingDecision = classification.routingDecision || {};\n if (routingDecision.permissionDecision === \"blocked\") {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[ROUTE BLOCKED] ${routingDecision.reason}`);\n }\n if (routingDecision.permissionDecision === \"rerouted\") {\n console.log(`[REROUTED] ${routingDecision.reason}`);\n }\n\n const planner = new ExecutionPlanner({ cwd });\n const plan = planner.plan(classification, taskSlug);\n console.log(`[PLANNED] Owner: ${plan.owner}, Remediation limit: ${plan.remediationLimit}`);\n stateMachine.transitionTo(\"PLANNED\");\n\n return { plan, classification };\n}\n\n/**\n * runBranchGate - Authorizes changes within the branch lifecycle.\n */\nfunction runBranchGate(plan: ExecutionPlan, taskSlug: string, cwd: string, stateMachine: WorkflowStateMachine, branchGate: BranchGate): BranchGateResult {\n const gateResult = branchGate.check(\"\", {\n taskSlug,\n readOnly: !plan.branchNeeded\n });\n\n if (gateResult.blocked) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);\n }\n console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);\n stateMachine.transitionTo(\"BRANCH_READY\");\n return gateResult;\n}\n\n/**\n * createSpecIfRequired - Implements Spec-Driven Development gate.\n */\nasync function createSpecIfRequired(plan: ExecutionPlan, classification: RequestClassifierResult, taskSlug: string, cwd: string): Promise<void> {\n if (plan.specPath) {\n const fullSpecPath = path.join(cwd, plan.specPath);\n const specExists = await fs.access(fullSpecPath).then(() => true).catch(() => false);\n if (!specExists) {\n await fs.mkdir(path.dirname(fullSpecPath), { recursive: true });\n const specTemplatePath = path.join(cwd, \".ai-workflow/templates/specs/standard.md\");\n const templateContent = await fs.readFile(specTemplatePath, \"utf8\").catch(() => {\n return `# [STANDARD] Specification: ${classification.request}\\n\\n## Metadata\\n\\n- ID: SPEC-${taskSlug}\\n- Author: Spec-Engineer\\n- Status: DRAFT\\n- Date: ${new Date().toISOString().split(\"T\")[0]}\\n\\n## Functional Requirements\\n\\n- ${classification.request}\\n\\n## Technical Implementation Plan\\n\\n### Files to Create/Modify\\n\\n- \\`src/index.js\\`\\n\\n## Acceptance Criteria\\n\\n- [ ] Implemented successfully\\n\\n## Testing Strategy\\n\\n- [ ] Behavior tests pass`;\n });\n await fs.writeFile(fullSpecPath, templateContent);\n console.log(`[EXECUTE] Created DRAFT specification template at: ${plan.specPath}`);\n }\n }\n}\n\n/**\n * runImplementation - Delegations to the implementation engine.\n */\nasync function runImplementation(\n plan: ExecutionPlan,\n classification: RequestClassifierResult,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine,\n fastTrack: boolean = false\n): Promise<any> {\n stateMachine.transitionTo(\"DELEGATED\");\n stateMachine.transitionTo(\"IMPLEMENTING\");\n\n let promptMsg = classification.request;\n if (plan.specPath) {\n promptMsg = `Please review and fill in the specification file at: ${plan.specPath}. Make sure to change the Status field to 'APPROVED' in the Metadata section, and then implement the behavior described.`;\n }\n\n const runResult = await delegationController.implement(promptMsg, plan.owner, { readOnly: !plan.branchNeeded, fastTrack });\n\n if (!runResult.success) {\n console.error(`[EXECUTE] OpenCode adapter execution reported failure: ${runResult.error || \"Unknown error\"}`);\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] OpenCode runtime execution failed: ${runResult.error || \"Unknown error\"}`);\n }\n return runResult;\n}\n\n/**\n * runReadOnlyConfinementCheck - Asserts read-only execution constraints.\n */\nasync function runReadOnlyConfinementCheck(readOnlyStateBefore: ReadOnlyWorkspaceState, cwd: string, stateMachine: WorkflowStateMachine, fastTrack = false): Promise<void> {\n const readOnlyStateAfter = await captureReadOnlyState(cwd, fastTrack);\n const violations = compareReadOnlyState(readOnlyStateBefore, readOnlyStateAfter);\n if (violations.length > 0) {\n console.error(`[EXECUTE] Read-only confinement violation detected:`);\n for (const v of violations) {\n console.error(` - ${v}`);\n }\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] Read-only confinement violation: files were written/modified, index or commits modified: \\n${violations.join(\"\\n\")}`);\n }\n}\n\n/**\n * runValidation - Resolves evidence validation contracts.\n */\nasync function runValidation(\n plan: ExecutionPlan,\n taskSlug: string,\n cwd: string,\n gateResult: BranchGateResult,\n naturalRequest: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<{ result: ValidationResult; validateWorkflow: () => Promise<ValidationResult> }> {\n stateMachine.transitionTo(\"VALIDATING\");\n\n const validateWorkflow = async () => {\n const evidence = await runCollectEvidence({\n cwd,\n exitOnError: false,\n taskSlug,\n evidencePolicy: plan.evidencePolicy,\n profile: plan.profile,\n branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : \"NOT_REQUIRED\",\n userRequest: naturalRequest,\n explicitApprovals: process.env.AI_WORKFLOW_APPROVALS ? process.env.AI_WORKFLOW_APPROVALS.split(\",\").map(a => a.trim()) : []\n });\n const quality = await new QualityGuard({\n cwd,\n taskSlug,\n evidencePolicy: plan.evidencePolicy,\n riskLevel: plan.riskLevel\n }).verify();\n return combineValidation(evidence, quality);\n };\n\n const result = await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n return { result, validateWorkflow };\n}\n\n/**\n * runBoundedRemediation - Heals gate violations.\n */\nasync function runBoundedRemediation(\n plan: any,\n taskSlug: string,\n cwd: string,\n initialResult: any,\n validateWorkflow: () => Promise<any>,\n ledger: EvidenceLedger,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine,\n checkBranchSafety: () => void,\n updateSnapshot: () => Promise<void>\n): Promise<any> {\n if (!isRecoverableGateFailure(initialResult.overallStatus)) {\n return initialResult;\n }\n\n console.log(`\\n[REMEDIATION REQUIRED] ${initialResult.overallStatus}. Starting bounded remediation (limit: ${plan.remediationLimit}).`);\n const executor = createRuntimeRemediationExecutor(cwd, ledger);\n const healer = new HealerEngine({\n cwd,\n remediationLimit: plan.remediationLimit,\n taskSlug,\n ledger\n });\n\n return await healer.run({\n initialResult,\n validate: async () => {\n stateMachine.transitionTo(\"REVALIDATING\");\n return await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n },\n remediate: async (remedCtx) => {\n stateMachine.transitionTo(\"REMEDIATING\");\n const remRes = await executor(remedCtx as any);\n if (remRes.applied) {\n checkBranchSafety();\n await updateSnapshot();\n }\n return remRes;\n }\n });\n}\n\n/**\n * runFinalizerStabilization - Verifies integrity and fidelity.\n */\nasync function runFinalizerStabilization(\n plan: any,\n taskSlug: string,\n cwd: string,\n initialResult: any,\n validateWorkflow: () => Promise<any>,\n delegationController: DelegationController,\n finalizer: Finalizer,\n lastWriteSnapshotRef: { current: any },\n checkBranchSafety: () => void\n): Promise<{ result: any; integrity: any }> {\n let integrity = await finalizer.verifyIntegrity(lastWriteSnapshotRef.current);\n let revalidationCount = 0;\n const maxRevalidations = 2;\n let result = initialResult;\n\n while (!integrity.valid && revalidationCount < maxRevalidations) {\n console.log(`\\n[FINALIZER WARNING] Workspace mutated during validation! Re-running validation to stabilize.`);\n console.log(`Changes detected:`, integrity.changes);\n\n checkBranchSafety();\n\n lastWriteSnapshotRef.current = await finalizer.snapshotManager.capture();\n revalidationCount++;\n\n result = await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n\n checkBranchSafety();\n\n integrity = await finalizer.verifyIntegrity(lastWriteSnapshotRef.current);\n }\n\n return { result, integrity };\n}\n\n/**\n * generateFinalHandoff - Generates Handoff report.\n */\nasync function generateFinalHandoff(plan: ExecutionPlan, taskSlug: string, cwd: string, finalState: string, evidence: Record<string, unknown> | null): Promise<string> {\n console.log(\"\\n--- Final Handoff ---\");\n const handoffEngine = new HandoffEngine({ cwd });\n const handoffPath = await handoffEngine.generate({\n taskId: taskSlug,\n status: finalState,\n specPaths: plan.specPath ? [plan.specPath] : [],\n evidence,\n nextActions: `Profile ${plan.profile}. Observed execution completed with status ${finalState}.`\n });\n\n console.log(`\\n[AI WORKFLOW COMPLETE] ${finalState}`);\n console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\\n`);\n return handoffPath;\n}\n\n/**\n * runExecute - Coordinators natural request execution.\n */\nexport async function runExecute({ cwd, naturalRequest, taskSlug: taskSlugOverride }: ExecuteOptions): Promise<any> {\n if (!naturalRequest || !naturalRequest.trim()) {\n throw new Error(\"Missing request. Please provide a natural request string via positional arguments or --request flag.\");\n }\n\n const taskSlug = taskSlugOverride || slugify(naturalRequest);\n console.log(`\\n[AI WORKFLOW] Executing natural request intake [slug: ${taskSlug}]...\\n`);\n\n const ledger = new EvidenceLedger({ cwd, workflowId: taskSlug });\n const delegationController = new DelegationController({ cwd, ledger, adapter: new OpenCodeAdapter({ cwd }) });\n\n let plan: ExecutionPlan | null = null;\n try {\n const stateMachine = new WorkflowStateMachine();\n\n // 1. Classification & Planning\n const { plan: planObj, classification } = await classifyAndPlanExecution(naturalRequest, cwd, taskSlug, delegationController, stateMachine);\n plan = planObj;\n const fastTrack = plan.riskLevel === \"low\" && (plan.branchNeeded ? plan.evidencePolicy === \"optional\" : true);\n\n // 2. Branch Gate\n const branchGate = new BranchGate({ memoryDir: path.join(cwd, \".ai-workflow\"), cwd });\n const gateResult = runBranchGate(plan, taskSlug, cwd, stateMachine, branchGate);\n\n const checkBranchSafety = () => {\n if (plan.branchNeeded) {\n const currentBranch = branchGate.getCurrentBranch();\n if (branchGate.protectedBranches.includes(currentBranch)) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] Security violation: current branch is protected '${currentBranch}'!`);\n }\n }\n };\n\n // 3. Spec template creation\n await createSpecIfRequired(plan, classification, taskSlug, cwd);\n\n // 4. Confinement capture before implementation\n let readOnlyStateBefore: ReadOnlyWorkspaceState | null = null;\n if (!plan.branchNeeded) {\n readOnlyStateBefore = await captureReadOnlyState(cwd, fastTrack);\n }\n\n // 5. Implementation\n await runImplementation(plan, classification, delegationController, stateMachine, fastTrack);\n\n // 6. Confinement check\n if (!plan.branchNeeded) {\n await runReadOnlyConfinementCheck(readOnlyStateBefore, cwd, stateMachine, fastTrack);\n\n stateMachine.transitionTo(\"IMPLEMENTED\");\n stateMachine.transitionTo(\"VALIDATING\");\n stateMachine.transitionTo(\"COMPLETED\");\n\n console.log(\"\\n--- Final Handoff ---\");\n console.log(`\\n[AI WORKFLOW COMPLETE] COMPLETED`);\n console.log(`Handoff Packet: [IN-MEMORY] (No handoff file written in read-only mode)\\n`);\n\n return {\n overallStatus: \"PASS\",\n evidence: {\n internalStatus: \"PASS\",\n commandsRun: []\n },\n quality: {\n overallStatus: \"PASS\"\n },\n stateHistory: stateMachine.getHistory()\n };\n }\n\n stateMachine.transitionTo(\"IMPLEMENTED\");\n checkBranchSafety();\n\n // Capture snapshot immediately after last implementation write\n const finalizer = new Finalizer({ cwd, fastTrack });\n const snapshotRef = { current: await finalizer.snapshotManager.capture() };\n\n // 7. Validation\n const { result: valResult, validateWorkflow } = await runValidation(plan, taskSlug, cwd, gateResult, naturalRequest, delegationController, stateMachine);\n let result = valResult;\n\n // 8. Bounded Remediation\n result = await runBoundedRemediation(\n plan,\n taskSlug,\n cwd,\n result,\n validateWorkflow,\n ledger,\n delegationController,\n stateMachine,\n checkBranchSafety,\n async () => {\n snapshotRef.current = await finalizer.snapshotManager.capture();\n }\n );\n\n if (isTerminalFailure(result.overallStatus)) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: Validation could not be resolved safely.`);\n }\n\n checkBranchSafety();\n\n // 9. Finalizer / Stabilization Loop\n let integrity = { valid: true, changes: { added: [], modified: [], deleted: [] } };\n let stabResult = result;\n if (!fastTrack) {\n const stab = await runFinalizerStabilization(\n plan,\n taskSlug,\n cwd,\n result,\n validateWorkflow,\n delegationController,\n finalizer,\n snapshotRef,\n checkBranchSafety\n );\n stabResult = stab.result;\n integrity = stab.integrity;\n }\n result = stabResult;\n\n let finalStatus = result.overallStatus;\n if (fastTrack) {\n console.log(`\\n--- [FAST-TRACK] Running Lightweight Validation Gates ---`);\n \n // 1. Branch safety check\n checkBranchSafety();\n \n // 2. Changed files summary\n const changedFiles = result.evidence?.changedFiles || [];\n console.log(`[FAST-TRACK] Changed files detected:`, changedFiles);\n \n // 3. Strict evidence validation if EVIDENCE.json exists\n const evidencePath = path.join(cwd, \"EVIDENCE.json\");\n const hasEvidence = await fs.access(evidencePath).then(() => true).catch(() => false);\n if (hasEvidence) {\n const { EvidenceValidator } = await import(\"../../core/validation/evidence-validator.js\");\n const isTest = process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\";\n const evidenceValidator = new EvidenceValidator({ cwd, skipFileCheck: isTest, skipGitCheck: isTest });\n const valResult = await evidenceValidator.validate();\n if (!valResult.valid) {\n console.error(`\\n[FAST-TRACK BLOCKED] EVIDENCE.json validation failed: ${valResult.reason}`);\n finalStatus = \"FAIL_QUALITY_GATE\";\n }\n }\n } else if (!integrity.valid) {\n console.log(`\\n[FINALIZER BLOCKED] BLOCKED: workspace did not stabilize`);\n console.log(`Final changes detected:`, integrity.changes);\n finalStatus = \"FAIL_QUALITY_GATE\";\n } else {\n // Workspace stabilized, now run Artifact Fidelity Gate\n const fidelityResult = await finalizer.verifyFidelity({\n userRequest: naturalRequest,\n projectContext: result.evidence?.deliveryDecision?.projectContext || null,\n deliveryDecision: result.evidence?.deliveryDecision || null,\n changedFiles: result.evidence?.changedFiles || [],\n evidence: result.evidence || null,\n explicitApprovals: process.env.AI_WORKFLOW_APPROVALS ? process.env.AI_WORKFLOW_APPROVALS.split(\",\").map(a => a.trim()) : []\n });\n if (!fidelityResult.passed) {\n console.log(`\\n[FINALIZER BLOCKED] BLOCKED: Artifact fidelity check failed!`);\n console.log(`Reason: ${fidelityResult.reason}`);\n finalStatus = \"FAIL_QUALITY_GATE\";\n }\n }\n\n const finalState = finalStatus === \"PASS\"\n ? \"COMPLETED\"\n : finalStatus === \"PASS_WITH_NOTES\"\n ? \"COMPLETED_WITH_NOTES\"\n : \"BLOCKED\";\n\n stateMachine.transitionTo(finalState);\n\n // 10. Generate Handoff\n const handoffPath = await generateFinalHandoff(plan, taskSlug, cwd, finalState, result.evidence);\n\n return { ...result, overallStatus: finalStatus, stateHistory: stateMachine.getHistory() };\n } finally {\n if (plan && !plan.branchNeeded) {\n console.log(`\\n[READ-ONLY LEDGER] (In-Memory/Stdout)\\n${JSON.stringify(ledger.getEvents(), null, 2)}\\n`);\n } else {\n try {\n await ledger.save(`.ai-workflow/history/${taskSlug}-ledger.json`);\n } catch (err) {\n // ignore or log\n }\n }\n }\n}\n","import { existsSync, rmSync, lstatSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport readline from \"node:readline\";\n\ninterface CleanOptions {\n cwd: string;\n yes?: boolean;\n dryRun?: boolean;\n purgeAgents?: boolean;\n}\n\nfunction askConfirmation(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim().toLowerCase());\n });\n });\n}\n\nfunction isSymlink(filePath: string): boolean {\n try {\n return lstatSync(filePath).isSymbolicLink();\n } catch (_) {\n return false;\n }\n}\n\nexport async function runClean({ cwd, yes = false, dryRun = false, purgeAgents = false }: CleanOptions): Promise<void> {\n const targets = [\n \".ai-workflow\",\n \"opencode.jsonc\",\n \".workflow-state.json\",\n \"opencode\"\n ];\n\n const hasAgents = existsSync(join(cwd, \".agents\"));\n\n // Check what actually exists\n const existingTargets = targets\n .map(name => join(cwd, name))\n .filter(path => existsSync(path) || isSymlink(path));\n\n if (existingTargets.length === 0 && (!hasAgents || !purgeAgents)) {\n console.log(\"No AI Workflow configuration or files found in the current project.\");\n return;\n }\n\n console.log(\"\\n[AI WORKFLOW] De-initialization\");\n console.log(\"===============================\");\n\n if (dryRun) {\n console.log(\"[DRY RUN] The following items would be deleted:\");\n existingTargets.forEach(path => console.log(` - ${path}`));\n if (hasAgents && purgeAgents) {\n console.log(` - ${join(cwd, \".agents\")} (customizations folder)`);\n } else if (hasAgents) {\n console.log(` - NOTE: ${join(cwd, \".agents\")} exists but will NOT be deleted (run with --purge-agents to delete)`);\n }\n return;\n }\n\n // Interactive prompts if --yes / -y is not passed\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.log(\"Error: Non-interactive terminal detected. Run with --yes to bypass confirmation.\");\n if (process.env.NODE_ENV === \"test\") {\n // Allow tests to bypass TTY block if they mock/stub process.stdin\n } else {\n process.exit(1);\n }\n }\n\n const confirmDeinit = await askConfirmation(\"Are you sure you want to de-initialize AI Workflow from the project? [y/N] \");\n if (confirmDeinit !== \"y\" && confirmDeinit !== \"yes\") {\n console.log(\"Aborted.\");\n return;\n }\n\n if (hasAgents && !purgeAgents) {\n const confirmPurge = await askConfirmation(\"A custom '.agents' folder was detected. Do you want to purge it (this deletes custom prompts/rules/skills)? [y/N] \");\n if (confirmPurge === \"y\" || confirmPurge === \"yes\") {\n purgeAgents = true;\n }\n }\n }\n\n // Add .agents if requested and exists\n if (purgeAgents && hasAgents) {\n existingTargets.push(join(cwd, \".agents\"));\n }\n\n console.log(\"\\nRemoving files...\");\n for (const target of existingTargets) {\n try {\n if (isSymlink(target)) {\n unlinkSync(target);\n console.log(`Deleted symlink: ${target}`);\n } else {\n rmSync(target, { recursive: true, force: true });\n console.log(`Deleted directory/file: ${target}`);\n }\n } catch (error: any) {\n console.error(`Failed to delete ${target}: ${error.message}`);\n }\n }\n\n console.log(\"\\nAI Workflow has been successfully removed from this project.\");\n}\n","import { getPackageVersion } from \"../core/package-assets.js\";\nimport { runInit } from \"./commands/init.js\";\nimport { runDoctor } from \"./commands/doctor.js\";\nimport { runCollectEvidence } from \"./commands/collect-evidence.js\";\nimport { runMasterOrchestrator } from \"./commands/run.js\";\nimport { runExecute } from \"./commands/execute.js\";\nimport { runClean } from \"./commands/clean.js\";\n\nfunction printHelp() {\n console.log(`ai-workflow\n\nUsage:\n ai-workflow execute \"<request>\" [--task=<slug>] [--request=\"<request>\"]\n ai-workflow run --spec-path=<path>\n ai-workflow init [--yes] [--force] [--dry-run] [--no-install] [--no-overwrite] [--claude] [--codex] [--antigravity] [--profile=<profile>]\n ai-workflow validate [--a11y] [--visual-dist=<path>] [--port=<port>]\n ai-workflow collect-evidence [--task=<slug>] [--evidence-policy=<optional|required>] [--mode=<quick|standard|full>] [--dry-run] [--visual-dist=<path>] [--port=<port>]\n ai-workflow doctor\n ai-workflow clean [--yes] [--dry-run] [--purge-agents]\n\nCommands:\n execute Orchestrate execution of a natural request through the state machine\n run Proportionate orchestrator with branch safety, validation, and bounded remediation\n init Install AI workflow defaults (OpenCode). --profile=standard (default) or --profile=full (adds examples)\n collect-evidence Run observed project validation; persists EVIDENCE.json under required evidence policy\n doctor Verify local ai-workflow installation\n clean De-initialize and remove AI Workflow files and symlinks from the project\n`);\n}\n\ninterface ParsedFlags {\n yes: boolean;\n force: boolean;\n dryRun: boolean;\n noInstall: boolean;\n noOverwrite: boolean;\n claude: boolean;\n codex: boolean;\n antigravity: boolean;\n \"dev-mode\": boolean;\n specPath?: string;\n profile?: string;\n taskSlug?: string;\n mode?: string;\n evidencePolicy?: \"optional\" | \"required\";\n request?: string;\n visualDist?: string;\n port?: string;\n a11y: boolean;\n purgeAgents?: boolean;\n}\n\nfunction parseFlags(args: string[]): ParsedFlags {\n const specPathArg = args.find((arg) => arg.startsWith(\"--spec-path=\"));\n const profileEqArg = args.find((arg) => arg.startsWith(\"--profile=\"));\n const taskArg = args.find((arg) => arg.startsWith(\"--task=\"));\n const modeArg = args.find((arg) => arg.startsWith(\"--mode=\"));\n const evidencePolicyArg = args.find((arg) => arg.startsWith(\"--evidence-policy=\"));\n const requestArg = args.find((arg) => arg.startsWith(\"--request=\"));\n const visualDistArg = args.find((arg) => arg.startsWith(\"--visual-dist=\"));\n const portArg = args.find((arg) => arg.startsWith(\"--port=\"));\n const profileIdx = args.indexOf(\"--profile\");\n const profileVal = profileEqArg\n ? profileEqArg.replace(\"--profile=\", \"\")\n : profileIdx >= 0 && profileIdx + 1 < args.length && !args[profileIdx + 1].startsWith(\"--\")\n ? args[profileIdx + 1]\n : undefined;\n\n return {\n yes: args.includes(\"--yes\"),\n force: args.includes(\"--force\"),\n dryRun: args.includes(\"--dry-run\"),\n noInstall: args.includes(\"--no-install\"),\n noOverwrite: args.includes(\"--no-overwrite\"),\n claude: args.includes(\"--claude\"),\n codex: args.includes(\"--codex\"),\n antigravity: args.includes(\"--antigravity\"),\n \"dev-mode\": args.includes(\"--dev-mode\"),\n specPath: specPathArg ? specPathArg.replace(\"--spec-path=\", \"\") : undefined,\n profile: profileVal || undefined,\n taskSlug: taskArg ? taskArg.replace(\"--task=\", \"\") : undefined,\n mode: modeArg ? modeArg.replace(\"--mode=\", \"\") : undefined,\n evidencePolicy: evidencePolicyArg ? (evidencePolicyArg.replace(\"--evidence-policy=\", \"\") as any) : undefined,\n request: requestArg ? requestArg.replace(\"--request=\", \"\") : undefined,\n visualDist: visualDistArg ? visualDistArg.replace(\"--visual-dist=\", \"\") : undefined,\n port: portArg ? portArg.replace(\"--port=\", \"\") : undefined,\n a11y: args.includes(\"--a11y\"),\n purgeAgents: args.includes(\"--purge-agents\") || args.includes(\"--purge\")\n };\n}\n\nexport async function runCli(args: string[]): Promise<void> {\n const [command] = args;\n\n if (command === \"--version\" || command === \"-v\") {\n console.log(getPackageVersion() || \"unknown\");\n return;\n }\n\n if (!command || command === \"--help\" || command === \"-h\") {\n printHelp();\n return;\n }\n\n if (command === \"execute\") {\n const flags = parseFlags(args.slice(1));\n const positionals = args.slice(1).filter((arg) => !arg.startsWith(\"-\"));\n const request = flags.request || positionals.join(\" \");\n const result = await runExecute({\n cwd: process.cwd(),\n naturalRequest: request,\n taskSlug: flags.taskSlug\n });\n if (result && (result.overallStatus === \"FAIL_QUALITY_GATE\" || result.overallStatus === \"BLOCKED\" || result.overallStatus === \"FAIL\")) {\n process.exit(1);\n }\n return;\n }\n\n if (command === \"run\") {\n await runMasterOrchestrator({\n cwd: process.cwd(),\n ...parseFlags(args.slice(1))\n });\n return;\n }\n\n if (command === \"init\") {\n await runInit({\n cwd: process.cwd(),\n ...parseFlags(args.slice(1))\n });\n return;\n }\n\n if (command === \"collect-evidence\") {\n const flags = parseFlags(args.slice(1));\n if (flags.mode && ![\"quick\", \"standard\", \"full\"].includes(flags.mode)) throw new Error(\"--mode must be quick, standard, or full\");\n await runCollectEvidence({ \n cwd: process.cwd(), \n taskSlug: flags.taskSlug, \n mode: flags.mode, \n evidencePolicy: flags.evidencePolicy,\n dryRun: flags.dryRun,\n visualDist: flags.visualDist,\n port: flags.port\n });\n return;\n }\n\n if (command === \"validate\") {\n const flags = parseFlags(args.slice(1));\n const { runValidate } = await import(\"./commands/validate.js\");\n await runValidate({\n cwd: process.cwd(),\n taskSlug: flags.taskSlug,\n a11y: flags.a11y,\n visualDist: flags.visualDist,\n port: flags.port\n });\n return;\n }\n\n if (command === \"doctor\") {\n await runDoctor({ cwd: process.cwd() });\n return;\n }\n\n if (command === \"clean\") {\n await runClean({\n cwd: process.cwd(),\n ...parseFlags(args.slice(1))\n });\n return;\n }\n\n throw new Error(`unknown command: ${command}`);\n}\n\nrunCli(process.argv.slice(2)).catch((error) => {\n console.error(`ai-workflow error: ${error.message}`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,SAAQ;AACf,OAAOC,WAAU;;;ACDjB,OAAO,UAAU;;;ACGjB,IAAM,eAAuC;AAAA,EAC3C,sBAAsB;AAAA;AAAA;AAAA;AAAA;AACxB;AAEA,IAAM,sBAAgC;AAAA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M;AAAA,MAChB,MAAM,MAAM;AAAA,MACZ,YAAY,MAAM;AAAA,MAClB,MAAM,MAAM;AAAA,IACd,CAAC;AACD;AAAA,EACF;AAEA,MAAI,YAAY,UAAU;AACxB,UAAM,UAAU,EAAE,KAAK,QAAQ,IAAI,EAAE,CAAC;AACtC;AAAA,EACF;AAEA,MAAI,YAAY,SAAS;AACvB,UAAM,SAAS;AAAA,MACb,KAAK,QAAQ,IAAI;AAAA,MACjB,GAAG,WAAW,KAAK,MAAM,CAAC,CAAC;AAAA,IAC7B,CAAC;AACD;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,oBAAoB,OAAO,EAAE;AAC/C;AAEA,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,UAAU;AAC7C,UAAQ,MAAM,sBAAsB,MAAM,OAAO,EAAE;AACnD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["fs","path","exists","path","fs","path","path","fs","path","path","fs","path","exists","fs","path","fs","path","fs","path","fs","path","fs","path","fs","path","path","fs","next","fs","path","fs","path","execSync","fs","path","path","fs","path","fs","fs","path","execSync","getChangedFiles","fs","path","execSync","combineValidation","valResult","isSymlink","path"]}
1
+ {"version":3,"sources":["../../src/cli/commands/init.ts","../../src/core/install-plan.ts","../../src/core/templates.ts","../../src/core/filesystem.ts","../../src/core/backup.ts","../../src/core/opencode-merge.ts","../../src/core/symlink-layout.ts","../../src/adapters/platforms/claude.ts","../../src/adapters/platforms/codex.ts","../../src/adapters/platforms/antigravity.ts","../../src/cli/commands/doctor.ts","../../src/core/validation/canonical-finalization.ts","../../src/cli/commands/collect-evidence.ts","../../src/core/healing/cli-remediation-executor.ts","../../src/cli/commands/run.ts","../../src/core/healing/runtime-remediation-executor.ts","../../src/cli/commands/execute.ts","../../src/cli/commands/clean.ts","../../src/cli/index.ts"],"sourcesContent":["import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createInstallPlan } from \"../../core/install-plan.js\";\nimport { buildAiWorkflowConfig, getTemplateFiles, isValidProfile } from \"../../core/templates.js\";\nimport { exists, writeFileSafe, readJson } from \"../../core/filesystem.js\";\nimport { createManagedBackup, createManagedPathBackup } from \"../../core/backup.js\";\nimport { mergeOpencodeConfig } from \"../../core/opencode-merge.js\";\nimport { buildSymlinkEntries, isSymlinkTo, setupInternalSymlinks } from \"../../core/symlink-layout.js\";\nimport { ClaudeAdapter, CodexAdapter, AntigravityAdapter } from \"../../adapters/index.js\";\n\nfunction summarize(actions: any[]) {\n const createCount = actions.filter((a) => a.type === \"create\").length;\n const conflictCount = actions.filter((a) => a.type === \"conflict\").length;\n\n return { createCount, conflictCount };\n}\n\nfunction printPlan(actions: any[]) {\n for (const action of actions) {\n console.log(`- ${action.type.padEnd(8)} ${action.relativePath}`);\n }\n}\n\nfunction toIgnoreEntries(linkPath: string): string[] {\n if (linkPath === \"README.workflow.md\") {\n return [linkPath];\n }\n\n const normalized = linkPath.endsWith(\"/\") ? linkPath.slice(0, -1) : linkPath;\n return [normalized, `${normalized}/`];\n}\n\nfunction buildGitignoreBlock(entries: string[]): string {\n const unique = Array.from(new Set(entries));\n const sorted = unique.sort((a, b) => a.localeCompare(b));\n\n return [\n \"# BEGIN AI WORKFLOW KIT\",\n \"# AI Workflow Kit generated files\",\n ...sorted,\n \"# END AI WORKFLOW KIT\"\n ].join(\"\\n\");\n}\n\nasync function upsertGitignoreBlock(cwd: string, entries: string[]): Promise<string> {\n const gitignorePath = path.join(cwd, \".gitignore\");\n const block = buildGitignoreBlock(entries);\n const beginMarker = \"# BEGIN AI WORKFLOW KIT\";\n const endMarker = \"# END AI WORKFLOW KIT\";\n\n const hasGitignore = await exists(gitignorePath);\n if (!hasGitignore) {\n await writeFileSafe(gitignorePath, `${block}\\n`);\n return \"created\";\n }\n\n const current = await fs.readFile(gitignorePath, \"utf8\");\n const beginIndex = current.indexOf(beginMarker);\n const endIndex = current.indexOf(endMarker);\n\n if (beginIndex >= 0 && endIndex > beginIndex) {\n const before = current\n .slice(0, beginIndex)\n .replace(/\\n?# AI Workflow Kit generated files\\n?$/, \"\\n\")\n .replace(/[ \\t]+$/gm, \"\")\n .replace(/\\n*$/, \"\\n\");\n const afterStart = endIndex + endMarker.length;\n const after = current.slice(afterStart).replace(/^\\n*/, \"\\n\");\n const next = `${before}${block}${after}`;\n if (next !== current) {\n await writeFileSafe(gitignorePath, next);\n return \"updated\";\n }\n return \"unchanged\";\n }\n\n const separator = current.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = `${current}${separator}${block}\\n`;\n await writeFileSafe(gitignorePath, next);\n return \"updated\";\n}\n\nasync function injectScripts(cwd: string): Promise<boolean> {\n const pkgPath = path.join(cwd, \"package.json\");\n if (!(await exists(pkgPath))) return false;\n\n try {\n const pkg = await readJson(pkgPath);\n if (!pkg.scripts) pkg.scripts = {};\n\n if (!pkg.scripts.validate) {\n pkg.scripts.validate = \"ai-workflow collect-evidence\";\n await writeFileSafe(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n return true;\n }\n } catch {\n // Ignore invalid package.json\n }\n return false;\n}\n\nexport interface InitOptions {\n cwd: string;\n yes?: boolean;\n force?: boolean;\n dryRun?: boolean;\n noInstall?: boolean;\n noOverwrite?: boolean;\n claude?: boolean;\n codex?: boolean;\n antigravity?: boolean;\n \"dev-mode\"?: boolean;\n profile?: string;\n}\n\nasync function verifySelfExecutionGuard(cwd: string, devMode?: boolean): Promise<void> {\n if (!devMode) {\n try {\n const pkgPath = path.join(cwd, \"package.json\");\n if (await exists(pkgPath)) {\n const pkg = await readJson(pkgPath);\n if (pkg.name === \"@williambeto/ai-workflow\") {\n console.error(\"\\nFATAL: Cannot run 'ai-workflow init' inside its own development repository.\");\n console.error(\"This would corrupt the development environment. Aborting.\");\n console.error(\"Use the --dev-mode flag if you are developing the kit itself and need to test the init command.\\n\");\n process.exit(1);\n }\n }\n } catch {\n // Ignore if package.json is unreadable. The guard is a safety net.\n }\n }\n}\n\nfunction resolveProfile(profile?: string): string {\n const selectedProfile = profile || \"standard\";\n if (!isValidProfile(selectedProfile)) {\n console.error(`Invalid profile: \"${selectedProfile}\". Valid profiles: standard, full`);\n process.exit(1);\n }\n return selectedProfile;\n}\n\nasync function writeInstallFiles(\n cwd: string,\n actions: any[],\n selectedProfile: string,\n force?: boolean,\n noOverwrite?: boolean,\n backupRoot = \".ai-workflow-backups\"\n): Promise<{ skipped: string[]; backups: string[] }> {\n const skipped: string[] = [];\n const backups: string[] = [];\n\n for (const action of actions) {\n if (action.type === \"conflict\" && (noOverwrite || !force)) {\n skipped.push(action.relativePath);\n continue;\n }\n\n if (action.type === \"conflict\" && force) {\n const backupPath = await createManagedBackup(action.absolutePath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n backups.push(backupPath);\n }\n\n const content =\n action.relativePath === \".ai-workflow/config.json\"\n ? `${JSON.stringify(buildAiWorkflowConfig({ profile: selectedProfile }), null, 2)}\\n`\n : action.content;\n\n await writeFileSafe(action.absolutePath, content || \"\");\n }\n\n return { skipped, backups };\n}\n\nasync function writeSymlinks(\n cwd: string,\n linkEntries: any[],\n force?: boolean,\n backupRoot = \".ai-workflow-backups\"\n): Promise<{ linkBackups: string[]; linkCreated: string[] }> {\n const linkBackups: string[] = [];\n const linkCreated: string[] = [];\n\n for (const { linkPath, targetPath } of linkEntries) {\n const absoluteLinkPath = path.join(cwd, linkPath);\n const absoluteTargetPath = path.join(cwd, targetPath);\n\n if (!(await exists(absoluteTargetPath))) {\n throw new Error(`missing link target: ${targetPath}`);\n }\n\n if (await isSymlinkTo(absoluteLinkPath, absoluteTargetPath)) {\n continue;\n }\n\n if (await exists(absoluteLinkPath)) {\n if (!force) {\n throw new Error(\n `cannot create symlink '${linkPath}' because path already exists. Re-run with --force to backup and replace. If symlink creation fails, see troubleshooting in docs/npm-consumer-quickstart.md.`\n );\n }\n const backupPath = await createManagedPathBackup(absoluteLinkPath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n linkBackups.push(backupPath);\n await fs.rm(absoluteLinkPath, { recursive: true, force: true });\n }\n\n const stat = await fs.lstat(absoluteTargetPath);\n const type = process.platform === \"win32\"\n ? (stat.isDirectory() ? \"junction\" : \"file\")\n : (stat.isDirectory() ? \"dir\" : \"file\");\n const linkTarget = process.platform === \"win32\"\n ? absoluteTargetPath\n : path.relative(path.dirname(absoluteLinkPath), absoluteTargetPath);\n\n try {\n await fs.mkdir(path.dirname(absoluteLinkPath), { recursive: true });\n await fs.symlink(linkTarget, absoluteLinkPath, type);\n } catch (error: any) {\n throw new Error(\n `failed to create symlink '${linkPath}' -> '${targetPath}' (${error.message}). ` +\n \"For Windows, enable Developer Mode or run terminal as Administrator. \" +\n \"For Linux/macOS, verify write permissions in project root.\"\n );\n }\n linkCreated.push(linkPath);\n }\n\n return { linkBackups, linkCreated };\n}\n\nasync function executePlatformMigrations(\n cwd: string,\n installRoot: string,\n platforms: string[],\n claude?: boolean,\n codex?: boolean,\n antigravity?: boolean\n): Promise<void> {\n if (platforms.length === 0) return;\n\n console.log(\"ai-workflow: migrating to native platforms...\");\n const agentsDir = path.join(cwd, installRoot, \"opencode/agents\");\n const skillsDir = path.join(cwd, installRoot, \"opencode/skills\");\n\n const agentFiles = (await fs.readdir(agentsDir).catch(() => []))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => path.join(agentsDir, f));\n\n if (claude) {\n const adapter = new ClaudeAdapter({ cwd });\n await adapter.deploy(installRoot);\n console.log(\"- claude: deployed AI Workflow Kit agents to CLAUDE.md and .claude/rules/ (native discovery enabled)\");\n }\n\n if (codex) {\n const adapter = new CodexAdapter({ cwd });\n await adapter.deploy(installRoot);\n console.log(\"- codex: deployed AI Workflow Kit agents to .agents/, .codex/, and .github/ (native discovery enabled)\");\n }\n\n if (antigravity) {\n const adapter = new AntigravityAdapter({ cwd });\n const skillFolders = await fs.readdir(skillsDir).catch(() => []);\n const skillFiles: string[] = [];\n for (const folder of skillFolders) {\n const skillPath = path.join(skillsDir, folder, \"SKILL.md\");\n if (await exists(skillPath)) {\n skillFiles.push(skillPath);\n }\n }\n\n const allFiles = [...agentFiles, ...skillFiles];\n const transformed = await Promise.all(allFiles.map((f) => adapter.transform(f)));\n await adapter.deploy(transformed, installRoot);\n console.log(`- antigravity: deployed AI Workflow Kit agents to .agents/ (native discovery enabled)`);\n }\n}\n\nfunction printInstallationSummary({\n selectedProfile,\n opencodeResult,\n gitignoreResult,\n scriptInjected,\n linkCreated,\n backups,\n linkBackups,\n skipped,\n noInstall\n}: {\n selectedProfile: string;\n opencodeResult: any;\n gitignoreResult: string;\n scriptInjected: boolean;\n linkCreated: string[];\n backups: string[];\n linkBackups: string[];\n skipped: string[];\n noInstall?: boolean;\n}): void {\n console.log(\"Installation complete.\");\n console.log(`- profile: ${selectedProfile}`);\n console.log(`- opencode.jsonc: ${opencodeResult.reason}`);\n console.log(`- .gitignore: ${gitignoreResult}`);\n console.log(`- scripts: ${scriptInjected ? \"injected 'validate'\" : \"already-up-to-date\"}`);\n console.log(`- symlink layout: ${linkCreated.length > 0 ? `created ${linkCreated.length}` : \"already-up-to-date\"}`);\n\n if (backups.length > 0) {\n console.log(`- backups created: ${backups.length}`);\n for (const filePath of backups) {\n console.log(` ${filePath}`);\n }\n }\n if (linkBackups.length > 0) {\n console.log(`- symlink backups created: ${linkBackups.length}`);\n for (const filePath of linkBackups) {\n console.log(` ${filePath}`);\n }\n }\n if (skipped.length > 0) {\n console.log(`- conflicts skipped: ${skipped.length}`);\n for (const relativePath of skipped) {\n console.log(` ${relativePath}`);\n }\n }\n console.log(`- dependency install: ${noInstall ? \"skipped (--no-install)\" : \"not managed in this step\"}`);\n console.log(\"Next steps:\");\n console.log(\" npx @williambeto/ai-workflow doctor\");\n}\n\nexport async function runInit({\n cwd, yes, force, dryRun, noInstall, noOverwrite, claude, codex, antigravity, \"dev-mode\": devMode, profile\n}: InitOptions): Promise<void> {\n await verifySelfExecutionGuard(cwd, devMode);\n\n const selectedProfile = resolveProfile(profile);\n const installRoot = \".ai-workflow\";\n const backupRoot = \".ai-workflow-backups\";\n\n const platforms: string[] = [];\n if (claude) platforms.push(\"claude\");\n if (codex) platforms.push(\"codex\");\n if (antigravity) platforms.push(\"antigravity\");\n\n console.log(`ai-workflow: initializing in ${cwd}`);\n console.log(`Profile: ${selectedProfile}`);\n if (platforms.length > 0) {\n console.log(`Platforms: ${platforms.join(\", \")}`);\n }\n\n const actions = await createInstallPlan({ cwd, exists, profile: selectedProfile });\n const linkEntries = buildSymlinkEntries({ templateFiles: getTemplateFiles(selectedProfile), installRoot });\n const { createCount, conflictCount } = summarize(actions);\n\n console.log(`Plan: ${createCount} create, ${conflictCount} conflict`);\n printPlan(actions);\n\n if (!yes && conflictCount > 0 && !force && !noOverwrite) {\n throw new Error(\n \"conflicts detected. Re-run with --force to replace managed files or resolve conflicts manually\"\n );\n }\n\n if (dryRun) {\n console.log(\"Dry-run enabled. No files were written.\");\n if (platforms.length > 0) {\n console.log(\"ai-workflow: (dry-run) platform migration would be executed after file writing.\");\n }\n return;\n }\n\n const { skipped, backups } = await writeInstallFiles(cwd, actions, selectedProfile, force, noOverwrite, backupRoot);\n const { linkBackups, linkCreated } = await writeSymlinks(cwd, linkEntries, force, backupRoot);\n\n await setupInternalSymlinks(cwd, installRoot);\n\n const opencodeResult = await mergeOpencodeConfig(cwd, { force, backupRoot });\n\n const generatedIgnoreEntries = [\n \"node_modules/\",\n \".ai-workflow/\",\n \".ai-workflow-backups/\",\n \"opencode.jsonc.backup.*\",\n \"EVIDENCE.json\",\n \"*.tgz\",\n ...linkEntries.flatMap((entry) => toIgnoreEntries(entry.linkPath))\n ];\n\n if (codex) {\n generatedIgnoreEntries.push(\".agents/\", \".codex/\");\n }\n if (claude) {\n generatedIgnoreEntries.push(\".claude/\");\n }\n if (antigravity) {\n generatedIgnoreEntries.push(\".agents/\");\n }\n\n const gitignoreResult = await upsertGitignoreBlock(cwd, generatedIgnoreEntries);\n const scriptInjected = await injectScripts(cwd);\n\n await executePlatformMigrations(cwd, installRoot, platforms, claude, codex, antigravity);\n\n printInstallationSummary({\n selectedProfile,\n opencodeResult,\n gitignoreResult,\n scriptInjected,\n linkCreated,\n backups,\n linkBackups,\n skipped,\n noInstall\n });\n}\n","import path from \"node:path\";\nimport { getTemplateFiles } from \"./templates.js\";\n\nexport interface InstallAction {\n type: \"conflict\" | \"create\";\n relativePath: string;\n absolutePath: string;\n content: string | null;\n}\n\nexport interface CreateInstallPlanOptions {\n cwd: string;\n exists: (filePath: string) => Promise<boolean> | boolean;\n profile?: string;\n}\n\nexport async function createInstallPlan({\n cwd,\n exists,\n profile = \"standard\"\n}: CreateInstallPlanOptions): Promise<InstallAction[]> {\n const actions: InstallAction[] = [];\n const templateFiles = getTemplateFiles(profile);\n const installRoot = \".ai-workflow\";\n\n for (const [relativePath, content] of Object.entries(templateFiles)) {\n if (relativePath === \"opencode.jsonc\") {\n continue;\n }\n\n const installedRelativePath = path.join(installRoot, relativePath);\n const absolutePath = path.join(cwd, installedRelativePath);\n const action = (await exists(absolutePath)) ? \"conflict\" : \"create\";\n actions.push({\n type: action,\n relativePath: installedRelativePath,\n absolutePath,\n content\n });\n }\n\n const configPath = path.join(cwd, \".ai-workflow/config.json\");\n actions.push({\n type: (await exists(configPath)) ? \"conflict\" : \"create\",\n relativePath: \".ai-workflow/config.json\",\n absolutePath: configPath,\n content: null\n });\n\n return actions;\n}\n","import { getFullAgentContent, getFullSkillFiles, discoverPackageFiles, readPackageFile, getPackageVersion } from \"./package-assets.js\";\nimport { getCanonicalAgentName } from \"./identity.js\";\n\nconst COMMON_FILES: Record<string, string> = {\n \"opencode/README.md\": `# OpenCode Setup\\n\\nThis directory is managed by \\`ai-workflow\\` init.\\nAdd agent and command files required by your project workflow.\\n`\n};\n\nconst FULL_PRIMARY_AGENTS: string[] = [\n \"atlas\",\n \"nexus\",\n \"orion\",\n \"astra\",\n \"sage\",\n \"phoenix\"\n];\n\nconst FULL_SKILLS: string[] = [\n \"project-memory\",\n \"optimize-tokens\",\n \"documentation\",\n \"architecture\",\n \"technical-leadership\",\n \"product-discovery\",\n \"product-planning\",\n \"spec-driven-development\",\n \"pr-workflow\",\n \"qa-workflow\",\n \"release-workflow\",\n \"deployment\",\n \"ui-ux-design\",\n \"design-principles\",\n \"frontend-development\",\n \"backend-development\",\n \"full-stack-development\",\n \"refactoring\",\n \"prompt-engineer\"\n];\n\nfunction buildRuntimeFiles({ includeFormalEvidence = false }: { includeFormalEvidence?: boolean } = {}): Record<string, string> {\n const files: Record<string, string> = {};\n\n for (const agent of FULL_PRIMARY_AGENTS) {\n const content = getFullAgentContent(agent);\n if (content === null) {\n throw new Error(`CRITICAL FAILURE: Missing required agent asset: dist-assets/agents/${agent}.md`);\n }\n files[`opencode/agents/${agent}.md`] = content;\n }\n\n for (const skill of FULL_SKILLS) {\n const skillFiles = getFullSkillFiles(skill);\n if (Object.keys(skillFiles).length === 0) {\n continue;\n }\n for (const [relPath, content] of Object.entries(skillFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n }\n\n // Copy governance policy into opencode/docs/policies/ so the relative link\n // ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md resolves correctly from\n // opencode/skills/{skill}/SKILL.md for OpenCode and all platform adapters.\n const opencodeGovernancePolicy = readPackageFile(\"dist-assets/docs/policies/SKILLS_COMMON_GOVERNANCE.md\");\n if (opencodeGovernancePolicy !== null) {\n files[\"opencode/docs/policies/SKILLS_COMMON_GOVERNANCE.md\"] = opencodeGovernancePolicy;\n }\n\n const commandFiles = discoverPackageFiles(\"dist-assets/commands\");\n for (const [relPath, content] of Object.entries(commandFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n\n const opencodeSkillFiles = discoverPackageFiles(\"dist-assets/skills\");\n for (const [relPath, content] of Object.entries(opencodeSkillFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n\n const harnessWorkflowFiles = discoverPackageFiles(\"dist-assets/harness/workflows\");\n for (const [relPath, content] of Object.entries(harnessWorkflowFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const harnessHandoffFiles = discoverPackageFiles(\"dist-assets/harness/handoffs\");\n for (const [relPath, content] of Object.entries(harnessHandoffFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const agentsContent = readPackageFile(\"dist-assets/AGENTS.md\");\n if (agentsContent !== null) files[\"AGENTS.md\"] = agentsContent;\n\n const consumerQuickstart = readPackageFile(\"dist-assets/docs/QUICKSTART.md\");\n if (consumerQuickstart !== null) files[\"QUICKSTART.md\"] = consumerQuickstart;\n\n const policyContent = readPackageFile(\"dist-assets/docs/architecture-policy.md\");\n if (policyContent !== null) files[\"opencode/docs/architecture-policy.md\"] = policyContent;\n\n const dpContent = readPackageFile(\"dist-assets/docs/design-patterns-policy.md\");\n if (dpContent !== null) files[\"opencode/docs/design-patterns-policy.md\"] = dpContent;\n\n const visualValidationGuide = readPackageFile(\"dist-assets/docs/visual-validation-guide.md\");\n if (visualValidationGuide !== null) files[\"opencode/docs/visual-validation-guide.md\"] = visualValidationGuide;\n\n const governancePolicies = discoverPackageFiles(\"dist-assets/docs/policies\");\n for (const [relPath, content] of Object.entries(governancePolicies)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const compatibilityDocs = discoverPackageFiles(\"dist-assets/docs/compatibility\");\n for (const [relPath, content] of Object.entries(compatibilityDocs)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const qualityReferenceFiles = discoverPackageFiles(\"dist-assets/docs/references\");\n for (const [relPath, content] of Object.entries(qualityReferenceFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const workflowProfileFiles = discoverPackageFiles(\"dist-assets/docs/profiles\");\n for (const [relPath, content] of Object.entries(workflowProfileFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const templateFiles = discoverPackageFiles(\"dist-assets/templates\");\n for (const [relPath, content] of Object.entries(templateFiles)) {\n if (!includeFormalEvidence && relPath.includes(\"/owner-evidence/\")) continue;\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const schemaFiles = discoverPackageFiles(\"dist-assets/schemas\");\n for (const [relPath, content] of Object.entries(schemaFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n return files;\n}\n\nfunction buildExtraFiles(): Record<string, string> {\n const files: Record<string, string> = {};\n const exampleFiles = discoverPackageFiles(\"dist-assets/examples\");\n for (const [relPath, content] of Object.entries(exampleFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n return files;\n}\n\nconst STANDARD_FILES = buildRuntimeFiles();\nconst FULL_FILES = { ...buildRuntimeFiles({ includeFormalEvidence: true }), ...buildExtraFiles() };\n\nexport const PROFILE_FILES: Record<string, Record<string, string>> = {\n standard: {\n ...COMMON_FILES,\n ...STANDARD_FILES\n },\n full: {\n ...COMMON_FILES,\n ...FULL_FILES\n }\n};\n\nexport function isValidProfile(profile: any): boolean {\n return profile === \"standard\" || profile === \"full\";\n}\n\nexport function getTemplateFiles(profile: string = \"standard\"): Record<string, string> {\n return PROFILE_FILES[profile] ?? PROFILE_FILES.standard;\n}\n\nexport function getManagedBlocks(): string[] {\n return [\n ...FULL_PRIMARY_AGENTS.map((agent) => `opencode.jsonc:agent.${getCanonicalAgentName(agent)}`),\n ...FULL_SKILLS.map((skill) => `opencode.jsonc:agent.${getCanonicalAgentName(skill)}`),\n \"opencode.jsonc:command.atlas\",\n \"opencode.jsonc:command.run\",\n \"opencode.jsonc:command.discover\",\n \"opencode.jsonc:command.spec-create\",\n \"opencode.jsonc:command.spec-review\",\n \"opencode.jsonc:command.spec-implement\",\n \"opencode.jsonc:command.plan\",\n \"opencode.jsonc:command.implement\",\n \"opencode.jsonc:command.validate\",\n \"opencode.jsonc:command.audit\",\n \"opencode.jsonc:command.optimize-tokens\",\n \"opencode.jsonc:command.update-memory\",\n \"opencode.jsonc:command.release\",\n \"opencode.jsonc:command.deploy\"\n ];\n}\n\nexport interface BuildAiWorkflowConfigOptions {\n profile: string;\n managedFiles?: any;\n managedLinks?: any[];\n}\n\nexport interface AiWorkflowConfig {\n package: string;\n version: string | null;\n runtime: string;\n profile: string;\n installMode: string;\n generatedAt: string;\n paths: {\n agents: string;\n commands: string;\n skills: string;\n policies: string;\n harness: string;\n schemas: string;\n };\n}\n\nexport function buildAiWorkflowConfig({ profile }: BuildAiWorkflowConfigOptions): AiWorkflowConfig {\n const version = getPackageVersion();\n const now = new Date().toISOString();\n\n return {\n package: \"@williambeto/ai-workflow\",\n version,\n runtime: \"opencode\",\n profile,\n installMode: \"project-local\",\n generatedAt: now,\n paths: {\n agents: \".ai-workflow/opencode/agents\",\n commands: \".ai-workflow/opencode/commands\",\n skills: \".ai-workflow/opencode/skills\",\n policies: \".ai-workflow/opencode/docs/policies\",\n harness: \".ai-workflow/harness\",\n schemas: \".ai-workflow/schemas\"\n }\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function exists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nimport { execSync } from \"node:child_process\";\n\n/**\n * Safe wrapper for writing files that enforces branch guards on protected branches.\n * NOTE: This branch guard only protects write operations performed through this kit wrapper\n * (or the kit's runtime executions). It does not intercept external shell commands or processes.\n */\nexport async function writeFileSafe(filePath: string, content: string): Promise<void> {\n const absolutePath = path.resolve(filePath);\n const repoCwd = path.resolve(process.cwd());\n const relativeToRepo = path.relative(repoCwd, absolutePath).replaceAll(\"\\\\\", \"/\");\n \n // Normalized precise allowlist\n const isOperational = relativeToRepo === \"EVIDENCE.json\" ||\n relativeToRepo.startsWith(\".ai-workflow/\") ||\n relativeToRepo.startsWith(\".ai-workflow\\\\\");\n \n if (!isOperational) {\n let currentBranch = \"\";\n const fileCwd = path.dirname(absolutePath);\n try {\n currentBranch = execSync(\"git branch --show-current\", { cwd: fileCwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n // ignore\n }\n const protectedBranches = [\"main\", \"master\"];\n const isInitCommand = process.argv.includes(\"init\");\n if (protectedBranches.includes(currentBranch) && !isInitCommand) {\n if (process.env.AI_WORKFLOW_BYPASS_PROTECTED_BRANCH !== \"true\") {\n throw new Error(\"FAIL_PROTECTED_BRANCH: Direct writes to protected branch are prohibited.\");\n }\n }\n }\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf8\");\n}\n\nexport async function readJson(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(content);\n}\n\nfunction stripJsonComments(content: string): string {\n let output = \"\";\n let inString = false;\n let quote = \"\";\n let escaped = false;\n let inLineComment = false;\n let inBlockComment = false;\n\n for (let index = 0; index < content.length; index += 1) {\n const char = content[index];\n const next = content[index + 1];\n\n if (inLineComment) {\n if (char === \"\\n\" || char === \"\\r\") {\n inLineComment = false;\n output += char;\n }\n continue;\n }\n\n if (inBlockComment) {\n if (char === \"*\" && next === \"/\") {\n inBlockComment = false;\n index += 1;\n continue;\n }\n if (char === \"\\n\" || char === \"\\r\") {\n output += char;\n }\n continue;\n }\n\n if (inString) {\n output += char;\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === quote) {\n inString = false;\n quote = \"\";\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n quote = char;\n output += char;\n continue;\n }\n\n if (char === \"/\" && next === \"/\") {\n inLineComment = true;\n index += 1;\n continue;\n }\n\n if (char === \"/\" && next === \"*\") {\n inBlockComment = true;\n index += 1;\n continue;\n }\n\n output += char;\n }\n\n return output;\n}\n\nfunction stripTrailingCommas(content: string): string {\n let output = \"\";\n let inString = false;\n let quote = \"\";\n let escaped = false;\n\n for (let index = 0; index < content.length; index += 1) {\n const char = content[index];\n\n if (inString) {\n output += char;\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === quote) {\n inString = false;\n quote = \"\";\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n quote = char;\n output += char;\n continue;\n }\n\n if (char === \",\") {\n let nextIndex = index + 1;\n while (/\\s/.test(content[nextIndex] ?? \"\")) {\n nextIndex += 1;\n }\n if (content[nextIndex] === \"}\" || content[nextIndex] === \"]\") {\n continue;\n }\n }\n\n output += char;\n }\n\n return output;\n}\n\nexport async function readJsonc(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(stripTrailingCommas(stripJsonComments(content)));\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { BackupOptions } from \"./types.js\";\n\nexport function buildBackupPath(filePath: string, now: Date = new Date()): string {\n const stamp = now.toISOString().replace(/[:.]/g, \"-\");\n return `${filePath}.bak.${stamp}`;\n}\n\nexport async function createBackup(filePath: string): Promise<string> {\n const backupPath = buildBackupPath(filePath);\n await fs.copyFile(filePath, backupPath);\n return backupPath;\n}\n\nfunction escapeRelativePath(relativePath: string): string {\n return relativePath.replace(/[\\\\/]/g, \"__\");\n}\n\nexport async function createManagedBackup(\n filePath: string,\n { cwd, backupRoot, maxPerFile = 20 }: BackupOptions\n): Promise<string> {\n const relativePath = path.relative(cwd, filePath);\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const backupName = `${escapeRelativePath(relativePath)}.${stamp}.bak`;\n const absoluteBackupRoot = path.join(cwd, backupRoot);\n const backupPath = path.join(absoluteBackupRoot, backupName);\n\n await fs.mkdir(absoluteBackupRoot, { recursive: true });\n await fs.copyFile(filePath, backupPath);\n\n const prefix = `${escapeRelativePath(relativePath)}.`;\n const entries = await fs.readdir(absoluteBackupRoot);\n const matching = entries\n .filter((entry) => entry.startsWith(prefix) && entry.endsWith(\".bak\"))\n .sort();\n\n if (matching.length > maxPerFile) {\n const excess = matching.slice(0, matching.length - maxPerFile);\n await Promise.all(excess.map((entry) => fs.unlink(path.join(absoluteBackupRoot, entry))));\n }\n\n return backupPath;\n}\n\nexport async function createManagedPathBackup(\n targetPath: string,\n { cwd, backupRoot, maxPerFile = 20 }: BackupOptions\n): Promise<string> {\n const relativePath = path.relative(cwd, targetPath);\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const backupName = `${escapeRelativePath(relativePath)}.${stamp}.bak`;\n const absoluteBackupRoot = path.join(cwd, backupRoot);\n const backupPath = path.join(absoluteBackupRoot, backupName);\n\n await fs.mkdir(absoluteBackupRoot, { recursive: true });\n await fs.rename(targetPath, backupPath);\n\n const prefix = `${escapeRelativePath(relativePath)}.`;\n const entries = await fs.readdir(absoluteBackupRoot);\n const matching = entries\n .filter((entry) => entry.startsWith(prefix) && entry.endsWith(\".bak\"))\n .sort();\n\n if (matching.length > maxPerFile) {\n const excess = matching.slice(0, matching.length - maxPerFile);\n await Promise.all(excess.map((entry) => fs.rm(path.join(absoluteBackupRoot, entry), { recursive: true, force: true })));\n }\n\n return backupPath;\n}\n","import path from \"node:path\";\nimport { exists, readJsonc, writeFileSafe } from \"./filesystem.js\";\nimport { createManagedBackup } from \"./backup.js\";\nimport { getTemplateFiles } from \"./templates.js\";\n\n/**\n * @file opencode-merge.ts\n * @description Architecture & Registry for OpenCode configuration synthesis (`opencode.jsonc`).\n *\n * ## Architecture Overview\n * This module is responsible for initializing, updating, and merging the project's\n * `opencode.jsonc` file when `aw init` is executed in a consumer repository.\n *\n * ### Core Responsibilities:\n * 1. **Primary Agents Registry (`AGENTS`)**: Defines the 6 core workflow actors (Atlas, Nexus, Orion, Astra, Sage, Phoenix)\n * and maps their instructions to `.ai-workflow/agents/<name>.md`.\n * 2. **Subagents Registry (`SUBAGENTS`)**: Registers domain-specific subagents mapped 1-to-1 with skills installed\n * in `.ai-workflow/skills/<skill>/SKILL.md`. These subagents can be activated by OpenCode runtimes.\n * 3. **Commands Registry (`COMMANDS`)**: Maps slash-commands (e.g. `/atlas`, `/spec-create`, `/validate`) to their respective agent owners.\n * 4. **Safe JSONC Merging**: Merges AIWK configuration blocks into consumer repositories while preserving existing custom user\n * settings in `opencode.jsonc` and managing backups.\n *\n * ### Registering a New Subagent:\n * To add a new subagent to the OpenCode runtime registry:\n * - Ensure a corresponding skill exists in `dist-assets/skills/<skill-name>/SKILL.md`.\n * - Add a new entry to the `SUBAGENTS` object with a PascalCase/Kebab name, a concise `description`, and the matching `skill` directory name.\n * - Note: 5 auxiliary skills (`cyber-security`, `database`, `devops`, `localization`, `performance`) are intentionally excluded\n * from subagent registration as they serve as contextual lenses for existing agents (see `dist-assets/AGENTS.md`).\n */\n\nconst LEGACY_MARKER = \"_aiWorkflowManaged\";\n\ninterface AgentDef {\n description: string;\n}\n\nconst AGENTS: Record<string, AgentDef> = {\n Atlas: { description: \"Router and workflow coordinator for AI Workflow Kit\" },\n Nexus: { description: \"Discovery, requirement, scope, and specification owner\" },\n Orion: { description: \"Planning, PR sequencing, release, and deployment strategy owner\" },\n Astra: { description: \"Implementation owner for incremental, scoped changes\" },\n Sage: { description: \"Audit, validation, evidence, and quality gate owner\" },\n Phoenix: { description: \"Remediation and regression recovery owner\" }\n};\n\ninterface SubagentDef {\n description: string;\n skill: string;\n}\n\nconst SUBAGENTS: Record<string, SubagentDef> = {\n \"Architecture-Specialist\": { description: \"Select the simplest architecture that safely satisfies current requirements\", skill: \"architecture\" },\n \"Backend-Engineer\": { description: \"Support safe PHP/Node/Python backend changes for APIs and persistence\", skill: \"backend-development\" },\n \"Deployment-Specialist\": { description: \"Plan, review, or validate deployment, release, and production-readiness\", skill: \"deployment\" },\n \"Design-Specialist\": { description: \"Apply practical design principles to keep solutions simple and maintainable\", skill: \"design-principles\" },\n \"Docs-Engineer\": { description: \"Write or improve project documentation, READMEs, guides, and prompts\", skill: \"documentation\" },\n \"Frontend-Engineer\": { description: \"Implement or review frontend changes involving UI, state, routing, and accessibility\", skill: \"frontend-development\" },\n \"Frontend-Design-System-Specialist\": { description: \"Enforce CSS/HTML tokens, semantic elements, typography, and premium atmosphere constraints for frontend quality\", skill: \"frontend-design-system\" },\n \"Full-Stack-Engineer\": { description: \"Coordinate frontend and backend changes as one coherent, testable increment\", skill: \"full-stack-development\" },\n \"Token-Economist\": { description: \"Reduce context size while preserving information required for safe execution\", skill: \"optimize-tokens\" },\n \"PR-Manager\": { description: \"Plan, implement, review, or validate small pull requests while preserving scope\", skill: \"pr-workflow\" },\n \"Discovery-Analyst\": { description: \"Clarify ambiguous requests into actionable problem statements and success outcomes\", skill: \"product-discovery\" },\n \"Product-Planner\": { description: \"Turn clarified needs into scoped requirements with acceptance-ready outcomes\", skill: \"product-planning\" },\n \"Memory-Guardian\": { description: \"Manage discoverable project memory for durable decisions and recurring corrections\", skill: \"project-memory\" },\n \"Prompt-Engineer\": { description: \"Expert in creating and refining prompts for AI agents and workflows\", skill: \"prompt-engineer\" },\n \"QA-Engineer\": { description: \"Design, review, or improve tests, acceptance criteria, and validation evidence\", skill: \"qa-workflow\" },\n \"Refactoring-Specialist\": { description: \"Improve code/document structure safely while preserving behavior\", skill: \"refactoring\" },\n \"Release-Specialist\": { description: \"Prepare release readiness decisions with explicit gates and evidence\", skill: \"release-workflow\" },\n \"SDD-Specialist\": { description: \"Convert approved requirements into explicit, testable specification artifacts\", skill: \"spec-driven-development\" },\n \"Technical-Leader\": { description: \"Make technical decisions, review architecture, and identify trade-offs\", skill: \"technical-leadership\" },\n \"UI-UX-Engineer\": { description: \"Improve usability and interface clarity without introducing unnecessary complexity\", skill: \"ui-ux-design\" }\n};\n\ninterface CommandDef {\n description: string;\n agent: string;\n}\n\nconst COMMANDS: Record<string, CommandDef> = {\n atlas: { description: \"Decide safest next step and delegate to the appropriate workflow or agent\", agent: \"Atlas\" },\n run: { description: \"Execute the master orchestration pipeline (Gates, SDD, Implementation, Validation, Healing)\", agent: \"Atlas\" },\n discover: { description: \"Understand the project, gather context, and create initial documentation\", agent: \"Nexus\" },\n \"spec-create\": { description: \"Create a clear specification before implementation\", agent: \"Nexus\" },\n \"spec-review\": { description: \"Review a specification and validate scope, risks, criteria, and gaps\", agent: \"Nexus\" },\n \"spec-implement\": { description: \"Implement an approved specification incrementally\", agent: \"Astra\" },\n plan: { description: \"Plan a task or change, defining steps, risks, and validation\", agent: \"Orion\" },\n implement: { description: \"Implement a small task with defined scope\", agent: \"Astra\" },\n validate: { description: \"Run project validations and collect evidence\", agent: \"Sage\" },\n audit: { description: \"Audit the project, identify issues, and suggest prioritized improvements\", agent: \"Sage\" },\n \"optimize-tokens\": { description: \"Analyze workflow and context usage; suggest reductions without losing quality or evidence\", agent: \"Sage\" },\n \"update-memory\": { description: \"Update durable project memory with relevant decisions, constraints, and reusable context\", agent: \"Nexus\" },\n release: { description: \"Prepare delivery with commit, push, PR/merge readiness, changelog, and evidence\", agent: \"Orion\" },\n deploy: { description: \"Publish the project to the defined environment after validation and release readiness\", agent: \"Orion\" }\n};\n\ninterface ManagedAgentConfig {\n mode: \"primary\" | \"subagent\";\n description: string;\n prompt: string;\n}\n\ninterface ManagedCommandConfig {\n description: string;\n agent: string;\n template: string;\n}\n\ninterface ManagedConfig {\n $schema: string;\n default_agent: string;\n agent: Record<string, ManagedAgentConfig>;\n skills: {\n paths: string[];\n };\n command: Record<string, ManagedCommandConfig>;\n mcp?: Record<string, any>;\n}\n\nfunction buildManagedConfig(): ManagedConfig {\n const agent: Record<string, ManagedAgentConfig> = {};\n for (const [name, def] of Object.entries(AGENTS)) {\n agent[name] = {\n mode: \"primary\",\n description: def.description,\n prompt: `{file:./.ai-workflow/opencode/agents/${name.toLowerCase()}.md}`\n };\n }\n\n for (const [name, def] of Object.entries(SUBAGENTS)) {\n agent[name] = {\n mode: \"subagent\",\n description: def.description,\n prompt: `{file:./.ai-workflow/opencode/skills/${def.skill}/SKILL.md}`\n };\n }\n\n const command: Record<string, ManagedCommandConfig> = {};\n for (const [name, def] of Object.entries(COMMANDS)) {\n command[name] = {\n description: def.description,\n agent: def.agent,\n template: `{file:./.ai-workflow/opencode/commands/${name}.md}`\n };\n }\n\n return {\n $schema: \"https://opencode.ai/config.json\",\n default_agent: \"Atlas\",\n agent,\n skills: {\n paths: [\"./.ai-workflow/opencode/skills\"]\n },\n command\n };\n}\n\nexport interface MergeOpencodeConfigOptions {\n force?: boolean;\n backupRoot?: string;\n}\n\nexport interface MergeOpencodeConfigResult {\n changed: boolean;\n reason: string;\n}\n\nexport async function mergeOpencodeConfig(\n cwd: string,\n { force = false, backupRoot = \".ai-workflow-backups\" }: MergeOpencodeConfigOptions = {}\n): Promise<MergeOpencodeConfigResult> {\n const targetPath = path.join(cwd, \"opencode.jsonc\");\n const managed = buildManagedConfig();\n\n if (!(await exists(targetPath))) {\n await writeFileSafe(targetPath, `${JSON.stringify(managed, null, 2)}\\n`);\n return { changed: true, reason: \"created\" };\n }\n\n let current: any;\n try {\n current = await readJsonc(targetPath);\n } catch {\n if (!force) {\n return { changed: false, reason: \"invalid-json (skipped)\" };\n }\n await createManagedBackup(targetPath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n await writeFileSafe(targetPath, `${JSON.stringify(managed, null, 2)}\\n`);\n return { changed: true, reason: \"invalid-json (replaced with --force)\" };\n }\n\n const { [LEGACY_MARKER]: _legacyManaged, ...currentWithoutLegacy } = current;\n\n const next = {\n ...currentWithoutLegacy,\n $schema: current.$schema ?? managed.$schema,\n ...(managed.mcp\n ? {\n mcp: {\n ...(current.mcp ?? {}),\n ...managed.mcp\n }\n }\n : {}),\n agent: {\n ...(current.agent ?? {}),\n ...managed.agent\n },\n command: {\n ...(current.command ?? {}),\n ...managed.command\n }\n };\n\n const changed = JSON.stringify(current) !== JSON.stringify(next);\n if (!changed) {\n return { changed: false, reason: \"already-up-to-date\" };\n }\n\n await writeFileSafe(targetPath, `${JSON.stringify(next, null, 2)}\\n`);\n return { changed: true, reason: \"merged-managed-sections\" };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nfunction normalize(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/**\n * For v3.0.0 \"Elite Governance\", we want an ULTRA-CLEAN root.\n * Only \"opencode\" is symlinked to the root (required for OpenCode discovery).\n * All other assets stay inside .ai-workflow/.\n */\nconst LINKABLE_ROOTS = new Set([\n \"opencode\",\n \".agents\"\n]);\n\nconst LINKABLE_FILES = new Set<string>([]);\n\nexport interface BuildSymlinkEntriesOptions {\n templateFiles: Record<string, string>;\n installRoot?: string;\n}\n\nexport interface SymlinkEntry {\n linkPath: string;\n targetPath: string;\n}\n\nexport function buildSymlinkEntries({ templateFiles, installRoot = \".ai-workflow\" }: BuildSymlinkEntriesOptions): SymlinkEntry[] {\n const entries = new Map<string, string>();\n\n for (const relativePath of Object.keys(templateFiles)) {\n if (relativePath === \"opencode.jsonc\") continue;\n\n const normalized = normalize(relativePath);\n\n if (LINKABLE_FILES.has(normalized)) {\n entries.set(normalized, `${installRoot}/${normalized}`);\n continue;\n }\n\n // Match composite paths in LINKABLE_ROOTS (e.g., \"docs/policies\")\n for (const rootPath of LINKABLE_ROOTS) {\n if (normalized === rootPath || normalized.startsWith(`${rootPath}/`)) {\n entries.set(rootPath, `${installRoot}/${rootPath}`);\n break;\n }\n }\n }\n\n return Array.from(entries.entries()).map(([linkPath, targetPath]) => ({ linkPath, targetPath }));\n}\n\nexport async function isSymlinkTo(absoluteLinkPath: string, absoluteTargetPath: string): Promise<boolean> {\n try {\n const stat = await fs.lstat(absoluteLinkPath);\n if (!stat.isSymbolicLink()) return false;\n const currentTarget = await fs.readlink(absoluteLinkPath);\n const resolved = path.resolve(path.dirname(absoluteLinkPath), currentTarget);\n return resolved === absoluteTargetPath;\n } catch {\n return false;\n }\n}\n\n/**\n * Internal symlink to satisfy opencode.jsonc paths without polluting the root.\n * Creates .ai-workflow/opencode/skills -> ../.agents/skills\n */\nexport async function setupInternalSymlinks(cwd: string, installRoot: string = \".ai-workflow\"): Promise<void> {\n const skillsLink = path.join(cwd, installRoot, \"opencode/skills\");\n const skillsTarget = path.join(cwd, installRoot, \".agents/skills\");\n\n if (!(await exists(skillsTarget))) return;\n\n try {\n const stat = await fs.lstat(skillsLink).catch(() => null);\n if (stat) {\n if (stat.isSymbolicLink()) {\n const current = await fs.readlink(skillsLink);\n if (current === \"../.agents/skills\") return;\n await fs.unlink(skillsLink);\n } else {\n return; // File exists, skip\n }\n }\n\n const type = process.platform === \"win32\" ? \"junction\" : \"dir\";\n await fs.symlink(\"../.agents/skills\", skillsLink, type);\n } catch {\n // Silent fail for internal symlink\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\n\n/**\n * Claude Adapter - Transforms OpenCode agents and skills into CLAUDE.md and .claude/rules/.\n */\nexport class ClaudeAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent or skill into a Claude rule with completion contract.\n */\n async transformToRule(filePath: string, type: \"agent\" | \"skill\" = \"agent\"): Promise<{ content: string; name: string }> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\") === \"SKILL\" \n ? path.basename(path.dirname(filePath)) \n : path.basename(filePath, \".md\");\n \n const ruleName = `${type}-${fileName.toLowerCase()}`;\n \n const hardenedContent = `---\nname: ${ruleName}\ndescription: ${type === \"agent\" ? \"Persona\" : \"Skill\"} rule for ${fileName}\n---\n# ${fileName} ${type === \"agent\" ? \"Persona\" : \"Skill\"}\n\n${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: hardenedContent,\n name: ruleName\n };\n }\n\n /**\n * Deploys agents, skills, and root CLAUDE.md.\n */\n async deploy(installRoot: string = \".ai-workflow\"): Promise<void> {\n const rulesDir = path.join(this.cwd, \".claude/rules\");\n await fs.mkdir(rulesDir, { recursive: true });\n\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n\n // 1. Deploy Agents to .claude/rules/agent-*.md\n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const transformed = await this.transformToRule(path.join(sourceAgentsDir, file), \"agent\");\n await fs.writeFile(path.join(rulesDir, `${transformed.name}.md`), transformed.content);\n }\n\n // 2. Deploy Skills to .claude/rules/skill-*.md\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n const transformed = await this.transformToRule(skillSource, \"skill\");\n await fs.writeFile(path.join(rulesDir, `${transformed.name}.md`), transformed.content);\n }\n }\n\n // 3. Create root CLAUDE.md\n await this.deployRootClaudeMd(sourceCommandsDir);\n }\n\n async deployRootClaudeMd(sourceCommandsDir: string): Promise<void> {\n const targetPath = path.join(this.cwd, \"CLAUDE.md\");\n \n // Collect commands to document them in CLAUDE.md\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n let commandsDoc = \"\";\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\")) continue;\n const name = path.basename(file, \".md\");\n commandsDoc += `- \\`ai-workflow run --spec-path=...\\` (Target: ${name})\\n`;\n }\n\n const instructions = `# CLAUDE.md - AI Workflow Kit Governance\n\nThis project uses the **AI Workflow Kit** (OpenCode-first) workflow.\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority** (./specs).\n\n## Common Commands\n${commandsDoc}\n- \\`ai-workflow doctor\\`: Verify installation.\n- \\`ai-workflow collect-evidence\\`: Generate EVIDENCE.json.\n\n## Rules & Personas\nAdhere to the specific rules and personas defined in \\`.claude/rules/\\`. \n- Always follow the **Branch Gate** policy (never work on \\`main\\`).\n- Always follow the **SDD Workflow** (Spec -> Plan -> PR -> Evidence).\n\n## Completion Contract\nEvery task completion MUST follow the payload format defined in the individual rule files.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\n\n/**\n * Codex Adapter - Transforms OpenCode agents, skills, and commands into Codex-native formats.\n */\nexport class CodexAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent into a Codex prompt with completion contract.\n */\n async transformAgent(filePath: string): Promise<{ content: string; name: string }> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\");\n \n const hardenedContent = `${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: hardenedContent,\n name: fileName\n };\n }\n\n /**\n * Deploys agents, skills, and commands to Codex-native directories.\n * Mapping:\n * - Agents -> .github/agents/\n * - Skills -> .agents/skills/\n * - Commands -> .codex/prompts/\n */\n async deploy(installRoot: string = \".ai-workflow\"): Promise<void> {\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n\n // 1. Deploy Agents to .github/agents/\n const codexAgentsDir = path.join(this.cwd, \".github/agents\");\n await fs.mkdir(codexAgentsDir, { recursive: true });\n \n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const transformed = await this.transformAgent(path.join(sourceAgentsDir, file));\n await fs.writeFile(path.join(codexAgentsDir, `${transformed.name}.md`), transformed.content);\n }\n\n // 2. Deploy Skills to .agents/skills/\n const codexSkillsDir = path.join(this.cwd, \".agents/skills\");\n await fs.mkdir(codexSkillsDir, { recursive: true });\n\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n const targetDir = path.join(codexSkillsDir, folder);\n await fs.mkdir(targetDir, { recursive: true });\n const content = await fs.readFile(skillSource, \"utf8\");\n await fs.writeFile(path.join(targetDir, \"SKILL.md\"), content);\n }\n }\n\n // 3. Deploy Commands to .codex/prompts/\n const codexPromptsDir = path.join(this.cwd, \".codex/prompts\");\n await fs.mkdir(codexPromptsDir, { recursive: true });\n\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".toml\")) continue;\n // Codex prompts work best as .md\n const targetFileName = file.endsWith(\".toml\") ? `${path.basename(file, \".toml\")}.md` : file;\n const content = await fs.readFile(path.join(sourceCommandsDir, file), \"utf8\");\n await fs.writeFile(path.join(codexPromptsDir, targetFileName), content);\n }\n\n // 4. Copy governance policy into .agents/docs/policies/ so the relative\n // link ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md in each\n // .agents/skills/{skill}/SKILL.md resolves correctly.\n const codexPoliciesDir = path.join(this.cwd, \".agents\", \"docs\", \"policies\");\n await fs.mkdir(codexPoliciesDir, { recursive: true });\n const sourcePoliciesDir = path.join(this.cwd, installRoot, \"opencode\", \"docs\", \"policies\");\n const policyFiles = await fs.readdir(sourcePoliciesDir).catch(() => []);\n for (const file of policyFiles) {\n if (!file.endsWith(\".md\")) continue;\n const policyContent = await fs.readFile(path.join(sourcePoliciesDir, file), \"utf8\");\n await fs.writeFile(path.join(codexPoliciesDir, file), policyContent);\n }\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\nexport interface TransformedItem {\n content: string;\n name: string;\n}\n\n/**\n * Maps OpenCode agent names to primary agent roles.\n */\nconst PERSONA_MAPPING: Record<string, string> = {\n \"atlas\": \"Atlas\",\n \"orion\": \"Orion\",\n \"sage\": \"Sage\",\n \"nexus\": \"Nexus\",\n \"astra\": \"Astra\",\n \"sage-validation\": \"Sage\",\n \"orion-release\": \"Orion\",\n \"orion-deploy\": \"Orion\",\n \"nexus-discovery\": \"Nexus\",\n \"phoenix\": \"Phoenix\"\n};\n\n/**\n * Antigravity Adapter - Transforms OpenCode .md to Antigravity Skill format and manages .agents/ integration.\n */\nexport class AntigravityAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent or specialized skill file to an Antigravity Skill.\n */\n async transform(filePath: string): Promise<TransformedItem> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\") === \"SKILL\" \n ? path.basename(path.dirname(filePath)) \n : path.basename(filePath, \".md\");\n \n const persona = PERSONA_MAPPING[fileName.toLowerCase()] || \"Astra\";\n \n // Check if already has frontmatter\n if (content.trim().startsWith(\"---\")) {\n return { content, name: fileName };\n }\n\n // Extract description from the first paragraph after the title\n const descriptionMatch = content.match(/^# .*\\n\\n(.*)/m);\n const description = descriptionMatch ? descriptionMatch[1].trim() : `Specialized agent for ${fileName}.`;\n\n const skillContent = `---\nname: ${fileName}\ndescription: ${description}\n---\n# ${persona} Persona\n\n${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: skillContent,\n name: fileName\n };\n }\n\n /**\n * Deploys transformed skills and agents to their respective directories.\n * Also orchestrates the .antigravity/ native integration.\n */\n async deploy(transformedItems: TransformedItem[], installRoot: string = \".ai-workflow\"): Promise<void> {\n const agentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const skillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n \n await fs.mkdir(agentsDir, { recursive: true });\n await fs.mkdir(skillsDir, { recursive: true });\n\n for (const item of transformedItems) {\n const isAgent = PERSONA_MAPPING[item.name.toLowerCase()];\n const targetDir = isAgent ? agentsDir : path.join(skillsDir, item.name);\n const fileName = isAgent ? `${item.name}.md` : \"SKILL.md\";\n \n const absoluteTargetDir = isAgent ? agentsDir : targetDir;\n await fs.mkdir(absoluteTargetDir, { recursive: true });\n await fs.writeFile(path.join(absoluteTargetDir, fileName), item.content);\n }\n \n // Deploy native Antigravity extensions (.antigravity/)\n await this.deployNativeExtensions(installRoot);\n\n // Also deploy root ANTIGRAVITY.md if it doesn't exist\n await this.deployInstructions();\n }\n\n /**\n * Orchestrates the .agents/ directory with copies of .ai-workflow/ assets.\n * Using hard copies instead of symlinks ensures native discovery across all platforms.\n */\n async deployNativeExtensions(installRoot: string = \".ai-workflow\"): Promise<void> {\n const antigravityDir = path.join(this.cwd, \".agents\");\n const antigravityAgents = path.join(antigravityDir, \"agents\");\n const antigravitySkills = path.join(antigravityDir, \"skills\");\n const antigravityCommands = path.join(antigravityDir, \"commands\");\n\n await fs.mkdir(antigravityAgents, { recursive: true });\n await fs.mkdir(antigravitySkills, { recursive: true });\n await fs.mkdir(antigravityCommands, { recursive: true });\n\n const getUrls = (targetPath: string) => {\n const linuxUrl = pathToFileURL(targetPath).href;\n const urls = [linuxUrl];\n \n if (process.platform === \"linux\" && process.env.WSL_DISTRO_NAME) {\n const distro = process.env.WSL_DISTRO_NAME;\n const normalizedPath = targetPath.replaceAll(\"\\\\\", \"/\");\n urls.push(`file://wsl.localhost/${distro}${normalizedPath}`);\n urls.push(`file:///wsl.localhost/${distro}${normalizedPath}`);\n }\n \n return urls.join(\"\\n\");\n };\n\n const toolNames = [\n \"send_message\",\n \"find_by_name\",\n \"grep_search\",\n \"view_file\",\n \"list_dir\",\n \"read_url_content\",\n \"search_web\",\n \"schedule\",\n \"multi_replace_file_content\",\n \"replace_file_content\",\n \"write_to_file\",\n \"run_command\",\n \"manage_task\",\n \"define_subagent\",\n \"invoke_subagent\",\n \"manage_subagents\",\n \"call_mcp_tool\"\n ];\n\n const systemPromptConfig = {\n \"includeSections\": [\n \"user_information\",\n \"mcp_servers\",\n \"skills\",\n \"subagent_reminder\",\n \"messaging\",\n \"artifacts\",\n \"user_rules\"\n ]\n };\n\n // 1. Deploy Primary Agents to .agents/agents/{agent_name}/\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n\n const AGENTS_INFO: Record<string, { name: string; description: string }> = {\n \"atlas\": { name: \"Atlas\", description: \"Router and workflow coordinator for AI Workflow Kit\" },\n \"nexus\": { name: \"Nexus\", description: \"Discovery, requirement, scope, and specification owner\" },\n \"orion\": { name: \"Orion\", description: \"Planning, PR sequencing, release, and deployment strategy owner\" },\n \"astra\": { name: \"Astra\", description: \"Implementation owner for incremental, scoped changes\" },\n \"sage\": { name: \"Sage\", description: \"Audit, validation, evidence, and quality gate owner\" },\n \"phoenix\": { name: \"Phoenix\", description: \"Remediation and regression recovery owner\" }\n };\n\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const lowercaseName = path.basename(file, \".md\").toLowerCase();\n const info = AGENTS_INFO[lowercaseName];\n if (!info) continue;\n\n const agentFolder = path.join(antigravityAgents, lowercaseName);\n await fs.mkdir(agentFolder, { recursive: true });\n\n // Copy Markdown file to the agent's folder\n const content = await fs.readFile(path.join(sourceAgentsDir, file), \"utf8\");\n const mdTarget = path.join(agentFolder, `${lowercaseName}.md`);\n await fs.writeFile(mdTarget, content);\n\n // Generate agent.json\n const agentJson = {\n name: lowercaseName,\n description: info.description,\n hidden: false,\n config: {\n customAgent: {\n systemPromptSections: [\n {\n title: \"Agent System Instructions\",\n content: `You are ${info.name}, the ${lowercaseName === \"astra\" ? \"implementation\" : lowercaseName} owner.\\n\\nFollow the contract instructions in:\\n${getUrls(mdTarget)}`\n }\n ],\n toolNames,\n systemPromptConfig\n }\n }\n };\n await fs.writeFile(path.join(agentFolder, \"agent.json\"), JSON.stringify(agentJson, null, 2));\n }\n\n // 2. Deploy Subagents to .agents/agents/{subagent_name}/\n const SUBAGENTS_INFO: Record<string, { description: string; skill: string }> = {\n \"Architecture-Specialist\": { description: \"Select the simplest architecture that safely satisfies current requirements\", skill: \"architecture\" },\n \"Backend-Engineer\": { description: \"Support safe PHP/Node/Python backend changes for APIs and persistence\", skill: \"backend-development\" },\n \"Deployment-Specialist\": { description: \"Plan, review, or validate deployment, release, and production-readiness\", skill: \"deployment\" },\n \"Design-Specialist\": { description: \"Apply practical design principles to keep solutions simple and maintainable\", skill: \"design-principles\" },\n \"Docs-Engineer\": { description: \"Write or improve project documentation, READMEs, guides, and prompts\", skill: \"documentation\" },\n \"Frontend-Engineer\": { description: \"Implement or review frontend changes involving UI, state, routing, and accessibility\", skill: \"frontend-development\" },\n \"Full-Stack-Engineer\": { description: \"Coordinate frontend and backend changes as one coherent, testable increment\", skill: \"full-stack-development\" },\n \"Token-Economist\": { description: \"Reduce context size while preserving information required for safe execution\", skill: \"optimize-tokens\" },\n \"PR-Manager\": { description: \"Plan, implement, review, or validate small pull requests while preserving scope\", skill: \"pr-workflow\" },\n \"Discovery-Analyst\": { description: \"Clarify ambiguous requests into actionable problem statements and success outcomes\", skill: \"product-discovery\" },\n \"Product-Planner\": { description: \"Turn clarified needs into scoped requirements with acceptance-ready outcomes\", skill: \"product-planning\" },\n \"Memory-Guardian\": { description: \"Manage discoverable project memory for durable decisions and recurring corrections\", skill: \"project-memory\" },\n \"Prompt-Engineer\": { description: \"Expert in creating and refining prompts for AI agents and workflows\", skill: \"prompt-engineer\" },\n \"QA-Engineer\": { description: \"Design, review, or improve tests, acceptance criteria, and validation evidence\", skill: \"qa-workflow\" },\n \"Refactoring-Specialist\": { description: \"Improve code/document structure safely while preserving behavior\", skill: \"refactoring\" },\n \"Release-Specialist\": { description: \"Prepare release readiness decisions with explicit gates and evidence\", skill: \"release-workflow\" },\n \"SDD-Specialist\": { description: \"Convert approved requirements into explicit, testable specification artifacts\", skill: \"spec-driven-development\" },\n \"Technical-Leader\": { description: \"Make technical decisions, review architecture, and identify trade-offs\", skill: \"technical-leadership\" },\n \"UI-UX-Engineer\": { description: \"Improve usability and interface clarity without introducing unnecessary complexity\", skill: \"ui-ux-design\" }\n };\n\n for (const [name, subInfo] of Object.entries(SUBAGENTS_INFO)) {\n const lowercaseSubagentName = name.toLowerCase();\n const subagentFolder = path.join(antigravityAgents, lowercaseSubagentName);\n await fs.mkdir(subagentFolder, { recursive: true });\n\n const skillPath = path.join(antigravitySkills, subInfo.skill, \"SKILL.md\");\n\n const subagentJson = {\n name: lowercaseSubagentName,\n description: subInfo.description,\n hidden: false,\n config: {\n customAgent: {\n systemPromptSections: [\n {\n title: \"Agent System Instructions\",\n content: `You are ${name}.\\n\\nFollow the contract instructions in:\\n${getUrls(skillPath)}`\n }\n ],\n toolNames,\n systemPromptConfig\n }\n }\n };\n await fs.writeFile(path.join(subagentFolder, \"agent.json\"), JSON.stringify(subagentJson, null, 2));\n }\n\n // 3. Copy Skills\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n await fs.mkdir(path.join(antigravitySkills, folder), { recursive: true });\n const content = await fs.readFile(skillSource, \"utf8\");\n await fs.writeFile(path.join(antigravitySkills, folder, \"SKILL.md\"), content);\n }\n }\n\n // 4. Copy Commands (from dist-assets/commands)\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n if (await this.exists(sourceCommandsDir)) {\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".toml\")) continue;\n const content = await fs.readFile(path.join(sourceCommandsDir, file), \"utf8\");\n await fs.writeFile(path.join(antigravityCommands, file), content);\n }\n }\n\n // 5. Copy governance policy into .agents/docs/policies/ so the relative\n // link ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md in each\n // .agents/skills/{skill}/SKILL.md resolves correctly.\n const sourcePoliciesDir = path.join(this.cwd, installRoot, \"opencode\", \"docs\", \"policies\");\n const antigravityPolicies = path.join(antigravityDir, \"docs\", \"policies\");\n if (await this.exists(sourcePoliciesDir)) {\n await fs.mkdir(antigravityPolicies, { recursive: true });\n const policyFiles = await fs.readdir(sourcePoliciesDir).catch(() => []);\n for (const file of policyFiles) {\n if (!file.endsWith(\".md\")) continue;\n const content = await fs.readFile(path.join(sourcePoliciesDir, file), \"utf8\");\n await fs.writeFile(path.join(antigravityPolicies, file), content);\n }\n }\n\n // 6. Inject project settings.json\n const settingsPath = path.join(antigravityDir, \"settings.json\");\n if (!(await this.exists(settingsPath))) {\n const settings = {\n model: { name: \"auto\" },\n ui: { theme: \"Ayu\" }\n };\n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));\n }\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Deploys the main ANTIGRAVITY.md and .antigravityignore instructions to the project root.\n */\n async deployInstructions(): Promise<void> {\n const targetPath = path.join(this.cwd, \"ANTIGRAVITY.md\");\n const ignorePath = path.join(this.cwd, \".antigravityignore\");\n \n // Deploy ANTIGRAVITY.md if it doesn't exist\n try {\n await fs.access(targetPath);\n } catch {\n const instructions = `# AI Workflow Kit - Engineering Governance\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority** (./specs).\n\n## Ternary Architecture\n- **Root:** Orchestration and config.\n- **.ai-workflow/:** Implementation (The Muscle).\n- **./specs:** Specifications (The Brain).\n\n## Branch Gates\n- **main Branch:** READ-ONLY.\n- **Validation:** Merges require successful observed validation; full/release workflows may persist EVIDENCE.json.\n\n## Primary Agents\n- **Atlas (Orchestrator)**\n- **Orion (Strategist)**\n- **Sage (Auditor)**\n- **Nexus (Spec Architect)**\n- **Astra (Developer)**\n- **Phoenix (Healer)**\n\n## Operational Preferences\n- Use \\`token-economy\\` and \\`minimal-context\\` skills.\n- **Native Discovery**: This project uses workspace-specific extensions in \\`.agents/\\`.\n- **Workflow Entry**: Use \\`/atlas\\` to begin any task.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n // Deploy .antigravityignore if it doesn't exist\n try {\n await fs.access(ignorePath);\n } catch {\n const ignoreContent = `.ai-workflow/\n.ai-workflow-backups/\nnode_modules/\n.git/\nEVIDENCE.json\n*.tgz\n*.zip\n*.tar\n.agents/tmp/\n.agents/history/\n`;\n await fs.writeFile(ignorePath, ignoreContent);\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { exists, readJson, readJsonc } from \"../../core/filesystem.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\n\nconst REQUIRED_FILES = [\n \".ai-workflow\",\n \"opencode/README.md\"\n];\n\nasync function isSymlink(filePath: string): Promise<boolean> {\n try {\n const stat = await fs.lstat(filePath);\n return stat.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport interface DoctorOptions {\n cwd: string;\n}\n\ninterface DoctorState {\n hasFailure: boolean;\n hasWarning: boolean;\n managedBlocks: string[];\n}\n\nasync function checkOpenCodeRuntime(cwd: string, state: DoctorState): Promise<void> {\n const adapter = new OpenCodeAdapter({ cwd });\n const inspection = await adapter.inspect();\n if (inspection.available) {\n console.log(\"PASS opencode CLI is available\");\n const supportedStr = Object.entries(inspection.supports)\n .filter(([_, v]) => v)\n .map(([k, _]) => k)\n .join(\", \");\n console.log(`PASS opencode capabilities detected: ${supportedStr || \"none\"}`);\n if (inspection.supports.agent) {\n console.log(\"PASS opencode --agent selection is supported\");\n } else {\n state.hasWarning = true;\n console.log(\"WARN opencode --agent selection is not supported; prompt fallback is available\");\n }\n } else {\n state.hasFailure = true;\n console.log(\"FAIL opencode CLI is not installed or not available in PATH\");\n }\n}\n\nasync function checkRequiredFiles(cwd: string, state: DoctorState): Promise<void> {\n for (const relativePath of REQUIRED_FILES) {\n const ok = await exists(path.join(cwd, relativePath));\n if (ok) {\n console.log(`PASS ${relativePath}`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL ${relativePath} missing`);\n }\n }\n}\n\nasync function checkAiWorkflowConfig(cwd: string, state: DoctorState): Promise<void> {\n const configPathV2 = path.join(cwd, \".ai-workflow/config.json\");\n const configPathLegacy = path.join(cwd, \".ai-workflow.json\");\n let configPath: string | null = null;\n\n if (await exists(configPathV2)) {\n configPath = configPathV2;\n } else if (await exists(configPathLegacy)) {\n configPath = configPathLegacy;\n }\n\n if (!configPath) return;\n\n try {\n const config = await readJson(configPath);\n const basename = path.basename(configPath);\n\n if (config.installMode === \"project-local\" || config.mode === \"standalone\") {\n console.log(\"PASS install mode is project-local/standalone\");\n } else {\n state.hasWarning = true;\n console.log(`WARN install mode is not project-local/standalone in ${basename}`);\n }\n\n if (config.profile) {\n console.log(`PASS profile detected: ${config.profile}`);\n } else {\n state.hasWarning = true;\n console.log(`WARN profile is missing in ${basename}`);\n }\n\n if (config.runtime) {\n console.log(`PASS runtime: ${config.runtime}`);\n } else {\n console.log(`NOTE runtime field not present in ${basename}`);\n }\n\n if (Array.isArray(config.managedBlocks)) {\n state.managedBlocks = config.managedBlocks;\n } else {\n console.log(`NOTE managedBlocks not present in ${basename} (legacy field)`);\n }\n\n if (Array.isArray(config.managedFiles)) {\n for (const relativePath of config.managedFiles) {\n const fileExists = await exists(path.join(cwd, relativePath));\n if (!fileExists) {\n state.hasWarning = true;\n console.log(`WARN managed file missing: ${relativePath}`);\n }\n }\n }\n\n if (Array.isArray(config.managedLinks)) {\n for (const relativePath of config.managedLinks) {\n const absolutePath = path.join(cwd, relativePath);\n if (!(await exists(absolutePath))) {\n state.hasWarning = true;\n console.log(`WARN managed link missing: ${relativePath}`);\n continue;\n }\n if (!(await isSymlink(absolutePath))) {\n state.hasWarning = true;\n console.log(`WARN managed link is not a symlink: ${relativePath}`);\n }\n }\n }\n } catch {\n state.hasFailure = true;\n console.log(`FAIL ${path.basename(configPath)} is not valid JSON`);\n }\n}\n\nasync function checkOpencodeJson(cwd: string, state: DoctorState): Promise<void> {\n const opencodePath = path.join(cwd, \"opencode.jsonc\");\n if (!(await exists(opencodePath))) {\n state.hasFailure = true;\n console.log(\"FAIL opencode.jsonc missing\");\n return;\n }\n \n try {\n const opencodeConfig = await readJsonc(opencodePath);\n console.log(\"PASS opencode.jsonc is valid JSONC\");\n\n const needsAgentDefault = state.managedBlocks.includes(\"opencode.jsonc:agent.default\");\n if (!needsAgentDefault || opencodeConfig.agent?.default) {\n console.log(\"PASS opencode agent.default available\");\n } else {\n state.hasFailure = true;\n console.log(\"FAIL opencode agent.default missing\");\n }\n\n const requiredCommands = state.managedBlocks\n .filter((block) => block.startsWith(\"opencode.jsonc:command.\"))\n .map((block) => block.replace(\"opencode.jsonc:command.\", \"\"));\n\n if (requiredCommands.length === 0) {\n console.log(\"PASS no managed opencode commands required\");\n } else {\n const missingCommands = requiredCommands.filter((command) => !opencodeConfig.command?.[command]);\n if (missingCommands.length === 0) {\n console.log(`PASS opencode managed commands available (${requiredCommands.length})`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL opencode command entries missing: ${missingCommands.join(\", \")}`);\n }\n }\n\n const requiredAgents = state.managedBlocks\n .filter((block) => block.startsWith(\"opencode.jsonc:agent.\") && !block.endsWith(\".default\"))\n .map((block) => block.replace(\"opencode.jsonc:agent.\", \"\"));\n\n if (requiredAgents.length === 0) {\n console.log(\"PASS no managed opencode agents required\");\n } else {\n const missingAgents = requiredAgents.filter((agent) => !opencodeConfig.agent?.[agent]);\n if (missingAgents.length === 0) {\n console.log(`PASS opencode managed agents available (${requiredAgents.length})`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL opencode agent entries missing: ${missingAgents.join(\", \")}`);\n }\n }\n } catch {\n state.hasFailure = true;\n console.log(\"FAIL opencode.jsonc is not valid JSONC\");\n }\n}\n\nasync function checkPackageJson(cwd: string, state: DoctorState): Promise<void> {\n const packageJsonPath = path.join(cwd, \"package.json\");\n if (await exists(packageJsonPath)) {\n try {\n const packageJson = await readJson(packageJsonPath);\n const scripts = packageJson.scripts ?? {};\n\n if (!scripts.validate) {\n state.hasWarning = true;\n console.log(\"WARN package.json has no validate script\");\n }\n } catch {\n state.hasFailure = true;\n console.log(\"FAIL package.json is not valid JSON\");\n }\n }\n}\n\nexport async function runDoctor({ cwd }: DoctorOptions): Promise<void> {\n const state: DoctorState = {\n hasFailure: false,\n hasWarning: false,\n managedBlocks: []\n };\n\n console.log(\"Doctor report:\");\n\n await checkOpenCodeRuntime(cwd, state);\n await checkRequiredFiles(cwd, state);\n await checkAiWorkflowConfig(cwd, state);\n await checkOpencodeJson(cwd, state);\n await checkPackageJson(cwd, state);\n\n const finalStatus = state.hasFailure ? \"FAIL\" : state.hasWarning ? \"PASS_WITH_NOTES\" : \"PASS\";\n console.log(`Final status: ${finalStatus}`);\n\n if (state.hasFailure) {\n process.exitCode = 1;\n }\n}\n\n","export const DELIVERY_SUMMARY_FIELDS = Object.freeze([\n \"Status\",\n \"Branch\",\n \"Changes\",\n \"Validation\",\n \"Known limitations\"\n] as const);\n\nexport function buildDeliverySummary({ evidence }: { evidence: any }): Record<string, string> {\n const commands = (evidence?.commands || []).map((item: any) => `${item.command || item.name}: ${item.status}`).join(\"; \") || \"No validation commands recorded\";\n return {\n Status: evidence?.status || \"BLOCKED\",\n Branch: evidence?.branch || \"unknown\",\n Changes: (evidence?.changedFiles || []).join(\", \") || \"No changed files recorded\",\n Validation: commands,\n \"Known limitations\": (evidence?.limitations || []).join(\"; \") || \"None recorded\"\n };\n}\n\nexport interface ValidationSummaryResult {\n status: \"PASS\" | \"FAIL\";\n missing: string[];\n invalid: string[];\n}\n\nexport function validateDeliverySummary(summary: any): ValidationSummaryResult {\n const missing = DELIVERY_SUMMARY_FIELDS.filter((field) => !String(summary?.[field] || \"\").trim());\n const status = String(summary?.Status || \"\").trim();\n const invalid: string[] = [];\n if (![\"COMPLETED\", \"COMPLETED_WITH_NOTES\", \"BLOCKED\"].includes(status)) invalid.push(\"Status\");\n if (status !== \"BLOCKED\" && /FAIL|BLOCKED/.test(String(summary?.Validation || \"\"))) invalid.push(\"successful status with failed validation\");\n return { status: missing.length || invalid.length ? \"FAIL\" : \"PASS\", missing, invalid };\n}\n\nexport function formatDeliverySummary(summary: any): string {\n return DELIVERY_SUMMARY_FIELDS.map((field) => `${field}: ${summary?.[field] || \"NOT_RECORDED\"}`).join(\"\\n\");\n}\n\n// Backward-compatible aliases for integrations that imported the previous API.\nexport const CANONICAL_FINALIZATION_FIELDS = DELIVERY_SUMMARY_FIELDS;\nexport const buildCanonicalFinalization = ({ collectorStatus = \"BLOCKED\", branchRecovery = \"unknown\" } = {}): Record<string, string> => ({\n Status: collectorStatus === \"PASS\" ? \"COMPLETED\" : collectorStatus === \"PASS_WITH_NOTES\" ? \"COMPLETED_WITH_NOTES\" : \"BLOCKED\",\n Branch: branchRecovery,\n Changes: \"See observed diff\",\n Validation: collectorStatus,\n \"Known limitations\": \"See evidence\"\n});\nexport const validateCanonicalFinalization = validateDeliverySummary;\nexport const formatCanonicalFinalization = formatDeliverySummary;\n","import { EvidenceCollector } from \"../../core/validation/evidence-collector.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { ValidationPlanner } from \"../../core/validation/validation-planner.js\";\nimport { buildDeliverySummary, formatDeliverySummary } from \"../../core/validation/canonical-finalization.js\";\n\nexport interface CollectEvidenceOptions {\n cwd: string;\n exitOnError?: boolean;\n taskSlug?: string | null;\n mode?: string | null;\n evidencePolicy?: \"optional\" | \"required\" | null;\n dryRun?: boolean;\n profile?: string;\n branchRecovery?: string;\n userRequest?: string | null;\n explicitApprovals?: string[];\n visualDist?: string | null;\n port?: number | string | null;\n}\n\n/**\n * @deprecated Boundary helper to translate legacy CLI mode options to modern policies.\n */\nexport function resolvePoliciesFromLegacyMode(mode: string | null, evidencePolicy: \"optional\" | \"required\" | null): {\n evidencePolicy: \"optional\" | \"required\";\n riskLevel: \"low\" | \"medium\" | \"high\";\n} {\n const activePolicy = evidencePolicy || (mode === \"full\" ? \"required\" : \"optional\");\n \n let risk: \"low\" | \"medium\" | \"high\" = \"medium\";\n if (mode === \"full\") {\n risk = \"high\";\n } else if (mode === \"quick\") {\n risk = activePolicy === \"required\" ? \"medium\" : \"low\";\n } else if (activePolicy === \"required\") {\n risk = \"high\";\n }\n \n return { evidencePolicy: activePolicy, riskLevel: risk };\n}\n\nexport async function runCollectEvidence({\n cwd, exitOnError = true, taskSlug = null, mode = null, evidencePolicy = null, dryRun = false, profile = \"generic\", branchRecovery = \"NOT_RECORDED\", userRequest = null, explicitApprovals = [], visualDist = null, port = null\n}: CollectEvidenceOptions): Promise<any> {\n const policies = resolvePoliciesFromLegacyMode(mode, evidencePolicy);\n const qualityGuard = new QualityGuard({ cwd, taskSlug, evidencePolicy: policies.evidencePolicy, riskLevel: policies.riskLevel });\n const planner = new ValidationPlanner({ cwd, qualityGuard });\n const tasks = await planner.plan(profile);\n\n const persist = !dryRun && policies.evidencePolicy === \"required\";\n const collector = new EvidenceCollector({\n cwd,\n timeout: 60000,\n taskSlug,\n evidencePolicy: policies.evidencePolicy,\n profile,\n branchRecovery,\n userRequest,\n explicitApprovals,\n visualDist,\n port: port || 8080\n });\n const evidence = await collector.collect(tasks, { writeArtifact: persist });\n const summary = buildDeliverySummary({ evidence });\n\n console.log(\"\\n--- Delivery Summary ---\");\n console.log(formatDeliverySummary(summary));\n console.log(persist ? \"\\nArtifact: EVIDENCE.json\" : \"\\nArtifact: NOT_REQUIRED for optional evidence policy\");\n console.log(`Commands processed: ${evidence.commands.length}\\n`);\n\n if (evidence.status === \"BLOCKED\" && exitOnError) process.exit(1);\n return evidence;\n}\n","import { spawnSync, execSync } from \"node:child_process\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Determines which npm scripts are available in the consumer project.\n */\nasync function readScripts(cwd: string): Promise<Record<string, string>> {\n try {\n const pkg = JSON.parse(await fs.readFile(path.join(cwd, \"package.json\"), \"utf8\"));\n return pkg.scripts || {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns the list of files changed since the last commit.\n * Used to detect whether remediation produced any observable change.\n */\nfunction getChangedFiles(cwd: string): string[] {\n try {\n const output = execSync(\"git status --short\", { cwd, encoding: \"utf8\" });\n return output\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => line.slice(3).trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n}\n\n/**\n * Maps an affectedCheck source string to likely npm script names to re-run.\n */\nfunction resolveRetryScripts(affectedChecks: string[], scripts: Record<string, string>): string[] {\n const retry = new Set<string>();\n\n for (const check of affectedChecks) {\n // Evidence failures → re-run the failing validation scripts\n if (check === \"evidence\" || check === \"result\") {\n if (scripts.test) retry.add(\"test\");\n if (scripts.lint) retry.add(\"lint\");\n if (scripts.build) retry.add(\"build\");\n if (scripts.typecheck) retry.add(\"typecheck\");\n }\n // Specific check types\n if (check.includes(\"test\")) retry.add(\"test\");\n if (check.includes(\"lint\")) retry.add(\"lint\");\n if (check.includes(\"build\")) retry.add(\"build\");\n if (check.includes(\"typecheck\")) retry.add(\"typecheck\");\n }\n\n // Filter to only scripts that actually exist\n return [...retry].filter((name) => !!scripts[name]);\n}\n\nexport interface RemediationExecutorContext {\n attempt: number;\n maxAttempts: number;\n mode: string;\n taskSlug: string;\n result: any;\n affectedChecks: string[];\n requestPath: string;\n}\n\nexport interface RemediationExecutorResult {\n applied: boolean;\n changedFiles?: string[];\n evidenceAdded?: string[];\n reason?: string;\n}\n\n/**\n * CLI Remediation Executor — default implementation for `ai-workflow run`.\n */\nexport function createCliRemediationExecutor(cwd: string) {\n return async function remediationExecutor({\n attempt,\n maxAttempts,\n mode,\n affectedChecks,\n requestPath\n }: RemediationExecutorContext): Promise<RemediationExecutorResult> {\n console.log(`\\n[HEALER] Attempt ${attempt}/${maxAttempts} — mode: ${mode}`);\n console.log(`[HEALER] Affected: ${affectedChecks.join(\", \")}`);\n\n const scripts = await readScripts(cwd);\n const filesBefore = getChangedFiles(cwd);\n const toRetry = resolveRetryScripts(affectedChecks, scripts);\n\n if (toRetry.length === 0) {\n console.log(\"[HEALER] No retryable scripts found for the affected checks.\");\n console.log(`[HEALER] Review ${requestPath} for details.`);\n return {\n applied: false,\n reason: `No npm scripts available to address: ${affectedChecks.join(\", \")}. Manual remediation required.`\n };\n }\n\n console.log(`[HEALER] Re-running: ${toRetry.map((s) => `npm run ${s}`).join(\", \")}`);\n\n const results: any[] = [];\n let anyPassed = false;\n\n for (const scriptName of toRetry) {\n process.stdout.write(` → npm run ${scriptName} ... `);\n const isWin32 = process.platform === \"win32\";\n const cmd = isWin32 ? \"npm.cmd\" : \"npm\";\n const result = spawnSync(cmd, [\"run\", scriptName], {\n cwd,\n shell: false,\n encoding: \"utf8\",\n timeout: 120000\n });\n const passed = result.status === 0;\n if (passed) anyPassed = true;\n console.log(passed ? \"PASS\" : \"FAIL\");\n results.push({ script: scriptName, passed, exitCode: result.status });\n }\n\n const filesAfter = getChangedFiles(cwd);\n const changedFiles = filesAfter.filter((f) => !filesBefore.includes(f));\n\n if (!anyPassed && changedFiles.length === 0) {\n console.log(\"[HEALER] No scripts passed and no files changed — remediation had no effect.\");\n return {\n applied: false,\n reason: `Re-ran ${toRetry.join(\", \")} — all failed. Structural fix required by the implementing agent.`\n };\n }\n\n console.log(`[HEALER] Applied: ${results.filter((r) => r.passed).map((r) => r.script).join(\", \") || \"none passed\"}`);\n if (changedFiles.length) console.log(`[HEALER] Changed files: ${changedFiles.join(\", \")}`);\n\n return {\n applied: true,\n changedFiles,\n evidenceAdded: anyPassed ? [\"validation-output\"] : []\n };\n };\n}\n","import { BranchGate } from \"../../core/gates/branch-gate.js\";\nimport { SpecValidator } from \"../../core/sdd/validator.js\";\nimport { HandoffEngine } from \"../../core/handoff/handoff-engine.js\";\nimport { runCollectEvidence } from \"./collect-evidence.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { HealerEngine } from \"../../core/healing/healer-engine.js\";\nimport { createCliRemediationExecutor } from \"../../core/healing/cli-remediation-executor.js\";\nimport { isRecoverableGateFailure, isTerminalFailure } from \"../../core/statuses.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { getWorkflowProfile, resolveWorkflowProfile } from \"../../core/workflow-profiles.js\";\n\nfunction normalizeTaskSlugFromSpec(specPath: string): string {\n const normalized = String(specPath).replaceAll(\"\\\\\", \"/\");\n const marker = \"/docs/workflows/\";\n const index = normalized.includes(marker)\n ? normalized.indexOf(marker) + marker.length\n : normalized.startsWith(\"docs/workflows/\") ? \"docs/workflows/\".length : -1;\n if (index >= 0) {\n const slug = normalized.slice(index).split(\"/\")[0];\n if (slug) return slug;\n }\n return path.basename(specPath, path.extname(specPath));\n}\n\nexport function combineValidation(evidence: any, quality: any): any {\n const statuses = [evidence.internalStatus, quality.overallStatus];\n let overallStatus = \"PASS\";\n if (statuses.includes(\"BLOCKED\")) overallStatus = \"BLOCKED\";\n else if (statuses.includes(\"FAIL\")) overallStatus = \"FAIL\";\n else if (statuses.includes(\"FAIL_DELEGATION_GATE\")) overallStatus = \"FAIL_DELEGATION_GATE\";\n else if (statuses.includes(\"FAIL_QUALITY_GATE\")) overallStatus = \"FAIL_QUALITY_GATE\";\n else if (statuses.includes(\"PASS_WITH_NOTES\")) overallStatus = \"PASS_WITH_NOTES\";\n return { overallStatus, evidence, quality };\n}\n\nexport interface runMasterOrchestratorOptions {\n cwd: string;\n specPath?: string;\n override?: string;\n remediationExecutor?: any;\n}\n\n/**\n * Coordinates branch safety, specification validation, observed validation, bounded remediation, and handoff.\n * Failed required validation can never be promoted to success.\n */\nexport async function runMasterOrchestrator({ cwd, specPath, override, remediationExecutor = null }: runMasterOrchestratorOptions): Promise<any> {\n console.log(\"\\n[AI WORKFLOW] Starting evidence-backed orchestration...\\n\");\n\n const branchGate = new BranchGate({ memoryDir: path.join(cwd, \".ai-workflow\"), cwd });\n const taskSlug = specPath ? normalizeTaskSlugFromSpec(specPath) : \"implementation\";\n const gateResult = branchGate.check(override, { taskSlug });\n if (gateResult.blocked) throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);\n console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);\n\n if (!specPath) throw new Error(\"[SDD BLOCKED] Missing --spec-path. An approved specification is required.\");\n\n const validator = new SpecValidator();\n const absoluteSpecPath = path.isAbsolute(specPath) ? specPath : path.join(cwd, specPath);\n const validation = await validator.validate(absoluteSpecPath);\n if (!validation.valid) throw new Error(`[SDD BLOCKED] Specification is not ready: ${validation.reason}`);\n\n const specTier = validation.tier || \"standard\";\n const riskLevel = specTier === \"deep\" ? \"high\" : specTier === \"tiny\" ? \"low\" : \"medium\";\n const evidencePolicy = specTier === \"deep\" ? \"required\" : \"optional\";\n const remediationLimit = specTier === \"deep\" ? 3 : specTier === \"tiny\" ? 1 : 2;\n\n const specContent = await fs.readFile(absoluteSpecPath, \"utf8\");\n const workflowProfile = resolveWorkflowProfile({ request: specContent });\n const profileDefinition = getWorkflowProfile(workflowProfile);\n console.log(`[PASS] Specification: ${specTier.toUpperCase()} spec is APPROVED.`);\n console.log(`[PROFILE] ${workflowProfile} -> ${profileDefinition.owner}; skills: ${profileDefinition.skills.join(\", \") || \"none\"}.`);\n\n const validateWorkflow = async () => {\n const evidence = await runCollectEvidence({\n cwd,\n exitOnError: false,\n taskSlug,\n evidencePolicy,\n profile: workflowProfile,\n branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : \"NOT_REQUIRED\"\n });\n const quality = await new QualityGuard({ cwd, taskSlug, evidencePolicy, riskLevel }).verify();\n return combineValidation(evidence, quality);\n };\n\n let result = await validateWorkflow();\n if (isRecoverableGateFailure(result.overallStatus)) {\n console.log(`\\n[REMEDIATION REQUIRED] ${result.overallStatus}. Starting bounded remediation (limit: ${remediationLimit}).`);\n // Use the provided executor (programmatic API) or fall back to the default CLI executor.\n // The CLI executor re-runs failed npm scripts; it does not modify source code.\n const executor = typeof remediationExecutor === \"function\"\n ? remediationExecutor\n : createCliRemediationExecutor(cwd);\n const healer = new HealerEngine({ cwd, remediationLimit, taskSlug });\n result = await healer.run({ initialResult: result, validate: validateWorkflow, remediate: executor });\n }\n\n if (isTerminalFailure(result.overallStatus)) {\n throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: ${result.reason || \"Validation could not be resolved safely.\"}`);\n }\n if (isRecoverableGateFailure(result.overallStatus)) {\n throw new Error(`[WORKFLOW BLOCKED] Unresolved gate status after remediation: ${result.overallStatus}`);\n }\n\n console.log(\"\\n--- Final Handoff ---\");\n const handoffEngine = new HandoffEngine({ cwd });\n const handoffPath = await handoffEngine.generate({\n taskId: path.basename(specPath, \".md\"),\n status: result.overallStatus,\n specPaths: [specPath],\n evidence: result.evidence,\n nextActions: `Profile ${workflowProfile}. Observed validation completed. Ready for review or explicitly approved release actions.`\n });\n\n console.log(`\\n[AI WORKFLOW COMPLETE] ${result.overallStatus}`);\n if (result.remediation?.attempts) console.log(`Remediation attempts: ${result.remediation.attempts}`);\n console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\\n`);\n return { ...result, workflowProfile };\n}\n","import { OpenCodeAdapter } from \"../runtime/opencode-adapter.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { EvidenceLedger } from \"../evidence/evidence-ledger.js\";\n\nexport function createRuntimeRemediationExecutor(cwd: string, ledger: EvidenceLedger | null = null) {\n const adapter = new OpenCodeAdapter({ cwd });\n\n function getChangedFiles(): string[] {\n try {\n const output = execSync(\"git status --short\", { cwd, encoding: \"utf8\" });\n return output\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => line.slice(3).trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n }\n\n return async function runtimeRemediationExecutor({\n attempt,\n maxAttempts,\n mode,\n affectedChecks,\n requestPath,\n result\n }: {\n attempt: number;\n maxAttempts: number;\n mode: string;\n affectedChecks: string[];\n requestPath: string;\n result: any;\n }): Promise<{ applied: boolean; changedFiles?: string[]; evidenceAdded?: string[]; reason?: string }> {\n console.log(`\\n[HEALER] Running Runtime/Phoenix Structural Remediation [Attempt ${attempt}/${maxAttempts}]`);\n console.log(`[HEALER] Affected checks: ${affectedChecks.join(\", \")}`);\n\n if (ledger) {\n ledger.logEvent({\n actor: \"Phoenix\",\n actorType: \"runtime-agent\",\n observed: true,\n runtime: \"opencode\",\n eventType: \"remediation_start\",\n provenance: \"opencode-adapter\",\n data: {\n attempt,\n affectedChecks,\n event: \"remediation.started\"\n }\n });\n }\n\n let requestContent: any = {};\n try {\n requestContent = JSON.parse(await fs.readFile(requestPath, \"utf8\"));\n } catch {\n // ignore/fallback\n }\n\n const filesBefore = getChangedFiles();\n const fileContentsBefore: Record<string, string | null> = {};\n for (const file of filesBefore) {\n try {\n fileContentsBefore[file] = await fs.readFile(path.join(cwd, file), \"utf8\");\n } catch {\n fileContentsBefore[file] = null;\n }\n }\n \n // Extract concrete command outputs for failing checks\n const failedCommands = (result?.evidence?.commands || [])\n .filter((cmd: any) => [\"FAIL\", \"BLOCKED\"].includes(cmd.status));\n \n let concreteOutput = \"\";\n if (failedCommands.length > 0) {\n concreteOutput = failedCommands.map((cmd: any) => {\n return `Command: ${cmd.name} (${Array.isArray(cmd.command) ? cmd.command.join(\" \") : cmd.command})\nExit Code: ${cmd.exitCode}\nOutput:\n${cmd.output}`;\n }).join(\"\\n\\n\");\n } else {\n concreteOutput = JSON.stringify(result?.quality || result || {}, null, 2);\n }\n\n const promptMsg = `We are in remediation mode (attempt ${attempt}/${maxAttempts}).\nThe following validation checks have failed:\n${affectedChecks.join(\", \")}\n\nDetails of the failure:\n\\`\\`\\`\n${concreteOutput}\n\\`\\`\\`\n\nPlease inspect the code, identify the root cause of these failures (e.g. failing tests, syntax issues, build errors), and write a correction to the relevant files in the workspace to make the tests/validations pass.`;\n\n console.log(`[HEALER] Sending structural healing request to Phoenix agent...`);\n const runResult = await adapter.execute(promptMsg, {\n agent: \"Phoenix\"\n });\n\n const filesAfter = getChangedFiles();\n const changedFiles: string[] = [];\n for (const file of filesAfter) {\n if (!filesBefore.includes(file)) {\n changedFiles.push(file);\n } else {\n try {\n const contentAfter = await fs.readFile(path.join(cwd, file), \"utf8\");\n if (contentAfter !== fileContentsBefore[file]) {\n changedFiles.push(file);\n }\n } catch {\n if (fileContentsBefore[file] !== null) {\n changedFiles.push(file);\n }\n }\n }\n }\n const success = runResult.success && changedFiles.length > 0;\n\n if (!runResult.success) {\n console.log(`[HEALER] Phoenix remediation failed: ${runResult.error || \"Unknown error\"}`);\n return {\n applied: false,\n reason: `Phoenix runtime execution failed: ${runResult.error || \"Unknown error\"}`\n };\n }\n\n if (changedFiles.length === 0) {\n console.log(`[HEALER] Phoenix execution succeeded but no files were modified.`);\n return {\n applied: false,\n reason: \"Phoenix runtime executed but did not modify any files in the workspace.\"\n };\n }\n\n console.log(`[HEALER] Phoenix successfully executed remediation commands.`);\n console.log(`[HEALER] Files modified: ${changedFiles.join(\", \")}`);\n\n return {\n applied: true,\n changedFiles,\n evidenceAdded: [\"phoenix-healing-run\"]\n };\n };\n}\n","import { RequestClassifier, RequestClassifierResult } from \"../../core/request-classifier.js\";\nimport { ExecutionPlanner, ExecutionPlan } from \"../../core/execution-planner.js\";\nimport { WorkflowStateMachine } from \"../../core/workflow-state-machine.js\";\nimport { BranchGate } from \"../../core/gates/branch-gate.js\";\nimport { EvidenceLedger } from \"../../core/evidence/evidence-ledger.js\";\nimport { DelegationController } from \"../../core/delegation-controller.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\nimport { runCollectEvidence } from \"./collect-evidence.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { HandoffEngine } from \"../../core/handoff/handoff-engine.js\";\nimport { HealerEngine } from \"../../core/healing/healer-engine.js\";\nimport { createRuntimeRemediationExecutor } from \"../../core/healing/runtime-remediation-executor.js\";\nimport { isRecoverableGateFailure, isTerminalFailure } from \"../../core/statuses.js\";\nimport { Finalizer } from \"../../core/finalization/finalizer.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\n\n/** Snapshot of workspace state before/after read-only execution. */\ninterface ReadOnlyWorkspaceState {\n snapshot: { files: Record<string, { sha256: string }> };\n head: string;\n branch: string;\n indexTree: string;\n porcelainStatus: string;\n}\n\n/** Combined result from evidence collection and quality guard. */\ninterface ValidationResult {\n overallStatus: string;\n evidence: Record<string, unknown>;\n quality: Record<string, unknown>;\n}\n\n/** Result returned by BranchGate.check(). */\ninterface BranchGateResult {\n blocked: boolean;\n reason: string;\n branch: string;\n branchBefore: string;\n recovered: boolean;\n}\n\nasync function captureReadOnlyState(cwd: string, fastTrack = false) {\n const finalizer = new Finalizer({ cwd, fastTrack });\n const snapshot = await finalizer.snapshotManager.capture();\n \n const execGit = (args: string) => {\n try {\n return execSync(`git ${args}`, { cwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n return \"\";\n }\n };\n\n const head = execGit(\"rev-parse HEAD\");\n const branch = execGit(\"rev-parse --abbrev-ref HEAD\");\n const indexTree = execGit(\"write-tree\");\n const porcelainStatus = execGit(\"status --porcelain\");\n\n return {\n snapshot,\n head,\n branch,\n indexTree,\n porcelainStatus\n };\n}\n\nfunction compareReadOnlyState(before: ReadOnlyWorkspaceState, after: ReadOnlyWorkspaceState) {\n const violations: string[] = [];\n\n // 1. Compare branch\n if (before.branch !== after.branch) {\n violations.push(`Branch changed from '${before.branch}' to '${after.branch}'`);\n }\n\n // 2. Compare HEAD\n if (before.head !== after.head) {\n violations.push(`Git HEAD changed from '${before.head}' to '${after.head}' (commit or reset made inside read-only task)`);\n }\n\n // 3. Compare index tree\n if (before.indexTree !== after.indexTree) {\n violations.push(`Git index tree changed from '${before.indexTree}' to '${after.indexTree}'`);\n }\n\n // 4. Compare porcelain status\n if (before.porcelainStatus !== after.porcelainStatus) {\n violations.push(`Git status changed. Before:\\n${before.porcelainStatus}\\nAfter:\\n${after.porcelainStatus}`);\n }\n\n // 5. Compare workspace files (SHA-256 hashes)\n const beforeFiles = before.snapshot.files || {};\n const afterFiles = after.snapshot.files || {};\n\n for (const [file, info] of Object.entries(afterFiles)) {\n const prevInfo = beforeFiles[file];\n if (!prevInfo) {\n violations.push(`File added: ${file}`);\n } else if (prevInfo.sha256 !== (info as any).sha256) {\n violations.push(`File content modified: ${file}`);\n }\n }\n for (const file of Object.keys(beforeFiles)) {\n if (!afterFiles[file]) {\n violations.push(`File deleted: ${file}`);\n }\n }\n\n return violations;\n}\n\nfunction slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 32) || \"task\";\n}\n\nfunction combineValidation(evidence: Record<string, unknown>, quality: Record<string, unknown>): ValidationResult {\n const statuses = [evidence.internalStatus, quality.overallStatus];\n let overallStatus = \"PASS\";\n if (statuses.includes(\"BLOCKED\")) overallStatus = \"BLOCKED\";\n else if (statuses.includes(\"FAIL\")) overallStatus = \"FAIL\";\n else if (statuses.includes(\"FAIL_DELEGATION_GATE\")) overallStatus = \"FAIL_DELEGATION_GATE\";\n else if (statuses.includes(\"FAIL_QUALITY_GATE\")) overallStatus = \"FAIL_QUALITY_GATE\";\n else if (statuses.includes(\"PASS_WITH_NOTES\")) overallStatus = \"PASS_WITH_NOTES\";\n return { overallStatus, evidence, quality };\n}\n\nexport interface ExecuteOptions {\n cwd: string;\n naturalRequest: string;\n taskSlug?: string;\n}\n\n/**\n * classifyAndPlanExecution - Intake analysis and contract formulation.\n */\nasync function classifyAndPlanExecution(\n naturalRequest: string,\n cwd: string,\n taskSlug: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<{ plan: ExecutionPlan; classification: RequestClassifierResult }> {\n const classifier = new RequestClassifier();\n const classification = classifier.classify(naturalRequest, { cwd });\n console.log(`[CLASSIFIED] Intent: ${classification.intent}, Mode: ${classification.mode}, Profile: ${classification.profile}`);\n stateMachine.transitionTo(\"CLASSIFIED\");\n\n await delegationController.route(naturalRequest, classification);\n\n const routingDecision = classification.routingDecision || {};\n if (routingDecision.permissionDecision === \"blocked\") {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[ROUTE BLOCKED] ${routingDecision.reason}`);\n }\n if (routingDecision.permissionDecision === \"rerouted\") {\n console.log(`[REROUTED] ${routingDecision.reason}`);\n }\n\n const planner = new ExecutionPlanner({ cwd });\n const plan = planner.plan(classification, taskSlug);\n console.log(`[PLANNED] Owner: ${plan.owner}, Remediation limit: ${plan.remediationLimit}`);\n stateMachine.transitionTo(\"PLANNED\");\n\n return { plan, classification };\n}\n\n/**\n * runBranchGate - Authorizes changes within the branch lifecycle.\n */\nfunction runBranchGate(plan: ExecutionPlan, taskSlug: string, cwd: string, stateMachine: WorkflowStateMachine, branchGate: BranchGate): BranchGateResult {\n const gateResult = branchGate.check(\"\", {\n taskSlug,\n readOnly: !plan.branchNeeded\n });\n\n if (gateResult.blocked) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);\n }\n console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);\n stateMachine.transitionTo(\"BRANCH_READY\");\n return gateResult;\n}\n\n/**\n * createSpecIfRequired - Implements Spec-Driven Development gate.\n */\nasync function createSpecIfRequired(plan: ExecutionPlan, classification: RequestClassifierResult, taskSlug: string, cwd: string): Promise<void> {\n if (plan.specPath) {\n const fullSpecPath = path.join(cwd, plan.specPath);\n const specExists = await fs.access(fullSpecPath).then(() => true).catch(() => false);\n if (!specExists) {\n await fs.mkdir(path.dirname(fullSpecPath), { recursive: true });\n const specTemplatePath = path.join(cwd, \".ai-workflow/templates/specs/standard.md\");\n const templateContent = await fs.readFile(specTemplatePath, \"utf8\").catch(() => {\n return `# [STANDARD] Specification: ${classification.request}\\n\\n## Metadata\\n\\n- ID: SPEC-${taskSlug}\\n- Author: Spec-Engineer\\n- Status: DRAFT\\n- Date: ${new Date().toISOString().split(\"T\")[0]}\\n\\n## Functional Requirements\\n\\n- ${classification.request}\\n\\n## Technical Implementation Plan\\n\\n### Files to Create/Modify\\n\\n- \\`src/index.js\\`\\n\\n## Acceptance Criteria\\n\\n- [ ] Implemented successfully\\n\\n## Testing Strategy\\n\\n- [ ] Behavior tests pass`;\n });\n await fs.writeFile(fullSpecPath, templateContent);\n console.log(`[EXECUTE] Created DRAFT specification template at: ${plan.specPath}`);\n }\n }\n}\n\n/**\n * runImplementation - Delegations to the implementation engine.\n */\nasync function runImplementation(\n plan: ExecutionPlan,\n classification: RequestClassifierResult,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine,\n fastTrack: boolean = false\n): Promise<any> {\n stateMachine.transitionTo(\"DELEGATED\");\n stateMachine.transitionTo(\"IMPLEMENTING\");\n\n let promptMsg = classification.request;\n if (plan.specPath) {\n promptMsg = `Please review and fill in the specification file at: ${plan.specPath}. Make sure to change the Status field to 'APPROVED' in the Metadata section, and then implement the behavior described.`;\n }\n\n const runResult = await delegationController.implement(promptMsg, plan.owner, { readOnly: !plan.branchNeeded, fastTrack });\n\n if (!runResult.success) {\n console.error(`[EXECUTE] OpenCode adapter execution reported failure: ${runResult.error || \"Unknown error\"}`);\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] OpenCode runtime execution failed: ${runResult.error || \"Unknown error\"}`);\n }\n return runResult;\n}\n\n/**\n * runReadOnlyConfinementCheck - Asserts read-only execution constraints.\n */\nasync function runReadOnlyConfinementCheck(readOnlyStateBefore: ReadOnlyWorkspaceState, cwd: string, stateMachine: WorkflowStateMachine, fastTrack = false): Promise<void> {\n const readOnlyStateAfter = await captureReadOnlyState(cwd, fastTrack);\n const violations = compareReadOnlyState(readOnlyStateBefore, readOnlyStateAfter);\n if (violations.length > 0) {\n console.error(`[EXECUTE] Read-only confinement violation detected:`);\n for (const v of violations) {\n console.error(` - ${v}`);\n }\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] Read-only confinement violation: files were written/modified, index or commits modified: \\n${violations.join(\"\\n\")}`);\n }\n}\n\n/**\n * runValidation - Resolves evidence validation contracts.\n */\nasync function runValidation(\n plan: ExecutionPlan,\n taskSlug: string,\n cwd: string,\n gateResult: BranchGateResult,\n naturalRequest: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<{ result: ValidationResult; validateWorkflow: () => Promise<ValidationResult> }> {\n stateMachine.transitionTo(\"VALIDATING\");\n\n const validateWorkflow = async () => {\n const evidence = await runCollectEvidence({\n cwd,\n exitOnError: false,\n taskSlug,\n evidencePolicy: plan.evidencePolicy,\n profile: plan.profile,\n branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : \"NOT_REQUIRED\",\n userRequest: naturalRequest,\n explicitApprovals: process.env.AI_WORKFLOW_APPROVALS ? process.env.AI_WORKFLOW_APPROVALS.split(\",\").map(a => a.trim()) : []\n });\n const quality = await new QualityGuard({\n cwd,\n taskSlug,\n evidencePolicy: plan.evidencePolicy,\n riskLevel: plan.riskLevel\n }).verify();\n return combineValidation(evidence, quality);\n };\n\n const result = await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n return { result, validateWorkflow };\n}\n\n/**\n * runBoundedRemediation - Heals gate violations.\n */\nasync function runBoundedRemediation(\n plan: any,\n taskSlug: string,\n cwd: string,\n initialResult: any,\n validateWorkflow: () => Promise<any>,\n ledger: EvidenceLedger,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine,\n checkBranchSafety: () => void,\n updateSnapshot: () => Promise<void>\n): Promise<any> {\n if (!isRecoverableGateFailure(initialResult.overallStatus)) {\n return initialResult;\n }\n\n console.log(`\\n[REMEDIATION REQUIRED] ${initialResult.overallStatus}. Starting bounded remediation (limit: ${plan.remediationLimit}).`);\n const executor = createRuntimeRemediationExecutor(cwd, ledger);\n const healer = new HealerEngine({\n cwd,\n remediationLimit: plan.remediationLimit,\n taskSlug,\n ledger\n });\n\n return await healer.run({\n initialResult,\n validate: async () => {\n stateMachine.transitionTo(\"REVALIDATING\");\n return await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n },\n remediate: async (remedCtx) => {\n stateMachine.transitionTo(\"REMEDIATING\");\n const remRes = await executor(remedCtx as any);\n if (remRes.applied) {\n checkBranchSafety();\n await updateSnapshot();\n }\n return remRes;\n }\n });\n}\n\n/**\n * runFinalizerStabilization - Verifies integrity and fidelity.\n */\nasync function runFinalizerStabilization(\n plan: any,\n taskSlug: string,\n cwd: string,\n initialResult: any,\n validateWorkflow: () => Promise<any>,\n delegationController: DelegationController,\n finalizer: Finalizer,\n lastWriteSnapshotRef: { current: any },\n checkBranchSafety: () => void\n): Promise<{ result: any; integrity: any }> {\n let integrity = await finalizer.verifyIntegrity(lastWriteSnapshotRef.current);\n let revalidationCount = 0;\n const maxRevalidations = 2;\n let result = initialResult;\n\n while (!integrity.valid && revalidationCount < maxRevalidations) {\n console.log(`\\n[FINALIZER WARNING] Workspace mutated during validation! Re-running validation to stabilize.`);\n console.log(`Changes detected:`, integrity.changes);\n\n checkBranchSafety();\n\n lastWriteSnapshotRef.current = await finalizer.snapshotManager.capture();\n revalidationCount++;\n\n result = await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n\n checkBranchSafety();\n\n integrity = await finalizer.verifyIntegrity(lastWriteSnapshotRef.current);\n }\n\n return { result, integrity };\n}\n\n/**\n * generateFinalHandoff - Generates Handoff report.\n */\nasync function generateFinalHandoff(plan: ExecutionPlan, taskSlug: string, cwd: string, finalState: string, evidence: Record<string, unknown> | null): Promise<string> {\n console.log(\"\\n--- Final Handoff ---\");\n const handoffEngine = new HandoffEngine({ cwd });\n const handoffPath = await handoffEngine.generate({\n taskId: taskSlug,\n status: finalState,\n specPaths: plan.specPath ? [plan.specPath] : [],\n evidence,\n nextActions: `Profile ${plan.profile}. Observed execution completed with status ${finalState}.`\n });\n\n console.log(`\\n[AI WORKFLOW COMPLETE] ${finalState}`);\n console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\\n`);\n return handoffPath;\n}\n\nasync function runFastTrackValidation(cwd: string, result: any, checkBranchSafety: () => void): Promise<string> {\n console.log(`\\n--- [FAST-TRACK] Running Lightweight Validation Gates ---`);\n checkBranchSafety();\n \n const changedFiles = result.evidence?.changedFiles || [];\n console.log(`[FAST-TRACK] Changed files detected:`, changedFiles);\n \n const evidencePath = path.join(cwd, \"EVIDENCE.json\");\n const hasEvidence = await fs.access(evidencePath).then(() => true).catch(() => false);\n \n if (hasEvidence) {\n const { EvidenceValidator } = await import(\"../../core/validation/evidence-validator.js\");\n const isTest = process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\";\n const evidenceValidator = new EvidenceValidator({ cwd, skipFileCheck: isTest, skipGitCheck: isTest });\n const valResult = await evidenceValidator.validate();\n if (!valResult.valid) {\n console.error(`\\n[FAST-TRACK BLOCKED] EVIDENCE.json validation failed: ${valResult.reason}`);\n return \"FAIL_QUALITY_GATE\";\n }\n }\n return result.overallStatus;\n}\n\nasync function runFidelityValidation(naturalRequest: string, result: any, finalizer: Finalizer): Promise<string> {\n const fidelityResult = await finalizer.verifyFidelity({\n userRequest: naturalRequest,\n projectContext: result.evidence?.deliveryDecision?.projectContext || null,\n deliveryDecision: result.evidence?.deliveryDecision || null,\n changedFiles: result.evidence?.changedFiles || [],\n evidence: result.evidence || null,\n explicitApprovals: process.env.AI_WORKFLOW_APPROVALS ? process.env.AI_WORKFLOW_APPROVALS.split(\",\").map(a => a.trim()) : []\n });\n \n if (!fidelityResult.passed) {\n console.log(`\\n[FINALIZER BLOCKED] BLOCKED: Artifact fidelity check failed!`);\n console.log(`Reason: ${fidelityResult.reason}`);\n return \"FAIL_QUALITY_GATE\";\n }\n return result.overallStatus;\n}\n\nfunction computeFinalState(finalStatus: string): string {\n if (finalStatus === \"PASS\") return \"COMPLETED\";\n if (finalStatus === \"PASS_WITH_NOTES\") return \"COMPLETED_WITH_NOTES\";\n return \"BLOCKED\";\n}\n\nasync function executeReadOnlyWorkflow(\n cwd: string,\n stateMachine: WorkflowStateMachine,\n readOnlyStateBefore: ReadOnlyWorkspaceState,\n fastTrack: boolean\n): Promise<any> {\n await runReadOnlyConfinementCheck(readOnlyStateBefore, cwd, stateMachine, fastTrack);\n\n stateMachine.transitionTo(\"IMPLEMENTED\");\n stateMachine.transitionTo(\"VALIDATING\");\n stateMachine.transitionTo(\"COMPLETED\");\n\n console.log(\"\\n--- Final Handoff ---\");\n console.log(`\\n[AI WORKFLOW COMPLETE] COMPLETED`);\n console.log(`Handoff Packet: [IN-MEMORY] (No handoff file written in read-only mode)\\n`);\n\n return {\n overallStatus: \"PASS\",\n evidence: {\n internalStatus: \"PASS\",\n commandsRun: []\n },\n quality: {\n overallStatus: \"PASS\"\n },\n stateHistory: stateMachine.getHistory()\n };\n}\n\n/**\n * runExecute - Coordinators natural request execution.\n */\nexport async function runExecute({ cwd, naturalRequest, taskSlug: taskSlugOverride }: ExecuteOptions): Promise<any> {\n if (!naturalRequest || !naturalRequest.trim()) {\n throw new Error(\"Missing request. Please provide a natural request string via positional arguments or --request flag.\");\n }\n\n const taskSlug = taskSlugOverride || slugify(naturalRequest);\n console.log(`\\n[AI WORKFLOW] Executing natural request intake [slug: ${taskSlug}]...\\n`);\n\n const ledger = new EvidenceLedger({ cwd, workflowId: taskSlug });\n const delegationController = new DelegationController({ cwd, ledger, adapter: new OpenCodeAdapter({ cwd }) });\n\n let plan: ExecutionPlan | null = null;\n try {\n const stateMachine = new WorkflowStateMachine();\n\n const { plan: planObj, classification } = await classifyAndPlanExecution(naturalRequest, cwd, taskSlug, delegationController, stateMachine);\n plan = planObj;\n const fastTrack = plan.riskLevel === \"low\" && (!plan.branchNeeded || plan.evidencePolicy === \"optional\");\n\n const branchGate = new BranchGate({ memoryDir: path.join(cwd, \".ai-workflow\"), cwd });\n const gateResult = runBranchGate(plan, taskSlug, cwd, stateMachine, branchGate);\n\n const checkBranchSafety = () => {\n if (!planObj.branchNeeded) return;\n const currentBranch = branchGate.getCurrentBranch();\n if (branchGate.protectedBranches.includes(currentBranch)) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] Security violation: current branch is protected '${currentBranch}'!`);\n }\n };\n\n await createSpecIfRequired(plan, classification, taskSlug, cwd);\n\n let readOnlyStateBefore: ReadOnlyWorkspaceState | null = null;\n if (!plan.branchNeeded) {\n readOnlyStateBefore = await captureReadOnlyState(cwd, fastTrack);\n }\n\n await runImplementation(plan, classification, delegationController, stateMachine, fastTrack);\n\n if (!plan.branchNeeded && readOnlyStateBefore) {\n return await executeReadOnlyWorkflow(cwd, stateMachine, readOnlyStateBefore, fastTrack);\n }\n\n stateMachine.transitionTo(\"IMPLEMENTED\");\n checkBranchSafety();\n\n const finalizer = new Finalizer({ cwd, fastTrack });\n const snapshotRef = { current: await finalizer.snapshotManager.capture() };\n\n const { result: valResult, validateWorkflow } = await runValidation(plan, taskSlug, cwd, gateResult, naturalRequest, delegationController, stateMachine);\n let result = valResult;\n\n result = await runBoundedRemediation(\n plan,\n taskSlug,\n cwd,\n result,\n validateWorkflow,\n ledger,\n delegationController,\n stateMachine,\n checkBranchSafety,\n async () => {\n snapshotRef.current = await finalizer.snapshotManager.capture();\n }\n );\n\n if (isTerminalFailure(result.overallStatus)) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: Validation could not be resolved safely.`);\n }\n\n checkBranchSafety();\n\n let integrity = { valid: true, changes: { added: [], modified: [], deleted: [] } };\n if (!fastTrack) {\n const stab = await runFinalizerStabilization(\n plan,\n taskSlug,\n cwd,\n result,\n validateWorkflow,\n delegationController,\n finalizer,\n snapshotRef,\n checkBranchSafety\n );\n result = stab.result;\n integrity = stab.integrity;\n }\n\n let finalStatus = result.overallStatus;\n \n if (fastTrack) {\n finalStatus = await runFastTrackValidation(cwd, result, checkBranchSafety);\n } else if (!integrity.valid) {\n console.log(`\\n[FINALIZER BLOCKED] BLOCKED: workspace did not stabilize`);\n console.log(`Final changes detected:`, integrity.changes);\n finalStatus = \"FAIL_QUALITY_GATE\";\n } else {\n finalStatus = await runFidelityValidation(naturalRequest, result, finalizer);\n }\n\n const finalState = computeFinalState(finalStatus);\n stateMachine.transitionTo(finalState);\n\n await generateFinalHandoff(plan, taskSlug, cwd, finalState, result.evidence);\n\n return { ...result, overallStatus: finalStatus, stateHistory: stateMachine.getHistory() };\n } finally {\n if (plan && !plan.branchNeeded) {\n console.log(`\\n[READ-ONLY LEDGER] (In-Memory/Stdout)\\n${JSON.stringify(ledger.getEvents(), null, 2)}\\n`);\n } else {\n try {\n await ledger.save(`.ai-workflow/history/${taskSlug}-ledger.json`);\n } catch (err) {\n // ignore\n }\n }\n }\n}\n","import { existsSync, rmSync, lstatSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport readline from \"node:readline\";\n\ninterface CleanOptions {\n cwd: string;\n yes?: boolean;\n dryRun?: boolean;\n purgeAgents?: boolean;\n}\n\nfunction askConfirmation(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim().toLowerCase());\n });\n });\n}\n\nfunction isSymlink(filePath: string): boolean {\n try {\n return lstatSync(filePath).isSymbolicLink();\n } catch (_) {\n return false;\n }\n}\n\nexport async function runClean({ cwd, yes = false, dryRun = false, purgeAgents = false }: CleanOptions): Promise<void> {\n const targets = [\n \".ai-workflow\",\n \"opencode.jsonc\",\n \".workflow-state.json\",\n \"opencode\"\n ];\n\n const hasAgents = existsSync(join(cwd, \".agents\"));\n\n // Check what actually exists\n const existingTargets = targets\n .map(name => join(cwd, name))\n .filter(path => existsSync(path) || isSymlink(path));\n\n if (existingTargets.length === 0 && (!hasAgents || !purgeAgents)) {\n console.log(\"No AI Workflow configuration or files found in the current project.\");\n return;\n }\n\n console.log(\"\\n[AI WORKFLOW] De-initialization\");\n console.log(\"===============================\");\n\n if (dryRun) {\n console.log(\"[DRY RUN] The following items would be deleted:\");\n existingTargets.forEach(path => console.log(` - ${path}`));\n if (hasAgents && purgeAgents) {\n console.log(` - ${join(cwd, \".agents\")} (customizations folder)`);\n } else if (hasAgents) {\n console.log(` - NOTE: ${join(cwd, \".agents\")} exists but will NOT be deleted (run with --purge-agents to delete)`);\n }\n return;\n }\n\n // Interactive prompts if --yes / -y is not passed\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.log(\"Error: Non-interactive terminal detected. Run with --yes to bypass confirmation.\");\n if (process.env.NODE_ENV === \"test\") {\n // Allow tests to bypass TTY block if they mock/stub process.stdin\n } else {\n process.exit(1);\n }\n }\n\n const confirmDeinit = await askConfirmation(\"Are you sure you want to de-initialize AI Workflow from the project? [y/N] \");\n if (confirmDeinit !== \"y\" && confirmDeinit !== \"yes\") {\n console.log(\"Aborted.\");\n return;\n }\n\n if (hasAgents && !purgeAgents) {\n const confirmPurge = await askConfirmation(\"A custom '.agents' folder was detected. Do you want to purge it (this deletes custom prompts/rules/skills)? [y/N] \");\n if (confirmPurge === \"y\" || confirmPurge === \"yes\") {\n purgeAgents = true;\n }\n }\n }\n\n // Add .agents if requested and exists\n if (purgeAgents && hasAgents) {\n existingTargets.push(join(cwd, \".agents\"));\n }\n\n console.log(\"\\nRemoving files...\");\n for (const target of existingTargets) {\n try {\n if (isSymlink(target)) {\n unlinkSync(target);\n console.log(`Deleted symlink: ${target}`);\n } else {\n rmSync(target, { recursive: true, force: true });\n console.log(`Deleted directory/file: ${target}`);\n }\n } catch (error: any) {\n console.error(`Failed to delete ${target}: ${error.message}`);\n }\n }\n\n console.log(\"\\nAI Workflow has been successfully removed from this project.\");\n}\n","import { getPackageVersion } from \"../core/package-assets.js\";\nimport { runInit } from \"./commands/init.js\";\nimport { runDoctor } from \"./commands/doctor.js\";\nimport { runCollectEvidence } from \"./commands/collect-evidence.js\";\nimport { runMasterOrchestrator } from \"./commands/run.js\";\nimport { runExecute } from \"./commands/execute.js\";\nimport { runClean } from \"./commands/clean.js\";\n\nfunction printHelp() {\n console.log(`ai-workflow\n\nUsage:\n ai-workflow execute \"<request>\" [--task=<slug>] [--request=\"<request>\"]\n ai-workflow run --spec-path=<path>\n ai-workflow init [--yes] [--force] [--dry-run] [--no-install] [--no-overwrite] [--claude] [--codex] [--antigravity] [--profile=<profile>]\n ai-workflow validate [--a11y] [--visual-dist=<path>] [--port=<port>]\n ai-workflow collect-evidence [--task=<slug>] [--evidence-policy=<optional|required>] [--mode=<quick|standard|full>] [--dry-run] [--visual-dist=<path>] [--port=<port>]\n ai-workflow doctor\n ai-workflow clean [--yes] [--dry-run] [--purge-agents]\n\nCommands:\n execute Orchestrate execution of a natural request through the state machine\n run Proportionate orchestrator with branch safety, validation, and bounded remediation\n init Install AI workflow defaults (OpenCode). --profile=standard (default) or --profile=full (adds examples)\n collect-evidence Run observed project validation; persists EVIDENCE.json under required evidence policy\n doctor Verify local ai-workflow installation\n clean De-initialize and remove AI Workflow files and symlinks from the project\n`);\n}\n\ninterface ParsedFlags {\n yes: boolean;\n force: boolean;\n dryRun: boolean;\n noInstall: boolean;\n noOverwrite: boolean;\n claude: boolean;\n codex: boolean;\n antigravity: boolean;\n \"dev-mode\": boolean;\n specPath?: string;\n profile?: string;\n taskSlug?: string;\n mode?: string;\n evidencePolicy?: \"optional\" | \"required\";\n request?: string;\n visualDist?: string;\n port?: string;\n a11y: boolean;\n purgeAgents?: boolean;\n}\n\nfunction parseFlags(args: string[]): ParsedFlags {\n const specPathArg = args.find((arg) => arg.startsWith(\"--spec-path=\"));\n const profileEqArg = args.find((arg) => arg.startsWith(\"--profile=\"));\n const taskArg = args.find((arg) => arg.startsWith(\"--task=\"));\n const modeArg = args.find((arg) => arg.startsWith(\"--mode=\"));\n const evidencePolicyArg = args.find((arg) => arg.startsWith(\"--evidence-policy=\"));\n const requestArg = args.find((arg) => arg.startsWith(\"--request=\"));\n const visualDistArg = args.find((arg) => arg.startsWith(\"--visual-dist=\"));\n const portArg = args.find((arg) => arg.startsWith(\"--port=\"));\n const profileIdx = args.indexOf(\"--profile\");\n const profileVal = profileEqArg\n ? profileEqArg.replace(\"--profile=\", \"\")\n : profileIdx >= 0 && profileIdx + 1 < args.length && !args[profileIdx + 1].startsWith(\"--\")\n ? args[profileIdx + 1]\n : undefined;\n\n return {\n yes: args.includes(\"--yes\"),\n force: args.includes(\"--force\"),\n dryRun: args.includes(\"--dry-run\"),\n noInstall: args.includes(\"--no-install\"),\n noOverwrite: args.includes(\"--no-overwrite\"),\n claude: args.includes(\"--claude\"),\n codex: args.includes(\"--codex\"),\n antigravity: args.includes(\"--antigravity\"),\n \"dev-mode\": args.includes(\"--dev-mode\"),\n specPath: specPathArg ? specPathArg.replace(\"--spec-path=\", \"\") : undefined,\n profile: profileVal || undefined,\n taskSlug: taskArg ? taskArg.replace(\"--task=\", \"\") : undefined,\n mode: modeArg ? modeArg.replace(\"--mode=\", \"\") : undefined,\n evidencePolicy: evidencePolicyArg ? (evidencePolicyArg.replace(\"--evidence-policy=\", \"\") as any) : undefined,\n request: requestArg ? requestArg.replace(\"--request=\", \"\") : undefined,\n visualDist: visualDistArg ? visualDistArg.replace(\"--visual-dist=\", \"\") : undefined,\n port: portArg ? portArg.replace(\"--port=\", \"\") : undefined,\n a11y: args.includes(\"--a11y\"),\n purgeAgents: args.includes(\"--purge-agents\") || args.includes(\"--purge\")\n };\n}\n\ntype CommandHandler = (args: string[], flags: ParsedFlags) => Promise<void>;\n\nconst commandMap: Record<string, CommandHandler> = {\n execute: async (args, flags) => {\n const positionals = args.filter((arg) => !arg.startsWith(\"-\"));\n const request = flags.request || positionals.join(\" \");\n const result = await runExecute({\n cwd: process.cwd(),\n naturalRequest: request,\n taskSlug: flags.taskSlug\n });\n if (result && (result.overallStatus === \"FAIL_QUALITY_GATE\" || result.overallStatus === \"BLOCKED\" || result.overallStatus === \"FAIL\")) {\n process.exit(1);\n }\n },\n run: async (_, flags) => {\n await runMasterOrchestrator({\n cwd: process.cwd(),\n ...flags\n });\n },\n init: async (_, flags) => {\n await runInit({\n cwd: process.cwd(),\n ...flags\n });\n },\n \"collect-evidence\": async (_, flags) => {\n if (flags.mode && ![\"quick\", \"standard\", \"full\"].includes(flags.mode)) {\n throw new Error(\"--mode must be quick, standard, or full\");\n }\n await runCollectEvidence({ \n cwd: process.cwd(), \n taskSlug: flags.taskSlug, \n mode: flags.mode, \n evidencePolicy: flags.evidencePolicy,\n dryRun: flags.dryRun,\n visualDist: flags.visualDist,\n port: flags.port\n });\n },\n validate: async (_, flags) => {\n const { runValidate } = await import(\"./commands/validate.js\");\n await runValidate({\n cwd: process.cwd(),\n taskSlug: flags.taskSlug,\n a11y: flags.a11y,\n visualDist: flags.visualDist,\n port: flags.port\n });\n },\n doctor: async () => {\n await runDoctor({ cwd: process.cwd() });\n },\n clean: async (_, flags) => {\n await runClean({\n cwd: process.cwd(),\n ...flags\n });\n }\n};\n\nexport async function runCli(args: string[]): Promise<void> {\n const [command] = args;\n\n if (command === \"--version\" || command === \"-v\") {\n console.log(getPackageVersion() || \"unknown\");\n return;\n }\n\n if (!command || command === \"--help\" || command === \"-h\") {\n printHelp();\n return;\n }\n\n const handler = commandMap[command];\n if (handler) {\n const argsSlice = args.slice(1);\n const flags = parseFlags(argsSlice);\n await handler(argsSlice, flags);\n return;\n }\n\n throw new Error(`unknown command: ${command}`);\n}\n\nrunCli(process.argv.slice(2)).catch((error) => {\n console.error(`ai-workflow error: ${error.message}`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,SAAQ;AACf,OAAOC,WAAU;;;ACDjB,OAAO,UAAU;;;ACGjB,IAAM,eAAuC;AAAA,EAC3C,sBAAsB;AAAA;AAAA;AAAA;AAAA;AACxB;AAEA,IAAM,sBAAgC;AAAA,EACpC;AAAA,EACA;AAAA,E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AQ,MAAM,sBAAsB,MAAM,OAAO,EAAE;AACnD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["fs","path","exists","path","fs","path","path","fs","path","path","fs","path","exists","fs","path","fs","path","fs","path","fs","path","fs","path","fs","path","path","fs","next","fs","path","fs","path","execSync","fs","path","path","fs","path","fs","fs","path","execSync","getChangedFiles","fs","path","execSync","combineValidation","isSymlink","path"]}