#!/usr/bin/env node
import'./chunk-5TAVYPOV.js';import*as o from'fs';import*as p from'path';import s from'chalk';import we from'ora';import*as F from'js-yaml';import {createRequire}from'module';function K(e,...t){return o.existsSync(p.join(e,...t))}function z(e,...t){o.mkdirSync(p.join(e,...t),{recursive:true});}function A(e){let t=p.join(e,".paradigm","config.yaml");if(!o.existsSync(t))return null;try{return F.load(o.readFileSync(t,"utf8"))}catch{return null}}function I(e){let t=p.join(e,".paradigm","config.yaml");return o.existsSync(t)?o.readFileSync(t,"utf8"):null}function x(e,t){o.writeFileSync(p.join(e,".paradigm","config.yaml"),t,"utf8");}function G(e){try{let t=n=>{let i=o.readdirSync(n,{withFileTypes:!0});for(let r of i)if(r.isDirectory()){if(t(p.join(n,r.name)))return !0}else if(r.name.endsWith(".yaml")&&!r.name.endsWith(".migrated")&&r.name!=="index.yaml"&&r.name!=="arc.yaml")return !0;return !1};return t(e)}catch{return  false}}function D(e,t){return t in e||t.replace(/-/g,"_")in e||t.replace(/_/g,"-")in e}var Q={id:"legacy-file-to-directory",introducedIn:"1.0.0",description:"Convert .paradigm file to .paradigm/ directory",category:"directory",auto:true,async check(e){let t=p.join(e,".paradigm");return o.existsSync(t)?o.statSync(t).isFile()?{needed:true,reason:".paradigm is a file, not a directory",details:["Legacy format \u2014 must convert to directory"]}:{needed:false,reason:".paradigm/ is already a directory"}:{needed:false,reason:"No .paradigm found"}},async apply(e,t){if(t.dryRun)return {status:"skipped",message:"Would convert .paradigm file to directory"};let n=p.join(e,".paradigm"),i=p.join(e,".paradigm.backup"),r=o.readFileSync(n,"utf8");return o.copyFileSync(n,i),o.unlinkSync(n),o.mkdirSync(n,{recursive:true}),o.mkdirSync(p.join(n,"specs"),{recursive:true}),o.mkdirSync(p.join(n,"docs"),{recursive:true}),o.mkdirSync(p.join(n,"prompts"),{recursive:true}),o.writeFileSync(p.join(n,"config.yaml"),r,"utf8"),{status:"applied",message:"Converted .paradigm file to directory (backup at .paradigm.backup)",filesCreated:[".paradigm/",".paradigm/config.yaml",".paradigm/specs/",".paradigm/docs/",".paradigm/prompts/"]}}},X={id:"legacy-scan-index-location",introducedIn:"1.0.0",description:"Move .paradigm-scan-index.json into .paradigm/",category:"format",auto:true,async check(e){let t=p.join(e,".paradigm-scan-index.json");return o.existsSync(t)?{needed:true,reason:"Scan index at root level needs relocation"}:{needed:false,reason:"No legacy scan index at root"}},async apply(e,t){if(t.dryRun)return {status:"skipped",message:"Would move .paradigm-scan-index.json"};let n=p.join(e,".paradigm-scan-index.json"),i=p.join(e,".paradigm","scan-index.json");return o.renameSync(n,i),{status:"applied",message:"Moved scan index into .paradigm/",filesModified:[".paradigm/scan-index.json"]}}};function w(e,t,n,i,r){return {id:e,introducedIn:t,description:i,category:"directory",auto:true,async check(a){return K(a,".paradigm",n)?{needed:false,reason:`.paradigm/${n}/ already exists`}:{needed:true,reason:`Missing .paradigm/${n}/`,details:r}},async apply(a,d){return d.dryRun?{status:"skipped",message:`Would create .paradigm/${n}/`}:(z(a,".paradigm",n),{status:"applied",message:`Created .paradigm/${n}/`,filesCreated:[`.paradigm/${n}/`]})}}}var Z=w("add-specs-directory","3.0.0","specs","Create .paradigm/specs/ for specifications",["Stores logger spec, symbols spec, scan spec, etc."]),ee=w("add-docs-directory","3.0.0","docs","Create .paradigm/docs/ for documentation",["Stores commands, patterns, troubleshooting docs"]),te=w("add-prompts-directory","3.0.0","prompts","Create .paradigm/prompts/ for task templates",["Stores add-feature, refactor, trace-flow prompts"]),ne={id:"add-tag-bank-config",introducedIn:"3.2.0",description:"Add tag-bank section to config.yaml",category:"config",auto:true,async check(e){let t=A(e);return t?D(t,"tag-bank")?{needed:false,reason:"tag-bank already configured"}:{needed:true,reason:"Missing tag-bank configuration"}:{needed:false,reason:"No config.yaml found"}},async apply(e,t){if(t.dryRun)return {status:"skipped",message:"Would add tag-bank to config.yaml"};let n=I(e);return n?(x(e,n.trimEnd()+`
`+`
# Tag bank configuration
tag-bank:
  file: tags.yaml
  core-tags:
    - feature
    - integration
    - state
    - idea
    - deprecated
    - critical
    - security
    - compliance
  allow-suggestions: true
`),{status:"applied",message:"Added tag-bank to config.yaml",filesModified:[".paradigm/config.yaml"]}):{status:"error",message:"Cannot read config.yaml"}}},se={id:"add-purpose-required-config",introducedIn:"3.3.0",description:"Add purpose-required patterns to config.yaml",category:"config",auto:true,async check(e){let t=A(e);return t?D(t,"purpose-required")?{needed:false,reason:"purpose-required already configured"}:{needed:true,reason:"Missing purpose-required patterns"}:{needed:false,reason:"No config.yaml found"}},async apply(e,t){if(t.dryRun)return {status:"skipped",message:"Would add purpose-required to config.yaml"};let n=I(e);return n?(x(e,n.trimEnd()+`
`+`
# Where .purpose files should exist
purpose-required:
  - pattern: "src/*"
    depth: 1
  - pattern: "lib/*"
    depth: 1
  - pattern: "packages/*"
    depth: 1
`),{status:"applied",message:"Added purpose-required to config.yaml",filesModified:[".paradigm/config.yaml"]}):{status:"error",message:"Cannot read config.yaml"}}},re=w("add-lore-directory","3.7.0","lore","Create .paradigm/lore/ for project reflections and decisions",["Stores lore entries (reflections, decisions, arcs)"]),oe=w("add-tasks-directory","3.8.0","tasks","Create .paradigm/tasks/ for work item tracking",["Stores task YAML files for persistent task management"]),ie=w("add-personas-directory","3.9.0","personas","Create .paradigm/personas/ for actor-driven journey testing",["Stores .persona files with traits, triggers, fixtures, journey steps"]),ae=w("add-protocols-directory","3.10.0","protocols","Create .paradigm/protocols/ for repeatable implementation patterns",["Stores protocol YAML files captured from implementation workflows"]),ce=w("add-habits-directory","3.14.0","habits","Create .paradigm/habits/ for session habit tracking"),de=w("add-wisdom-directory","3.5.0","wisdom","Create .paradigm/wisdom/ for antipatterns and team knowledge",["Stores antipatterns.yaml and other team knowledge files"]),le=w("add-history-directory","3.6.0","history","Create .paradigm/history/ for symbol change history",["Stores log.jsonl for commit-level symbol tracking"]),pe={id:"migrate-assessments-to-lore",introducedIn:"3.19.0",description:"Convert old assessment entries to lore format",category:"schema",auto:false,async check(e){let t=p.join(e,".paradigm","assessments");if(!o.existsSync(t))return {needed:false,reason:"No assessments directory found"};try{return G(t)?{needed:!0,reason:"Unmigrated assessment entries found",details:["Run: paradigm lore migrate-assessments --dry-run"]}:{needed:!1,reason:"All assessments already migrated"}}catch{return {needed:false,reason:"Cannot read assessments directory"}}},async apply(e,t){return {status:"skipped",message:"Run `paradigm lore migrate-assessments` manually"}}},ge={id:"add-component-types-config",introducedIn:"3.33.0",description:"Add component_types glossary to config.yaml",category:"config",auto:true,async check(e){let t=A(e);return t?D(t,"component_types")?{needed:false,reason:"component_types already configured"}:{needed:true,reason:"Missing component_types glossary"}:{needed:false,reason:"No config.yaml found"}},async apply(e,t){if(t.dryRun)return {status:"skipped",message:"Would add component_types to config.yaml"};let n=I(e);return n?(x(e,n.trimEnd()+`
`+`
# Component types glossary \u2014 defines the project vocabulary for the \`type\` field on components
component_types:
  command: "CLI command handler \u2014 registers subcommand, parses args, calls core logic"
  tool: "MCP tool definition + handler \u2014 serves AI agents via JSON-RPC"
  utility: "Shared helper function or module \u2014 no side effects, pure logic"
  engine: "Stateful processing core \u2014 owns data transformation lifecycle"
  loader: "Reads and parses data sources into typed structures"
  writer: "Writes structured data to files (YAML, JSON)"
  service: "Business logic coordinator \u2014 orchestrates tools, loaders, writers"
  model: "Data shape \u2014 TypeScript interface or type definition"
  view: "UI rendering unit \u2014 SwiftUI view, React component"
  provider: "Protocol-conforming platform capability wrapper \u2014 owns lifecycle"
  manager: "Stateful coordinator that owns child lifecycles"
  detector: "Observes external state and emits events"
  router: "Maps input signals to targets based on rules"
  filter: "Transforms or smooths data in a pipeline"
  store: "Persistent or reactive state container"
  handler: "Event handler, webhook receiver, or request processor"
  config: "Configuration, environment, constants"
`),{status:"applied",message:"Added component_types glossary to config.yaml",filesModified:[".paradigm/config.yaml"]}):{status:"error",message:"Cannot read config.yaml"}}},ue={id:"add-discipline-config",introducedIn:"3.4.0",description:"Add discipline field to config.yaml",category:"config",auto:true,async check(e){let t=A(e);return t?D(t,"discipline")?{needed:false,reason:"discipline already set"}:{needed:true,reason:"Missing discipline field"}:{needed:false,reason:"No config.yaml found"}},async apply(e,t){if(t.dryRun)return {status:"skipped",message:"Would add discipline to config.yaml"};let n=I(e);if(!n)return {status:"error",message:"Cannot read config.yaml"};let i=n.replace(/^(project:\s*.+)$/m,`$1
discipline: auto`);return i===n?x(e,n.trimEnd()+`
discipline: auto
`):x(e,i),{status:"applied",message:"Added discipline: auto to config.yaml",filesModified:[".paradigm/config.yaml"]}}},fe={id:"sync-templates",introducedIn:"evergreen",description:"Update specs/ and docs/ from installed CLI templates",category:"template",auto:true,async check(e){let t=$();if(!t)return {needed:false,reason:"Templates directory not found"};let n=[],i=["specs","docs","prompts"];for(let r of i){let a=p.join(t,r),d=p.join(e,".paradigm",r);if(o.existsSync(a))try{let g=o.readdirSync(a).filter(m=>o.statSync(p.join(a,m)).isFile());for(let m of g)o.existsSync(p.join(d,m))||n.push(`${r}/${m}`);}catch{}}return n.length===0?{needed:false,reason:"All templates are up to date"}:{needed:true,reason:`${n.length} new template file(s) available`,details:n.map(r=>`New: ${r}`)}},async apply(e,t){let n=$();if(!n)return {status:"error",message:"Templates directory not found"};let i=p.basename(e),r=[],a=["specs","docs","prompts"];for(let d of a){let g=p.join(n,d),m=p.join(e,".paradigm",d);if(o.existsSync(g)){t.dryRun||o.mkdirSync(m,{recursive:true});try{let S=o.readdirSync(g,{withFileTypes:!0});for(let k of S){if(k.isDirectory())continue;let M=p.join(m,k.name);if(!o.existsSync(M)){if(t.dryRun){r.push(`${d}/${k.name}`);continue}let c=o.readFileSync(p.join(g,k.name),"utf8");c=c.replace(/\{\{PROJECT_NAME\}\}/g,i),o.writeFileSync(M,c,"utf8"),r.push(`${d}/${k.name}`);}}}catch{}}}return t.dryRun?{status:"skipped",message:`Would copy ${r.length} template file(s)`}:r.length===0?{status:"skipped",message:"No new templates to sync"}:{status:"applied",message:`Synced ${r.length} template file(s)`,filesCreated:r.map(d=>`.paradigm/${d}`)}}},me={id:"refresh-hooks",introducedIn:"evergreen",description:"Reinstall hook scripts from plugin",category:"hook",auto:true,async check(e){let t=[p.join(e,".claude","hooks"),p.join(e,".cursor","hooks")];for(let i of t)if(o.existsSync(i))try{if(o.readdirSync(i).some(a=>a.includes("paradigm")))return {needed:!1,reason:"Hooks are installed"}}catch{}let n=p.join(e,".claude","settings.local.json");if(o.existsSync(n))try{if(JSON.parse(o.readFileSync(n,"utf8")).hooks)return {needed:!1,reason:"Plugin-managed hooks are configured"}}catch{}return {needed:true,reason:"No paradigm hooks found"}},async apply(e,t){if(t.dryRun)return {status:"skipped",message:"Would reinstall hooks"};try{let{hooksInstallCommand:n}=await import('./hooks-IG2GOAHP.js');return await n({force:!0}),{status:"applied",message:"Hooks reinstalled"}}catch(n){return {status:"error",message:`Hook install failed: ${n.message}`}}}},b=[Q,X,Z,ee,te,ne,se,ue,de,le,re,oe,ie,ae,ce,pe,ge,fe,me];var he=createRequire(import.meta.url),{version:W}=he("../package.json");function C(e){let t=p.join(e,".paradigm","migrate.yaml");if(!o.existsSync(t))return null;try{let n=o.readFileSync(t,"utf8");return F.load(n)}catch{return null}}async function V(e){let t=p.join(e,".paradigm"),n=C(e),i=n?.applied.map(l=>l.id)??[],r="unknown",a=p.join(t,"config.yaml");if(o.existsSync(a))try{let l=F.load(o.readFileSync(a,"utf8"));r=String(l.version??"unknown");}catch{}let g=["specs","docs","prompts","lore","tasks","protocols","personas"].filter(l=>!o.existsSync(p.join(t,l))),m=["discipline","tag-bank","purpose-required","component_types"],S=[];if(o.existsSync(a))try{let l=F.load(o.readFileSync(a,"utf8"));S=m.filter(h=>{let j=h.replace(/-/g,"_");return !(h in l)&&!(j in l)&&!(h.replace(/_/g,"-")in l)});}catch{}let k=[],M=$();if(M){let l=["specs","docs"];for(let h of l){let j=p.join(M,h),L=p.join(t,h);if(o.existsSync(j)&&o.existsSync(L)){let J=o.readdirSync(j).filter(R=>!o.statSync(p.join(j,R)).isDirectory());for(let R of J){let Y=p.join(L,R);o.existsSync(Y)||k.push(`${h}/${R}`);}}}}let c=!o.existsSync(p.join(e,".claude","hooks")),u=[];for(let l of b){let h=l.introducedIn==="evergreen";if(i.includes(l.id)&&!h)continue;(await l.check(e)).needed&&u.push(l);}return {configVersion:r,cliVersion:W,pendingMigrations:u,appliedIds:i,health:{missingDirectories:g,missingConfigFields:S,staleTemplates:k,hooksOutdated:c}}}async function U(e){let t=[],n=new Date().toISOString();for(let i of b){if(i.introducedIn==="evergreen")continue;(await i.check(e)).needed||t.push({id:i.id,appliedAt:n,cliVersion:W});}return t}function $(){let e=new URL(import.meta.url).pathname,t=p.dirname(e),n=[p.join(t,"..","..","..","templates","paradigm"),p.join(t,"..","..","templates","paradigm"),p.join(t,"..","templates","paradigm")];for(let i of n)if(o.existsSync(i))return i;return null}var ke=createRequire(import.meta.url),{version:N}=ke("../package.json");async function B(e){let t=C(e);if(t)return t;let n=await U(e);return {version:"1.0",cliVersion:N,lastMigrated:new Date().toISOString(),applied:n}}function _(e,t){let n=p.join(e,".paradigm","migrate.yaml");o.mkdirSync(p.dirname(n),{recursive:true}),t.cliVersion=N,t.lastMigrated=new Date().toISOString(),o.writeFileSync(n,F.dump(t,{indent:2,lineWidth:120,noRefs:true,sortKeys:false,quotingType:'"'}),"utf8");}async function E(e,t,n,i){let r={applied:0,skipped:0,errors:0,manual:0,results:[]},a=new Date().toISOString();for(let d of t){if(!d.auto){r.manual++,r.results.push({id:d.id,result:{status:"skipped",message:"Manual review recommended"}});continue}try{let g=await d.apply(e,n);r.results.push({id:d.id,result:g}),g.status==="applied"?(r.applied++,i.applied.push({id:d.id,appliedAt:a,cliVersion:N})):g.status==="skipped"?r.skipped++:r.errors++;}catch(g){r.errors++,r.results.push({id:d.id,result:{status:"error",message:g.message}});}}return r}async function _e(e={}){let t=process.cwd(),n=p.join(t,".paradigm");if((!o.existsSync(n)||!o.statSync(n).isDirectory())&&!(o.existsSync(n)&&o.statSync(n).isFile())){e.quiet||console.log(s.yellow("\n  No .paradigm/ directory found. Run `paradigm init` or `paradigm shift` first.\n"));return}let i=we();e.quiet||i.start("Detecting project state...");let r=await V(t);e.quiet||i.stop();let a=await B(t),d=r.pendingMigrations;if(e.only&&e.only.length>0&&(d=d.filter(c=>e.only.includes(c.id))),e.category&&(d=d.filter(c=>c.category===e.category)),e.force){let c=e.only?b.filter(u=>e.only.includes(u.id)):e.category?b.filter(u=>u.category===e.category):b;d=[];for(let u of c)((await u.check(t)).needed||e.force)&&d.push(u);}let g=d.filter(c=>c.auto),m=d.filter(c=>!c.auto);if(e.list){Me(a,r,e);return}if(e.quiet){if(g.length===0)return;let c=await E(t,g,e,a);return _(t,a),c}let S=C(t);if(console.log(s.blue(`
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(s.blue("\u2502")+s.white.bold("  paradigm migrate                                ")+s.blue("\u2502")),console.log(s.blue("\u2502")+s.gray("  Bring your project up to date                  ")+s.blue("\u2502")),console.log(s.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
`)),console.log(s.white(`  Project:        ${s.cyan(p.basename(t))}`)),console.log(s.white(`  Config version: ${s.cyan(r.configVersion)}`)),console.log(s.white(`  CLI version:    ${s.cyan(r.cliVersion)}`)),console.log(s.white(`  Last migrated:  ${s.cyan(S?.lastMigrated??"never")}`)),console.log(""),d.length===0){console.log(s.green(`  All migrations are up to date.
`)),S||(_(t,a),e.verbose&&console.log(s.gray(`  Created .paradigm/migrate.yaml with bootstrap state.
`)));return}if(e.verbose){let c=r.health;c.missingDirectories.length>0&&console.log(s.yellow(`  Missing directories: ${c.missingDirectories.join(", ")}`)),c.missingConfigFields.length>0&&console.log(s.yellow(`  Missing config fields: ${c.missingConfigFields.join(", ")}`)),c.staleTemplates.length>0&&console.log(s.yellow(`  New templates available: ${c.staleTemplates.join(", ")}`)),c.hooksOutdated&&console.log(s.yellow("  Hooks need installation")),console.log("");}let k=g.length,M=m.length;if(console.log(s.white(`  Pending Migrations (${k} auto${M>0?`, ${M} manual`:""})`)),console.log(s.gray("  "+"\u2500".repeat(49))),g.length>0){console.log(s.white("  AUTO:"));for(let c of g){let u=c.id.padEnd(30);if(console.log(s.green("  \u2713 ")+s.white(u)+s.gray(c.description)),e.verbose){let l=await c.check(t);if(l.details)for(let h of l.details)console.log(s.gray("    \u21B3 ")+s.gray(h));}}}if(m.length>0){console.log(""),console.log(s.white("  MANUAL (review recommended):"));for(let c of m){let u=c.id.padEnd(30);console.log(s.yellow("  \u25CB ")+s.white(u)+s.gray(c.description));let l=await c.check(t);if(l.details)for(let h of l.details)console.log(s.gray("    \u2192 ")+s.cyan(h));}}if(console.log(""),e.dryRun){console.log(s.yellow(`  Dry run \u2014 no changes applied.
`));return}if(g.length>0){if(!e.apply){let u=(await import('prompts')).default,{confirm:l}=await u({type:"confirm",name:"confirm",message:`Apply ${g.length} automatic migration(s)?`,initial:true});if(!l){console.log(s.gray(`
  Skipped. Run with --apply to auto-apply.
`));return}}i.start(`Applying ${g.length} migration(s)...`);let c=await E(t,g,e,a);i.stop();for(let{id:u,result:l}of c.results)l.status==="applied"?console.log(s.green("  \u2713 ")+s.white(u)+s.gray(` \u2014 ${l.message}`)):l.status==="error"?console.log(s.red("  \u2717 ")+s.white(u)+s.gray(` \u2014 ${l.message}`)):console.log(s.yellow("  \u25CB ")+s.white(u)+s.gray(` \u2014 ${l.message}`));console.log(""),console.log(s.green(`  Applied ${c.applied} migration(s).`)),c.errors>0&&console.log(s.red(`  ${c.errors} error(s).`));}_(t,a),console.log(s.gray("  Updated .paradigm/migrate.yaml")),console.log("");}function Me(e,t,n){let i=new Set(e.applied.map(a=>a.id)),r=new Set(t.pendingMigrations.map(a=>a.id));console.log(s.blue(`
  All Migrations`)),console.log(s.gray("  "+"\u2500".repeat(70))),console.log(s.gray("  Status  ")+s.gray("ID".padEnd(34))+s.gray("Version".padEnd(12))+s.gray("Category")),console.log(s.gray("  "+"\u2500".repeat(70)));for(let a of b){let d;i.has(a.id)?d=s.green("  \u2713     "):r.has(a.id)?d=a.auto?s.yellow("  \u25CF     "):s.yellow("  \u25CB     "):d=s.gray("  -     ");let g=a.id.padEnd(34),m=(a.introducedIn==="evergreen"?"evergreen":a.introducedIn).padEnd(12),S=a.category;console.log(d+s.white(g)+s.gray(m)+s.gray(S)),n.verbose&&console.log(s.gray(`          ${a.description}`));}console.log(""),console.log(s.gray("  \u2713 = applied  \u25CF = pending (auto)  \u25CB = pending (manual)  - = not needed")),console.log("");}export{_e as migrateCommand};