@pharn-dev/pharn 0.18.5 → 0.20.0

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.
@@ -0,0 +1,32 @@
1
+ import{archetypesFromSignals,classifyEntry,evidenceFor,isBaseDir,isNextConfigName,mergeSignals,packageFacts,recordedArchetypes}from"./chunk-IC45C3NS.js";import{installPrepared,manifestSources,prepareInstall,scanDest,upstreamSettingsCopyable}from"./chunk-NVSBRL4G.js";import{CapabilityRemovalError,absentSurfaceLines,deleteRootDocs,planCapabilityRemovals,planRootMigration,readUpstreamModels,removalBackups,removalBackupsNow,resolveCapabilities,rootMigrationNoteLines,runNodePrereq}from"./chunk-7LD2OYB4.js";import"./chunk-PDDT7V7X.js";import{minCliGate}from"./chunk-DFMTJQO7.js";import{deleteCapabilityDir}from"./chunk-6LOUFC5E.js";import{BACKUP_DIR,ProjectLockedError,applyGitignore,backupAction,backupDirIgnored,createBackup,gitignoreLines,gitignoreReport,interactiveAllowed,planGitignore,printBackupNotice,replacedConfigBackup,withProjectLock}from"./chunk-ZQWLF3HH.js";import"./chunk-BCURDSJC.js";import{applyPrettierignore,cap,checkModelsBlock,modelsLabelLines,planPrettierignore,prettierignoreLines,prettierignoreReport,resolvedStageLines,serializeJsonReport}from"./chunk-B4EM6WAR.js";import{diffHookWiring,findOrphans,freshSettingsHookLines,preservedSettingsHookLines,upstreamSettingsSummary}from"./chunk-KKY6HERY.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-62AJFPPH.js";import"./chunk-KZCUUHJT.js";import{DEFAULT_INIT_REF,ReleaseResolveError,channelOf,resolveSource,sourceLabel}from"./chunk-LVAJFL6J.js";import{MODELS_RECORD_KEY,PHARN_CONFIG_FILE,UpstreamManifestError,absentInstallSurfaces,buildRecords,carriedSettingsRecord,collectExpectedInstallPaths,configLayout,conflictingWriteTargets,detectLayout,layoutPaths,modelsRecordHash,readRecords,readSkillsVersion,recordsBaseline,recordsUnderCapabilities,warnIfOlderCli,writeRecords}from"./chunk-FUQURK5N.js";import{CLAUDE_AGENTS_DIR,CLAUDE_SETTINGS_FILE,FIRST_FEATURE_COMMAND,PHARN_VERSION,REPO_URL}from"./chunk-SQLIXTIY.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{assertConfigFingerprintUnchanged,color_default,configFingerprint,configPath,readJsonBounded,readPharnConfig,row,userOwnedConfigEntries,writePharnConfig}from"./chunk-LF4PFADC.js";import{VERSION_RE,isPlainObject,safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";import{intro,log as log3,note as note3,outro as outro2,spinner as spinner2}from"@clack/prompts";var LOGO=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D"];function showBanner(){console.log();for(let line of LOGO)console.log(` ${color_default.cyan(color_default.bold(line))}`);console.log(),console.log(` ${color_default.dim(`Ship features right with Claude Code \xB7 v${PHARN_VERSION}`)}`),console.log()}import{closeSync,constants,fstatSync,lstatSync,openSync,readSync,readdirSync}from"node:fs";import{join,resolve}from"node:path";var SKIP_DIRS=new Set(["node_modules",".git","dist","build",".next","out","coverage",".turbo",".vercel",".nuxt",".svelte-kit",".astro",".cache",".parcel-cache","storybook-static","__pycache__",".yarn"]),ECOSYSTEM_DIRS=new Map([["target",{siblings:["Cargo.toml","pom.xml","build.sbt"]}],["vendor",{siblings:["go.mod","composer.json","Gemfile"]}],["venv",{inside:"pyvenv.cfg"}],[".venv",{inside:"pyvenv.cfg"}]]);function isEcosystemTree(dir,name,siblingFiles){let marker=ECOSYSTEM_DIRS.get(name.toLowerCase());return marker===void 0?!1:"siblings"in marker?marker.siblings.some(file=>siblingFiles.has(file)):lstatSync(join(dir,name,marker.inside),{throwIfNoEntry:!1})?.isFile()===!0}var WALK_LIMITS=Object.freeze({maxDepth:24,maxEntries:5e4}),NO_PACKAGE_JSON={jsProject:!1,nextDependency:!1},NO_SIGNALS={ssr:!1,backend:!1,clientUi:!1},SIGNAL_KEYS=["ssr","backend","clientUi"];function scanFileTree(root,facts=NO_PACKAGE_JSON,limits=WALK_LIMITS){let acc={ssr:!1,backend:!1,clientUi:!1},evidence={},pkg=facts.packageSignals??NO_SIGNALS,budget=limits.maxEntries,truncated=!1,settled=()=>(pkg.ssr||acc.ssr)&&(pkg.backend||acc.backend),readEntries=dir=>{try{return readdirSync(dir,{withFileTypes:!0})}catch{return[]}},walk=(dir,depth,segments,names,inherited)=>{if(budget<=0&&truncated||settled())return;let entries=readEntries(dir).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0),siblingFiles=new Set(entries.filter(e=>e.isFile()).map(e=>e.name)),ctx=isBaseDir(segments)?{jsProject:facts.jsProject,baseDepth:segments.length,nextBase:segments.length===0&&facts.nextDependency||[...siblingFiles].some(isNextConfigName)}:inherited;for(let entry of entries){if(settled())return;let name=entry.name;if(entry.isSymbolicLink())continue;let isDir=entry.isDirectory();if(isDir&&SKIP_DIRS.has(name.toLowerCase())||isDir&&isEcosystemTree(dir,name,siblingFiles)||!isDir&&name.toLowerCase().startsWith(".env")||!isDir&&!entry.isFile())continue;if(depth>limits.maxDepth||budget<=0){truncated=!0;return}budget-=1;let sig=classifyEntry(name,isDir,segments,ctx);for(let key2 of SIGNAL_KEYS)sig[key2]&&evidence[key2]===void 0&&(evidence[key2]=[...names,name].join("/")+(isDir?"/":""));acc=mergeSignals(acc,sig),isDir&&walk(join(dir,name),depth+1,[...segments,name.toLowerCase()],[...names,name],ctx)}};return walk(root,0,[],[],{jsProject:facts.jsProject,baseDepth:0,nextBase:!1}),{signals:acc,evidence,truncated:truncated&&!settled()}}var MAX_PACKAGE_JSON_BYTES=4*1024*1024,PKG_OPEN_FLAGS=constants.O_RDONLY|(constants.O_NONBLOCK??0);function readPackageJsonText(pkgPath){let fd;try{fd=openSync(pkgPath,PKG_OPEN_FLAGS)}catch{return null}try{if(!fstatSync(fd).isFile())return null;let buf=Buffer.alloc(MAX_PACKAGE_JSON_BYTES+1),total=0;for(;total<buf.length;){let n=readSync(fd,buf,total,buf.length-total,null);if(n===0)break;total+=n}return total>MAX_PACKAGE_JSON_BYTES?null:buf.subarray(0,total).toString("utf8").replace(/^\uFEFF/,"")}catch{return null}finally{closeSync(fd)}}function readPackageFacts(cwd){let empty=packageFacts({}),text=readPackageJsonText(resolve(cwd,"package.json"));if(text===null)return{pkg:empty,packageJsonFound:!1};try{let parsed=JSON.parse(text);return typeof parsed!="object"||parsed===null||Array.isArray(parsed)?{pkg:empty,packageJsonFound:!1}:{pkg:packageFacts(parsed),packageJsonFound:!0}}catch{return{pkg:empty,packageJsonFound:!1}}}function detectArchetypesFromProject(cwd){let{pkg,packageJsonFound}=readPackageFacts(cwd),tree=scanFileTree(cwd,{jsProject:packageJsonFound,nextDependency:pkg.nextDependency,packageSignals:pkg.signals}),archetypes=archetypesFromSignals(mergeSignals(pkg.signals,tree.signals));return{archetypes,evidence:evidenceFor(archetypes,pkg.evidence,tree.evidence,pkg.devEvidence),truncated:tree.truncated}}import{existsSync as existsSync2}from"node:fs";import{existsSync}from"node:fs";var MAX_LISTED=10,DRIFT_MARKERS={modified:"(edited)",unrecorded:"(no pharn record)",unverifiable:"(differs from upstream)"},DRIFT_LABEL_ORDER=["modified","unrecorded","unverifiable"],CONFIG_MARKER="(will be rewritten \u2014 backed up first)";function planWriteTargets(params){let{repoDir,projectRoot,capabilities,manifest,records}=params,removals=params.removals??[],conflicts=conflictingWriteTargets({repoDir,projectRoot,capabilities,layout:detectLayout(repoDir),expected:manifest});if(conflicts.length===0)return{conflicts,labels:new Map,configBackedUp:!1,removals};let labels=params.labels??scanDest({repoDir,projectRoot,rels:conflicts.filter(p=>manifest.has(p)),sources:manifestSources(repoDir,manifest),records}).labels,configBackedUp=conflicts.includes(PHARN_CONFIG_FILE)&&replacedConfigBackup(projectRoot).length>0,rank=p=>{let label=labels.get(p);return label!==void 0?DRIFT_LABEL_ORDER.indexOf(label):configBackedUp&&p===PHARN_CONFIG_FILE?DRIFT_LABEL_ORDER.length:DRIFT_LABEL_ORDER.length+1};return{conflicts:[...conflicts].sort((a,b)=>rank(a)-rank(b)),labels,configBackedUp,removals}}function removalLines(removals){return removals.filter(r=>r.present).map(r=>{let n=r.backups.length;return n===0?` \u2022 ${r.dir}/ (${r.cap.role}:${r.cap.name})`:` \u2022 ${r.dir}/ (${r.cap.role}:${r.cap.name} \u2014 ${n} file(s) backed up to ${BACKUP_DIR}/ first)`})}function targetLines(plan,max){let{conflicts:paths,labels,configBackedUp}=plan,shown=max===void 0?paths:paths.slice(0,max),lines=shown.map(p=>{let label=labels.get(p);return label!==void 0?` \u2022 ${p} ${DRIFT_MARKERS[label]}`:configBackedUp&&p===PHARN_CONFIG_FILE?` \u2022 ${p} ${CONFIG_MARKER}`:` \u2022 ${p}`}),more=paths.length-shown.length;return more>0&&lines.push(` \u2026and ${more} more`),lines}var OverwriteRefusedError=class extends Error{constructor(message){super(message),this.name="OverwriteRefusedError"}},YES_WAYS_FORWARD=["--yes never overwrites. Run `pharn init` in a terminal to review and confirm the overwrite,","`pharn init --dry-run` to see the whole plan, or `pharn update` to refresh an existing install."];function existingConfigRefusal(projectRoot){return existsSync(safeJoin(projectRoot,PHARN_CONFIG_FILE))?[`pharn init --yes installs only into a project where none of its files exists yet, and ${PHARN_CONFIG_FILE} already exists.`,...YES_WAYS_FORWARD].join(`
2
+ `):null}function refuseExistingTargets(plan){if(plan.conflicts.length===0)return;let n=plan.conflicts.length;throw new OverwriteRefusedError([`pharn init --yes installs only into a project where none of its files exists yet, and ${n} of them already exist:`,...targetLines(plan,MAX_LISTED),...YES_WAYS_FORWARD].join(`
3
+ `))}function capabilityKey(cap2){return`${cap2.role}:${cap2.name}`}var UNREADABLE_REASON_MAX=200;function readPreviousConfig(cwd){let fingerprint=configFingerprint(cwd);try{let config=readPharnConfig(cwd),unreadable=config===null&&fingerprint!=="absent"?describeUnreadConfig(cwd):null;return{fingerprint,config,unreadable}}catch(err){let reason=escapeUnsafe(firstSentence(errorMessage(err)));return{fingerprint,config:null,unreadable:terminalSafe(reason,{max:UNREADABLE_REASON_MAX})}}}function firstSentence(text){let quoted=!1;for(let i=0;i<text.length;i++){let ch=text[i];if(ch==="\\")i++;else if(ch==='"')quoted=!quoted;else if(ch==="."&&!quoted&&(i+1===text.length||/\s/.test(text[i+1])))return text.slice(0,i)}return text}function describeUnreadConfig(cwd){let read=readJsonBounded(configPath(cwd));if(read.kind==="unusable")return`it ${read.reason}`;if(read.kind!=="ok")return"it changed while init was reading it";let raw=read.value;return isPlainObject(raw)?typeof raw.skillsVersion!="string"?'it has no "skillsVersion" string':'it has neither a "capabilities" key nor a "modules" array':"it is not a JSON object"}function previousConfigLines(previous){return previous.unreadable===null?[]:[` the previous pharn.config.json could not be read (${previous.unreadable}); nothing is carried over, so manual capabilities will be dropped`]}function carryOver(previous,index,resolved){let inIndex=new Set(index.capabilities.map(capabilityKey)),frozen=new Set(index.unknown.map(capabilityKey)),selected=new Set(resolved.selected.map(capabilityKey)),manualKeys=new Set,kept=[],extra=[],gone=[],dropped=[],seen=new Set;for(let cap2 of previous?.capabilities??[]){let k=capabilityKey(cap2);if(!seen.has(k)){if(seen.add(k),frozen.has(k)){kept.push({...cap2});continue}if(cap2.source!=="manual"){selected.has(k)||dropped.push({cap:cap2,reason:cap2.source==="auto"||inIndex.has(k)?"dropped-unselected":"dropped-gone"});continue}if(!inIndex.has(k)){gone.push(cap2),dropped.push({cap:cap2,reason:"dropped-gone"});continue}manualKeys.add(k),selected.has(k)||extra.push(cap2)}}return{manualKeys,kept,extra,gone,dropped,previousStamp:previous?{skillsVersion:previous.skillsVersion,commit:previous.commit}:null,...previous?{previousLayout:configLayout(previous)}:{}}}function planInitRemovals(cwd,carry,records){let drops=carry.dropped??[];return drops.length===0?[]:planCapabilityRemovals({cwd,paths:layoutPaths(carry.previousLayout??"flat"),drops,records,command:"init"})}function resolveInitSelection(params){let{cwd,archetypes,index}=params,resolved=resolveCapabilities(archetypes,index),previous=readPreviousConfig(cwd),carry=carryOver(previous.config,index,resolved),extraKeys=new Set(carry.extra.map(capabilityKey)),selection=carry.extra.length?{selected:[...resolved.selected,...carry.extra.map(c=>({name:c.name,role:c.role,matched:"manual"}))],skipped:resolved.skipped.filter(s=>!extraKeys.has(capabilityKey(s)))}:resolved;return{previous,carry,selection}}function reinstallBaseline(cwd,carry){return carry.previousStamp===null?null:recordsBaseline(readRecords(cwd)).records}function initRecordedPaths(params){let{cwd,manifest,carry,capabilities,layout,baseline}=params,kept=carry.kept.length===0||baseline===null?{}:recordsUnderCapabilities(baseline,layoutPaths(layout),carry.kept),orphans=findOrphans({projectRoot:cwd,records:baseline,expected:manifest,capabilities:[...capabilities,...carry.kept],frozen:carry.kept}).records;return[...Object.keys(kept),...Object.keys(orphans),...manifest.keys()]}function readCarriedEntries(cwd){let read=readJsonBounded(configPath(cwd));return read.kind!=="ok"?{}:isPlainObject(read.value)?userOwnedConfigEntries(read.value):{}}function initRootMigration(repoDir,cwd,carry,records){if(carry.previousStamp===null)return null;let skillsVersion="";try{skillsVersion=readSkillsVersion(repoDir)}catch{}return planRootMigration({projectRoot:cwd,repoDir,layout:detectLayout(repoDir),installedLayout:carry.previousLayout??"flat",skillsVersion,records})}function previousChannelLines(params){let{previous,channel,explicit,source}=params;if(previous===null||explicit)return[];if(channel!=="latest"||channelOf(previous)!=="main")return[];let lines=[" previously followed: main (the pharn-oss tip) \u2014 pass --ref main to keep it"],installed=previous.skillsVersion;return source.kind==="release"&&typeof installed=="string"&&versionStatus({installed,latest:source.version}).ahead&&lines.push(` installed v${terminalSafe(installed,{max:40})} is newer than release ${source.tag} \u2014 this re-install goes back to it`),lines}function buildInitPlan(params){let{repoDir,cwd,sha,source,channel,archetypes,index,chosen}=params,origin=params.origin??{kind:"detected",evidence:[],truncated:!1},{selection,carry}=chosen,layout=detectLayout(repoDir),manifest=collectExpectedInstallPaths({repoDir,capabilities:selection.selected,layout}),prepared=prepareInstall(repoDir,cwd,selection.selected,manifest),baseline=reinstallBaseline(cwd,carry),removals=planInitRemovals(cwd,carry,baseline),scan=scanDest({repoDir,projectRoot:cwd,rels:[...manifest.keys()],sources:manifestSources(repoDir,manifest),records:baseline}),writeTargets=planWriteTargets({repoDir,projectRoot:cwd,capabilities:selection.selected,manifest,records:baseline,removals,labels:scan.labels}),{conflicts,labels,configBackedUp}=writeTargets,existing=new Set(conflicts),targets=[...new Set([...manifest.keys(),PHARN_CONFIG_FILE])].sort().map(rel=>({rel,action:existing.has(rel)?"overwrite":"create",label:labels.get(rel)??(configBackedUp&&rel===PHARN_CONFIG_FILE?"rewritten":null)})),rootMigration=initRootMigration(repoDir,cwd,carry,baseline),backups=[...new Set([...[...labels.keys()].sort(),...configBackedUp?[PHARN_CONFIG_FILE]:[],...removalBackups(removals)])],settingsPreserved=existsSync2(safeJoin(cwd,CLAUDE_SETTINGS_FILE)),upstreamModels=readUpstreamModels(repoDir);return{report:{archetypes,archetypeOrigin:origin,previousArchetypes:recordedArchetypes(chosen.previous.config?.archetypes),channelLines:previousChannelLines({previous:chosen.previous.config,channel,explicit:params.refExplicit??!1,source}),previousConfigLines:previousConfigLines(chosen.previous),channel,source,commit:sha,skillsVersion:readSkillsVersion(repoDir),layout,selection,carry:{manual:[...carry.manualKeys].sort(),extra:carry.extra,kept:[...carry.kept],gone:carry.gone},unknownCapabilities:index.unknown,targets,conflicts,configBackedUp,removals,backups,counts:{create:targets.length-existing.size,overwrite:existing.size,backup:backups.length},settingsPreserved,hookWiring:settingsPreserved?diffHookWiring(repoDir,cwd):null,freshSettings:!settingsPreserved&&upstreamSettingsCopyable(repoDir)?upstreamSettingsSummary(repoDir):null,models:upstreamModels.kind==="ok"?{outcome:"copy",reasons:[]}:upstreamModels.kind==="absent"?{outcome:"none",reasons:[]}:{outcome:"rejected",reasons:upstreamModels.reasons},absentUpstream:absentInstallSurfaces({repoDir,layout}),carriedConfigKeys:Object.keys(readCarriedEntries(cwd)),rootMigration,gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,initRecordedPaths({cwd,manifest,carry,capabilities:selection.selected,layout,baseline}))},apply:{prepared,drifted:scan.drifted,seen:scan.seen,baseline,removals,rootMigration,targets:writeTargets,fingerprint:chosen.previous.fingerprint}}}var INIT_SCHEMA_VERSION=1,MAX_REASON=300,MAX_UNKNOWN_FIELD=200,MAX_EVIDENCE=200,key=c=>`${c.role}:${c.name}`;function buildInitReport(p){return{schemaVersion:INIT_SCHEMA_VERSION,command:"init",dryRun:!0,status:"planned",channel:p.channel,source:{kind:p.source.kind,tag:p.source.kind==="release"?p.source.tag:null},commit:p.commit,skillsVersion:p.skillsVersion,layout:p.layout,archetypes:[...p.archetypes],archetypeSource:p.archetypeOrigin.kind,detectedArchetypes:p.archetypeOrigin.kind==="flag"?[...p.archetypeOrigin.detected]:null,archetypeEvidence:p.archetypeOrigin.evidence.map(e=>({archetype:e.archetype,source:e.source,value:e.source==="dependency"||e.source==="devDependency"?e.name:e.source==="path"?cap(e.path,MAX_EVIDENCE):null})),...p.archetypeOrigin.truncated?{detectionTruncated:!0}:{},capabilities:{selected:p.selection.selected.map(c=>({role:c.role,name:c.name,matched:Array.isArray(c.matched)?[...c.matched]:c.matched})),skipped:p.selection.skipped.map(c=>({role:c.role,name:c.name,reason:cap(c.reason,MAX_REASON)})),carried:{manual:[...p.carry.manual],kept:p.carry.kept.map(key),dropped:p.carry.gone.map(key)},...p.removals.length>0?{removals:p.removals.map(r=>({role:r.cap.role,name:r.cap.name,reason:r.reason,dir:r.dir,present:r.present,backups:[...r.backups]}))}:{}},unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),targets:p.targets.map(t=>({rel:t.rel,action:t.action,label:t.label})),backups:[...p.backups],counts:{create:p.counts.create,overwrite:p.counts.overwrite,backup:p.counts.backup},yesWouldProceed:p.counts.overwrite===0,settings:{preserved:p.settingsPreserved},hooks:p.hookWiring===null?null:{status:p.hookWiring.status,missing:p.hookWiring.missing,localOnly:p.hookWiring.localOnly??[],file:p.hookWiring.file??null,reason:p.hookWiring.reason??null,...p.hookWiring.replace?.length?{replace:p.hookWiring.replace}:{}},...p.freshSettings===null?{}:{settingsHooks:p.freshSettings.status==="ok"?{status:"ok",hooks:p.freshSettings.hooks.map(e=>({event:e.event,matcher:e.matcher,command:e.command,args:[...e.args]})),otherKeys:p.freshSettings.otherKeys.map(k=>cap(k,MAX_UNKNOWN_FIELD)),skipped:p.freshSettings.skipped}:{status:"unreadable",reason:cap(p.freshSettings.reason,MAX_REASON)}},...p.absentUpstream.length>0?{absentUpstream:p.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))}:{},models:{outcome:p.models.outcome,reasons:p.models.reasons.map(r=>cap(r,MAX_REASON))},config:{carriedKeys:p.carriedConfigKeys.map(k=>cap(k,MAX_UNKNOWN_FIELD))},...gitignoreKey(p.gitignore),...prettierignoreKey(p.prettierignore)}}function prettierignoreKey(plan){let report=prettierignoreReport(plan);return report===null?{}:{prettierignore:report}}function gitignoreKey(plan){let report=gitignoreReport(plan);return report===null?{}:{gitignore:report}}import{existsSync as existsSync3}from"node:fs";import{dirname,join as join2,resolve as resolve2}from"node:path";function runGitPrereq(opts={}){let cwd=process.cwd();if(!existsSync3(resolve2(cwd,".git"))){let root=findAncestorGitRoot(cwd);fail(root===null?`git not found.
4
+ Run: git init && git add -A && git commit -m 'init'
5
+ Then re-run: npx @pharn-dev/pharn init`:`${escapeUnsafe(cwd)} is inside the git repository at ${escapeUnsafe(root)}, not at its root.
6
+ Run \`pharn init\` from the repository root (${escapeUnsafe(root)}).`,opts.json??!1)}}function findAncestorGitRoot(start){let dir=resolve2(start);for(;;){let parent=dirname(dir);if(parent===dir)return null;if(dir=parent,existsSync3(join2(dir,".git")))return dir}}function fail(message,json){throw CliError.error(message,{json})}import{confirm,isCancel,log}from"@clack/prompts";function recordedSkillsVersion(cwd){let read=readJsonBounded(safeJoin(cwd,PHARN_CONFIG_FILE));if(read.kind!=="ok")return null;let parsed=read.value;if(typeof parsed!="object"||parsed===null)return null;let version=parsed.skillsVersion;return typeof version=="string"&&VERSION_RE.test(version)?version:null}function labelLine(label,n){let one=n===1;switch(label){case"modified":return`${n} of them changed since pharn wrote ${one?"it":"them"} (your edits).`;case"unrecorded":return`${n} of them ${one?"differs":"differ"} from upstream, and pharn has no record of ${one?"it":"them"}.`;case"unverifiable":return`${n} of them ${one?"differs":"differ"} from upstream \u2014 pharn has no record to tell your edits from upstream changes.`}}async function confirmWriteTargets(repoDir,cwd,selection,context={}){let{conflicts,labels,configBackedUp,removals}=context.targets??planWriteTargets({repoDir,projectRoot:cwd,capabilities:selection.selected,manifest:context.manifest??collectExpectedInstallPaths({repoDir,capabilities:selection.selected,layout:detectLayout(repoDir)}),records:context.records??null,removals:context.removals}),deletes=removalLines(removals);if(conflicts.length===0&&deletes.length===0)return"proceed";let deleteBackups=removals.filter(r=>r.present).reduce((n,r)=>n+r.backups.length,0),deleteBlock=deletes.length>0?`${conflicts.length>0?`
7
+ `:""}These capability directories are no longer selected and will be DELETED (pharn runs every capability directory on disk):
8
+ ${deletes.join(`
9
+ `)}${deleteBackups>0?`
10
+ ${deleteBackups} file(s) in them pharn did not write will be copied to ${BACKUP_DIR}/ first.`:""}`:"";if(conflicts.length===0){log.warn(`PHARN installs into your existing project. ${deleteBlock}`);let result2=await confirm({message:"Continue and delete them?",initialValue:!1});return isCancel(result2)?"cancel":result2===!0?"proceed":"decline"}let list=targetLines({conflicts,labels,configBackedUp},MAX_LISTED).join(`
11
+ `),counts=DRIFT_LABEL_ORDER.map(label=>[label,[...labels.values()].filter(l=>l===label).length]).filter(([,n])=>n>0),editsLine=labels.size>0?`
12
+ ${counts.map(([label,n])=>labelLine(label,n)).join(`
13
+ `)}
14
+ ${labels.size===1?"It":`All ${labels.size}`} will be copied to ${BACKUP_DIR}/ before being overwritten.`:"",configLine=configBackedUp?`
15
+ ${PHARN_CONFIG_FILE} will be rewritten (models reset to its default); it will be copied to ${BACKUP_DIR}/ first.`:"",version=conflicts.includes(PHARN_CONFIG_FILE)?recordedSkillsVersion(cwd):null,intro2=version===null?"PHARN installs into your existing project.":`PHARN installs into your existing project (currently at skills v${version}).`;log.warn(`${intro2} These paths already exist and may be overwritten:
16
+ ${list}${editsLine}${configLine}${deleteBlock?`
17
+ ${deleteBlock}`:""}`);let result=await confirm({message:deletes.length>0?"Continue, overwrite and delete?":"Continue and overwrite?",initialValue:!1});return isCancel(result)?"cancel":result===!0?"proceed":"decline"}import{isCancel as isCancel2,note,select}from"@clack/prompts";var MAX_EVIDENCE_CHARS=120;function describeEvidence(evidence){switch(evidence.source){case"dependency":return`${evidence.name} (package.json)`;case"devDependency":return`${evidence.name} (package.json devDependencies)`;case"path":return terminalSafe(evidence.path,{max:MAX_EVIDENCE_CHARS});case"none":return"no framework signal found"}}var sameSet=(a,b)=>a.length===b.length&&a.every(x=>b.includes(x)),TRUNCATED_LINE=` detection stopped early: it examines at most ${WALK_LIMITS.maxEntries.toLocaleString("en-US")} entries, ${WALK_LIMITS.maxDepth} directories deep, so these archetypes may be incomplete \u2014 pass --archetype <list> if they are wrong`;function archetypeOriginLines(archetypes,origin,previous=null){let lines=[];if(origin.kind==="flag")lines.push(row("Archetypes (--archetype)",archetypes.join(", ")),` detection found ${origin.detected.join(", ")} (not used)`);else{lines.push(row("Detected archetypes",archetypes.join(", ")));for(let e of origin.evidence)lines.push(` ${e.archetype.padEnd(8)}\u2190 ${describeEvidence(e)}`);origin.truncated&&lines.push(TRUNCATED_LINE)}return previous!==null&&!sameSet(previous,archetypes)&&lines.push(` previously recorded: ${previous.join(", ")} \u2014 pass --archetype ${previous.join(",")} to keep them`),lines}function describeMatched(matched){return matched==="universal"?"universal":matched==="manual"?"added by hand":matched.join(", ")}function archetypeSummaryLines(archetypes,selection,origin={kind:"detected",evidence:[],truncated:!1},previous=null,rerunLines=[]){let lines=["\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"," PHARN Install Summary (archetype)","\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","",...archetypeOriginLines(archetypes,origin,previous),...rerunLines,"",` CAPABILITIES SELECTED (${selection.selected.length})`,...selection.selected.length>0?selection.selected.map(c=>row(`${c.name} (${c.role})`,describeMatched(c.matched))):[" (none)"]];return selection.skipped.length>0&&lines.push("",` CAPABILITIES SKIPPED (${selection.skipped.length})`,...selection.skipped.map(c=>row(`${c.name} (${c.role})`,c.reason))),lines.push(""," Installs PHARN product commands + write-gating hooks into .claude/"," (an existing .claude/settings.json is preserved, not overwritten).","","\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"),lines}async function runArchetypeSummary(archetypes,selection,origin={kind:"detected",evidence:[],truncated:!1},previous=null,rerunLines=[]){note(archetypeSummaryLines(archetypes,selection,origin,previous,rerunLines).join(`
18
+ `));let action=await select({message:"Ready to install?",initialValue:"install",options:[{value:"install",label:"Yes, install"},{value:"cancel",label:"Cancel"}]});return isCancel2(action)?"cancel":action==="install"?"install":"cancel"}import{log as log2,note as note2,outro,spinner}from"@clack/prompts";async function runInstallArchetype(repoDir,cwd,archetypes,selection,commit,carry,plan){let startedAt=Date.now(),{prepared,baseline,removals,rootMigration:migration}=plan;assertConfigFingerprintUnchanged(cwd,plan.fingerprint,"init");let deletes=removals.filter(r=>r.present),overwriteBackups=[...plan.drifted,...replacedConfigBackup(cwd)],toBackUp=[...new Set([...overwriteBackups,...removalBackupsNow({cwd,removals,records:baseline,command:"init"})])];if(toBackUp.length>0){let backupDir=createBackup(cwd,toBackUp),action=backupAction(overwriteBackups.length>0,deletes.length>0);printBackupNotice({dir:backupDir,saved:toBackUp.length,action,gitignored:backupDirIgnored(cwd,planGitignore(cwd))})}if(deletes.length>0){let paths=layoutPaths(carry.previousLayout??"flat");for(let removal of deletes)deleteCapabilityDir(cwd,paths,removal.cap);log2.info(`Deleted ${deletes.length} capability director${deletes.length===1?"y":"ies"} no longer installed: ${deletes.map(r=>`${r.dir}/`).join(", ")}.`)}let s=spinner();s.start("Installing capabilities");let capabilities,settingsPreserved,settingsWritten,skillsVersion,layout,docsWritten;try{let result=installPrepared(repoDir,cwd,selection,prepared,plan.seen);capabilities=result.capabilities,settingsPreserved=result.settingsPreserved,settingsWritten=result.settingsWritten,layout=result.layout,docsWritten=result.docs,skillsVersion=readSkillsVersion(repoDir)}catch(err){throw s.stop("Failed to install capabilities"),err}s.stop("Capabilities installed");let docResult=migration===null?{deleted:[],kept:[]}:deleteRootDocs(cwd,repoDir,migration.docs,baseline),retired=new Set(docResult.deleted);if(settingsPreserved){log2.info(`Existing ${CLAUDE_SETTINGS_FILE} preserved \u2014 pharn never overwrites it.`);let hookLines=preservedSettingsHookLines(diffHookWiring(repoDir,cwd));hookLines&&note2(hookLines.join(`
19
+ `),"HOOKS")}else settingsWritten&&note2(freshSettingsHookLines(upstreamSettingsSummary(repoDir)).join(`
20
+ `),"HOOKS");let upstreamModels=readUpstreamModels(repoDir);upstreamModels.kind==="invalid"&&log2.warn(["pharn-oss's models block was not written; this pharn rejects it:",...upstreamModels.reasons.map(reason=>` ${terminalSafe(reason,{max:300})}`),"If pharn-oss changed its models format, upgrade pharn","(npm i -g @pharn-dev/pharn@latest) and run `pharn update`."].join(`
21
+ `));let models=upstreamModels.kind==="ok"?upstreamModels.block:void 0,absent=absentInstallSurfaces({repoDir,layout}),absentLines=absentSurfaceLines(absent);absentLines&&log2.warn(absentLines.join(`
22
+ `));let agentsWritten=[...prepared.manifest.keys()].some(rel=>rel.startsWith(`${CLAUDE_AGENTS_DIR}/`)),claudeWritten=[...["commands","hooks"].filter(surface=>!absent.some(a=>a.surface===surface)),...agentsWritten?["agents"]:[]],frozenCapabilities=[...new Set(carry.kept.map(c=>`${c.role}:${c.name}`))].sort(),config={pharnVersion:PHARN_VERSION,skillsVersion,repo:REPO_URL.replace(/^github\.com\//,""),commit,...carry.ref==="latest"?{ref:"latest"}:{},modules:[],installedAt:new Date().toISOString(),models,archetypes,capabilities:[...capabilities.map(c=>({...c,source:carry.manualKeys.has(`${c.role}:${c.name}`)?"manual":"auto"})),...carry.kept.map(c=>({...c}))],layout,...frozenCapabilities.length>0?{frozenCapabilities}:{}},files={...keptRecords(baseline,carry,layout),...Object.fromEntries(Object.entries(findOrphans({projectRoot:cwd,records:baseline,expected:prepared.manifest,capabilities:[...capabilities,...carry.kept],frozen:carry.kept}).records).filter(([rel])=>!retired.has(rel))),...settingsWritten?buildRecords(cwd,[CLAUDE_SETTINGS_FILE]):carriedSettingsRecord(cwd,baseline),...buildRecords(cwd,prepared.manifest.keys()),...models!==void 0?{[MODELS_RECORD_KEY]:modelsRecordHash(models)}:{}};await writeRecords(cwd,{skillsVersion,commit,files}),await writePharnConfig(cwd,{...config,...readCarriedEntries(cwd)});let gitignore=await applyGitignore(cwd),gitignoreReport2=gitignoreLines(gitignore);gitignoreReport2?.warn&&log2.warn(gitignoreReport2.text);let prettierignore=await applyPrettierignore(cwd,Object.keys(files)),prettierignoreReport2=prettierignoreLines(prettierignore);if(prettierignoreReport2?.warn&&log2.warn(prettierignoreReport2.text),migration!==null){let lines=rootMigrationNoteLines(migration,docResult);lines&&note2(lines.join(`
23
+ `),"ROOT MIGRATION")}let elapsed=((Date.now()-startedAt)/1e3).toFixed(1),check=color_default.green("\u2714"),grillers=capabilities.filter(c=>c.role==="griller").length,lenses=capabilities.filter(c=>c.role==="lens").length,modelsCheck=checkModelsBlock(models),modelsSection=modelsCheck.kind==="valid"?["",color_default.bold("Declared model per stage")+` ${color_default.dim("(pharn.config.json \u2192 models, from pharn-oss)")}`,...resolvedStageLines(modelsCheck.stages).map(line=>` ${line}`),...modelsLabelLines(layoutPaths(layout).floor).map(line=>` ${color_default.dim(line)}`)]:[],docsLine=docsWritten.length?`${check} ${docsWritten.length} trusted doc${docsWritten.length===1?"":"s"} written \u2192 ${color_default.dim(docsWritten.join(", "))}`:`${color_default.yellow("!")} no trusted docs written ${color_default.dim("(the fetched repo shipped none at their expected paths)")}`;outro([`${check} ${capabilities.length} capabilit${capabilities.length===1?"y":"ies"} installed \u2192 ${color_default.dim(`(${grillers} griller${grillers===1?"":"s"}, ${lenses} lens${lenses===1?"":"es"})`)}`,claudeWritten.length?`${check} PHARN ${claudeWritten.join(" + ")} written \u2192 ${color_default.dim(".claude/")}`:`${color_default.yellow("!")} no PHARN commands or hooks written ${color_default.dim("(the fetched repo shipped none)")}`,docsLine,`${check} pharn.config.json written ${color_default.dim(`(skills v${skillsVersion}, archetypes: ${archetypes.join(", ")})`)}`,...gitignore.action==="create"||gitignore.action==="append"?[`${check} .gitignore ${gitignore.action==="create"?"created":"updated"} \u2192 ${color_default.dim(gitignore.entries.join(", "))}`]:[],...prettierignore.action==="create"||prettierignore.action==="append"?[`${check} .prettierignore ${prettierignore.action==="create"?"created":"updated"} \u2192 ${color_default.dim(`${prettierignore.entries.length} path${prettierignore.entries.length===1?"":"s"} pharn installs or rewrites`)}`]:[],`${color_default.dim(`Done in ${elapsed}s`)}`,...modelsSection,"",color_default.bold("Next steps"),` ${color_default.cyan("1.")} ${color_default.bold("claude")} ${color_default.dim("open Claude Code")}`,` ${color_default.cyan("2.")} ${color_default.bold(FIRST_FEATURE_COMMAND)} ${color_default.dim("capture your first feature's intent")}`].join(`
24
+ `))}function keptRecords(baseline,carry,layout){return carry.kept.length===0||baseline===null?{}:recordsUnderCapabilities(baseline,layoutPaths(layout),carry.kept)}async function runInit(opts={}){let yes=opts.yes??!1,json=opts.json??!1,dryRun=(opts.dryRun??!1)||json;if(runNodePrereq("init",{json}),runGitPrereq({json}),!dryRun&&!yes&&!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("pharn init is interactive \u2014 run it in an interactive terminal. To install without prompts, pass --yes: it installs only into a project where none of its files exists yet, and never overwrites. To see what init would do, pass --dry-run.");if(yes&&!dryRun){let refusal=existingConfigRefusal(process.cwd());if(refusal!==null)throw CliError.refusal(refusal)}json||(showBanner(),intro(dryRun?"pharn init --dry-run":"init wizard"));let run=()=>runInitArchetype({channel:opts.ref??DEFAULT_INIT_REF,refExplicit:opts.ref!==void 0,override:opts.archetypes,yes,dryRun,json});if(dryRun){await run();return}try{await withProjectLock(process.cwd(),"init",run)}catch(err){throw err instanceof ProjectLockedError?CliError.refusal(err.message):err}}function silentSpinner(){return{start:()=>{},stop:()=>{}}}async function runInitArchetype(mode){let{channel,refExplicit,override,yes,dryRun,json}=mode,warn=json?message=>logErrorPlain(message):message=>log3.warn(message),cwd=process.cwd(),detection=detectArchetypesFromProject(cwd),archetypes=override??detection.archetypes,origin=override?{kind:"flag",detected:detection.archetypes,evidence:detection.evidence,truncated:detection.truncated}:{kind:"detected",evidence:detection.evidence,truncated:detection.truncated},proxyNotice=detectProxyNotice(process.env);proxyNotice&&warn(proxyNoticeMessage(proxyNotice));let s=json?silentSpinner():spinner2();s.start(`Fetching PHARN from ${REPO_URL}`);let repo;try{repo=await fetchRepo(await resolveSource(channel))}catch(err){throw s.stop("Failed to fetch PHARN"),CliError.failure(err,{json,message:err instanceof ReleaseResolveError||err instanceof UpstreamManifestError?err.message:`Could not reach ${REPO_URL}: ${errorMessage(err)}`})}if(s.stop(`PHARN fetched from ${sourceLabel(repo.source)}`),dryRun){await runInitDryRun(repo,cwd,archetypes,origin,{channel,refExplicit,json});return}try{let gate=minCliGate(repo.dir,PHARN_VERSION);if(gate.warning&&log3.warn(gate.warning),gate.refusal)throw CliError.refusal(gate.refusal);{let index=parseCapabilityIndex(repo.dir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&log3.warn(unknownWarning);let chosen=resolveInitSelection({cwd,archetypes,index}),{previous,carry,selection}=chosen;warnIfOlderCli(previous.config),reportCarry(carry);let recorded=recordedArchetypes(previous.config?.archetypes),rerunLines=[...previousConfigLines(previous),...previousChannelLines({previous:previous.config,channel,explicit:refExplicit,source:repo.source})],action;if(yes?(note3(archetypeSummaryLines(archetypes,selection,origin,recorded,rerunLines).join(`
25
+ `)),action="install"):action=await runArchetypeSummary(archetypes,selection,origin,recorded,rerunLines),action!=="install")throw CliError.cancel();let planned=buildInitPlan({repoDir:repo.dir,cwd,sha:repo.sha,source:repo.source,channel,archetypes,origin,index,chosen,refExplicit}),targets=planned.apply.targets;if(yes)refuseExistingTargets(targets);else{let migration=planned.apply.rootMigration,migrationLines=migration===null?null:rootMigrationNoteLines(migration,null);if(migrationLines&&note3(migrationLines.join(`
26
+ `),"ROOT MIGRATION"),await confirmWriteTargets(repo.dir,cwd,selection,{targets})!=="proceed")throw CliError.cancel()}await runInstallArchetype(repo.dir,cwd,archetypes,selection,repo.sha,channel==="latest"?{...carry,ref:"latest"}:carry,planned.apply)}}catch(err){throw err instanceof OverwriteRefusedError||err instanceof CapabilityRemovalError?CliError.refusal(err.message):CliError.failure(err)}finally{repo.cleanup()}}function reportCarry(carry){carry.extra.length&&log3.info(`Keeping ${carry.extra.length} capabilit${carry.extra.length===1?"y":"ies"} you added by hand: ${carry.extra.map(capabilityKey).join(", ")}.`),carry.kept.length&&log3.info(`Keeping ${carry.kept.length} capabilit${carry.kept.length===1?"y":"ies"} as installed \u2014 upstream still ships ${carry.kept.length===1?"it":"them"} but this pharn cannot read ${carry.kept.length===1?"it":"them"} (see above): ${carry.kept.map(capabilityKey).join(", ")}. Files and config entries are left as they are; \`pharn update\` re-checks them.`),carry.gone.length&&log3.warn(`Not keeping ${carry.gone.length} capabilit${carry.gone.length===1?"y":"ies"} you added by hand that upstream no longer ships: ${carry.gone.map(capabilityKey).join(", ")}. ${carry.gone.length===1?"It is":"They are"} dropped from pharn.config.json, and ${carry.gone.length===1?"its directory is":"their directories are"} deleted (files pharn did not write are backed up first).`);let goneKeys=new Set(carry.gone.map(capabilityKey)),unselected=carry.dropped.filter(d=>!goneKeys.has(capabilityKey(d.cap)));unselected.length&&log3.warn(`Not keeping ${unselected.length} capabilit${unselected.length===1?"y":"ies"} your archetypes no longer select${unselected.some(d=>d.reason==="dropped-gone")?" (or upstream no longer ships)":""}: ${unselected.map(d=>capabilityKey(d.cap)).join(", ")}. ${unselected.length===1?"It is":"They are"} dropped from pharn.config.json, and ${unselected.length===1?"its directory is":"their directories are"} deleted (files pharn did not write are backed up first).`)}async function runInitDryRun(repo,cwd,archetypes,origin,mode){let{channel,refExplicit,json}=mode,warn=json?message=>logErrorPlain(message):message=>log3.warn(message),plan,carry;try{let gate=minCliGate(repo.dir,PHARN_VERSION);if(gate.warning&&warn(gate.warning),gate.refusal)throw CliError.refusal(gate.refusal,{json});let index=parseCapabilityIndex(repo.dir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&warn(unknownWarning);let chosen=resolveInitSelection({cwd,archetypes,index});warnIfOlderCli(chosen.previous.config,{json}),carry=chosen.carry,plan=buildInitPlan({repoDir:repo.dir,cwd,sha:repo.sha,source:repo.source,channel,archetypes,origin,index,chosen,refExplicit}).report}catch(err){throw err instanceof CapabilityRemovalError?CliError.refusal(err.message,{json}):CliError.failure(err,{json})}finally{repo.cleanup()}if(json){console.log(serializeJsonReport(buildInitReport(plan)));return}reportCarry(carry),reportInitDryRun(plan)}function reportInitDryRun(r){note3(archetypeSummaryLines(r.archetypes,r.selection,r.archetypeOrigin,r.previousArchetypes,[...r.previousConfigLines,...r.channelLines]).join(`
27
+ `));let labels=new Map(r.targets.flatMap(t=>t.label===null||t.label==="rewritten"?[]:[[t.rel,t.label]])),lines=[];r.counts.overwrite>0?(lines.push(` WOULD OVERWRITE ${r.counts.overwrite} existing file(s)`),lines.push(...targetLines({conflicts:r.conflicts,labels,configBackedUp:r.configBackedUp}))):lines.push(" Nothing in your project would be overwritten."),lines.push("",` WOULD CREATE ${r.counts.create} file(s)`);let deletes=removalLines(r.removals);deletes.length>0&&lines.push("",` WOULD DELETE ${deletes.length} capability director${deletes.length===1?"y":"ies"} dropped from your config`,...deletes),r.counts.backup>0&&lines.push("",` WOULD BACK UP ${r.counts.backup} file(s) to ${BACKUP_DIR}/<timestamp>/ first \u2014 the marked ones above${deletes.length>0?" and the deleted directories\u2019 files pharn did not write":""}`),lines.push("",` Would write pharn.config.json (skills v${r.skillsVersion}, ${r.layout} layout, archetypes: ${r.archetypes.join(", ")})`),r.configBackedUp&&lines.push(` The existing pharn.config.json would be rewritten (models reset to its default); it would be copied to ${BACKUP_DIR}/ first.`),r.carriedConfigKeys.length>0&&lines.push(` Would keep your own pharn.config.json keys: ${r.carriedConfigKeys.map(k=>terminalSafe(k,{max:200})).join(", ")}`),r.settingsPreserved?lines.push(` Would preserve the existing ${CLAUDE_SETTINGS_FILE} \u2014 pharn never overwrites it.`):r.freshSettings!==null&&lines.push(` Would write ${CLAUDE_SETTINGS_FILE} from upstream; see HOOKS.`);let gitignore=gitignoreLines(r.gitignore,{preview:!0});gitignore!==null&&!gitignore.warn&&lines.push(` ${gitignore.text}`);let prettierignore=prettierignoreLines(r.prettierignore,{preview:!0});prettierignore!==null&&!prettierignore.warn&&lines.push(` ${prettierignore.text}`),lines.push("",r.counts.overwrite===0?" `pharn init --yes` would install (nothing would be overwritten).":` \`pharn init --yes\` would refuse: ${r.counts.overwrite} existing file(s) would be overwritten.`),note3(lines.join(`
28
+ `),"PLAN"),gitignore?.warn&&log3.warn(gitignore.text),prettierignore?.warn&&log3.warn(prettierignore.text);let migrationLines=r.rootMigration===null?null:rootMigrationNoteLines(r.rootMigration,null);migrationLines&&note3(migrationLines.join(`
29
+ `),"ROOT MIGRATION");let hookLines=r.hookWiring!==null?preservedSettingsHookLines(r.hookWiring):r.freshSettings!==null?freshSettingsHookLines(r.freshSettings):null;hookLines&&note3(hookLines.join(`
30
+ `),"HOOKS");let absentLines=absentSurfaceLines(r.absentUpstream,{preview:!0});absentLines&&log3.warn(absentLines.join(`
31
+ `)),r.models.outcome==="rejected"&&log3.warn(["pharn-oss's models block would not be written; this pharn rejects it:",...r.models.reasons.map(reason=>` ${terminalSafe(reason,{max:300})}`)].join(`
32
+ `)),outro2(`Dry run \u2014 would create ${r.counts.create} \xB7 overwrite ${r.counts.overwrite}${deletes.length>0?` \xB7 delete ${deletes.length} director${deletes.length===1?"y":"ies"}`:""} \xB7 back up ${r.counts.backup}. Nothing was changed. Run \`pharn init\` to apply.`)}export{runInit};
@@ -0,0 +1,2 @@
1
+ import{renderCapabilityLines}from"./chunk-BCURDSJC.js";import{color_default,loadArchetypeConfig}from"./chunk-LF4PFADC.js";import"./chunk-L3QGAX2K.js";import"./chunk-A77BLCF4.js";import{intro,note,outro}from"@clack/prompts";async function runList(opts={}){let json=opts.json??!1,cwd=process.cwd();json||intro("pharn list");let config=loadArchetypeConfig(cwd,{json}),inventory=buildArchetypeInventory(config);if(json){console.log(JSON.stringify(inventory,null,2));return}renderArchetypeHuman(inventory)}function buildArchetypeInventory(config){return{mode:"archetype",skillsVersion:config.skillsVersion,archetypes:config.archetypes??[],capabilities:(config.capabilities??[]).map(c=>({name:c.name,role:c.role,...c.source!==void 0?{source:c.source}:{}}))}}function renderArchetypeHuman(inv){let lines=renderCapabilityLines(inv);note(lines.join(`
2
+ `),"INSTALLED (archetype)"),outro(color_default.dim("Read-only \u2014 nothing changed."))}export{runList};
@@ -0,0 +1 @@
1
+ import{parseCapabilityArg}from"./chunk-QGQRN6AC.js";import{capabilityDir,capabilityRelDir,deleteCapabilityDir,linkedComponent,removalBackupSet}from"./chunk-6LOUFC5E.js";import{ProjectLockedError,backupDirIgnored,buildRemoveSelection,createBackup,interactiveAllowed,printBackupNotice,withProjectLock}from"./chunk-ZQWLF3HH.js";import"./chunk-BCURDSJC.js";import{configLayout,layoutPaths,readRecords,recordsBaseline,warnIfOlderCli,writeRecords}from"./chunk-FUQURK5N.js";import"./chunk-SQLIXTIY.js";import"./chunk-C5RBIXPQ.js";import{assertConfigFingerprintUnchanged,color_default,configFingerprint,loadArchetypeConfig,writePharnConfig}from"./chunk-LF4PFADC.js";import"./chunk-L3QGAX2K.js";import{CliError,errorMessage}from"./chunk-A77BLCF4.js";import{confirm,groupMultiselect,intro,isCancel,log,outro}from"@clack/prompts";async function runRemove(arg){intro("pharn remove");let cwd=process.cwd();try{await withProjectLock(cwd,"remove",async()=>{let fingerprint=configFingerprint(cwd),config=loadArchetypeConfig(cwd);warnIfOlderCli(config),await removeCapability(cwd,config,arg,fingerprint)})}catch(err){throw err instanceof ProjectLockedError||err instanceof RemoveBackupError||err instanceof SymlinkedTargetError?CliError.error(err.message):err}}var RemoveBackupError=class extends Error{constructor(message){super(message),this.name="RemoveBackupError"}},SymlinkedTargetError=class extends Error{constructor(message){super(message),this.name="SymlinkedTargetError"}};async function removeCapability(cwd,config,arg,fingerprint){let installed=config.capabilities??[];if(arg===void 0){await runRemovePicker(cwd,config,installed,fingerprint);return}await removeNamed(cwd,config,installed,arg,fingerprint)}function backupBeforeDelete(cwd,paths,targets,records){for(let target of targets)capabilityDir(cwd,paths,target);let label=targets.map(t=>`${t.name} (${t.role})`).join(", ");try{let rels=removalBackupSet(cwd,targets.map(t=>capabilityRelDir(paths,t)),records);if(rels.length===0)return;let backupDir=createBackup(cwd,rels);printBackupNotice({dir:backupDir,saved:rels.length,action:"removing",gitignored:backupDirIgnored(cwd)})}catch(err){throw new RemoveBackupError(`Could not back up the files in ${label} before removing: ${errorMessage(err).replace(/\.$/,"")}. Nothing was removed.`)}}function readRecordsBaseline(cwd){return recordsBaseline(readRecords(cwd)).records}function refuseSymlinkedTargets(cwd,paths,targets){for(let target of targets){let linked=linkedComponent(cwd,paths,target);if(linked!==null)throw new SymlinkedTargetError(`Refusing to remove ${target.name} (${target.role}): ${linked} is a symbolic link, so deleting through it would delete files OUTSIDE the project. Nothing was removed. Delete the directory yourself if that is what you want.`)}}async function pruneCapabilityRecords(cwd,config,paths,targets,records){if(records===null)return;let prefixes=targets.map(t=>`${capabilityRelDir(paths,t)}/`),kept={},dropped=0;for(let[key,hash]of Object.entries(records))prefixes.some(prefix=>key.startsWith(prefix))?dropped++:kept[key]=hash;dropped!==0&&await writeRecords(cwd,{skillsVersion:config.skillsVersion,commit:config.commit,files:kept})}function warnIfAutoSelected(targets){let auto=targets.filter(c=>c.source==="auto");if(auto.length===0)return;let names=auto.map(c=>`${c.name} (${c.role})`).join(", "),one=auto.length===1,pronoun=one?"it":"them";log.warn(`${names} ${one?"is":"are"} selected automatically for your archetypes, so ${one?"it comes":"they come"} back: the next \`pharn update\` reinstalls ${pronoun} and names ${pronoun} in its report.`)}async function removeNamed(cwd,config,installed,address,fingerprint){let parsed=parseCapabilityArg(address);if(parsed.error)throw CliError.error(parsed.error);let matches=installed.filter(c=>c.name===parsed.name&&(parsed.role===void 0||c.role===parsed.role));if(matches.length===0){let valid=installed.map(c=>`${c.role}:${c.name}`).sort(),hint=valid.length?` Installed: ${valid.join(", ")}.`:" No capabilities are installed.";throw CliError.error(`"${address}" is not an installed capability.${hint} Nothing was removed.`)}if(matches.length>1)throw CliError.error(`"${parsed.name}" is ambiguous \u2014 use ${matches.map(m=>`${m.role}:${m.name}`).join(" or ")}.`);let target=matches[0],paths=layoutPaths(configLayout(config));refuseSymlinkedTargets(cwd,paths,[target]),assertConfigFingerprintUnchanged(cwd,fingerprint,"remove");let records=readRecordsBaseline(cwd);backupBeforeDelete(cwd,paths,[target],records);let existed=deleteCapabilityDir(cwd,paths,target);await pruneCapabilityRecords(cwd,config,paths,[target],records),await writePharnConfig(cwd,{...config,capabilities:installed.filter(c=>!(c.name===target.name&&c.role===target.role))});let note=existed?"":color_default.dim(" (its files were already gone)");warnIfAutoSelected([target]),outro(`${color_default.green("\u2714")} Removed ${target.name} (${target.role})${note}`)}async function runRemovePicker(cwd,config,installed,fingerprint){if(installed.length===0){outro("No capabilities are installed.");return}if(!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("Specify a capability to remove (e.g. `pharn remove a11y`), or run `pharn remove` in an interactive terminal to pick from a list.");let{groups}=buildRemoveSelection(installed),picked=await groupMultiselect({message:"Select capabilities to remove",options:groups,required:!1,selectableGroups:!1});if(isCancel(picked))throw CliError.cancel();let values=picked;if(values.length===0){outro("Nothing selected. No capabilities were removed.");return}let targets=[];for(let value of values){let parsed=parseCapabilityArg(value),target=installed.find(c=>c.name===parsed.name&&c.role===parsed.role);target&&targets.push(target)}let paths=layoutPaths(configLayout(config));refuseSymlinkedTargets(cwd,paths,targets);let ok=await confirm({message:`Remove ${targets.length} ${plural(targets.length)}: ${targets.map(t=>`${t.name} (${t.role})`).join(", ")}?`,initialValue:!1});if(isCancel(ok)||ok!==!0)throw CliError.cancel();refuseSymlinkedTargets(cwd,paths,targets),assertConfigFingerprintUnchanged(cwd,fingerprint,"remove");let records=readRecordsBaseline(cwd);backupBeforeDelete(cwd,paths,targets,records);for(let target of targets)deleteCapabilityDir(cwd,paths,target);await pruneCapabilityRecords(cwd,config,paths,targets,records);let removed=new Set(targets.map(t=>`${t.role}:${t.name}`));await writePharnConfig(cwd,{...config,capabilities:installed.filter(c=>!removed.has(`${c.role}:${c.name}`))}),warnIfAutoSelected(targets),outro(`${color_default.green("\u2714")} Removed ${targets.length} ${plural(targets.length)}.`)}function plural(n){return n===1?"capability":"capabilities"}export{runRemove};
@@ -0,0 +1 @@
1
+ import{PHARN_DEBUG_HINT,logError,logErrorPlain,reportCliError,reportFatal,reportFatalPlain}from"./chunk-C5RBIXPQ.js";import{errorMessage}from"./chunk-A77BLCF4.js";export{PHARN_DEBUG_HINT,errorMessage,logError,logErrorPlain,reportCliError,reportFatal,reportFatalPlain};
@@ -0,0 +1,9 @@
1
+ import{NODE_FLOOR,cap,checkModelsBlock,modelsCheckerCommand,modelsLabelLines,nodeFloorLines,nodeFloorStatus,planPrettierignore,prettierignoreLines,prettierignoreReport,resolveStageRows,resolvedStageLines,serializeJsonReport}from"./chunk-B4EM6WAR.js";import{diffHookWiring,findOrphans,hookWiringFails,hookWiringLines,orphanNoteLines}from"./chunk-KKY6HERY.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-62AJFPPH.js";import{readDiskState}from"./chunk-KZCUUHJT.js";import{channelOf,resolveLatestReleaseVersion,resolveSource,sourceDescription,sourceLabel}from"./chunk-LVAJFL6J.js";import{absentInstallSurfaces,collectExpectedInstallPaths,configLayout,contentHash,detectLayout,fetchRemoteSkillsVersion,flatDeprecationLines,layoutPaths,readRecords,readSkillsVersion,recordsBaseline,warnIfOlderCli}from"./chunk-FUQURK5N.js";import{REPO}from"./chunk-SQLIXTIY.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{color_default,loadArchetypeConfig,row}from"./chunk-LF4PFADC.js";import"./chunk-L3QGAX2K.js";import{CliError,terminalSafe}from"./chunk-A77BLCF4.js";import{intro,log,note,outro,spinner}from"@clack/prompts";var STATUS_SCHEMA_VERSION=1,MAX_RED_DETAIL=300,MAX_UNKNOWN_FIELD=200,MAX_RUNNING_NODE=40;function layoutMismatch(recorded,upstream){return upstream!==null&&recorded!==upstream}function strictFails(input){let{outdated,diff,hooks,absentUpstream}=input;return outdated||input.layoutMismatch===!0||absentUpstream!==void 0&&absentUpstream.length>0||diff!==void 0&&(diff.modified.length>0||diff.missing.length>0||diff.unreadable.length>0)||hooks!==void 0&&hookWiringFails(hooks)}function modelsReport(models){if(models===void 0)return null;let check=checkModelsBlock(models);return check.kind==="invalid"?{conversionNeeded:!1,verdict:"invalid",stages:null,reds:check.reds.map(r=>({kind:r.kind,detail:cap(r.detail,MAX_RED_DETAIL)}))}:check.kind==="no-stages"?{conversionNeeded:!1,verdict:"no-stages",stages:null,reds:null}:{conversionNeeded:!1,verdict:"valid",stages:resolveStageRows(check.stages),reds:null}}function buildStatusReport(input){let{node,config,drift}=input,recorded=configLayout(config),upstream=drift===null?null:drift.upstreamLayout,mismatch=layoutMismatch(recorded,upstream),files=drift===null||drift.diff===null||mismatch?null:drift,{ahead,outdated}=versionStatus({installed:config.skillsVersion,latest:input.latest});return{schemaVersion:STATUS_SCHEMA_VERSION,node:{floor:NODE_FLOOR,running:node.kind==="unparseable"?node.raw===void 0?null:cap(node.raw,MAX_RUNNING_NODE):cap(node.current,MAX_RUNNING_NODE),status:node.kind},version:{installed:config.skillsVersion,latest:input.latest,channel:input.channel,source:{kind:input.source.kind,tag:input.source.kind==="release"?input.source.tag:null},ahead,outdated},archetypes:config.archetypes??[],capabilities:{count:(config.capabilities??[]).length},layout:{recorded,upstream},drift:files===null?null:{modified:files.diff.modified,missing:files.diff.missing,unreadable:files.diff.unreadable,okCount:files.diff.okCount,absentUpstream:files.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))},hooks:drift===null?null:{status:drift.hooks.status,missing:drift.hooks.missing,localOnly:drift.hooks.localOnly??[],file:drift.hooks.file??null,reason:drift.hooks.reason??null,...drift.hooks.replace?.length?{replace:drift.hooks.replace}:{}},models:modelsReport(config.models),unknownCapabilities:drift===null?null:drift.unknown.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),orphans:drift===null||drift.orphans===null?null:drift.orphans.map(o=>({path:o.path,state:o.state,...o.reason!==void 0?{reason:cap(o.reason,MAX_RED_DETAIL)}:{}})),prettierignore:input.prettierignore===null?null:prettierignoreReport(input.prettierignore),strict:{enabled:input.strict,failed:input.strict&&strictFails({outdated,diff:files?.diff,hooks:drift?.hooks,absentUpstream:files?.absentUpstream,layoutMismatch:mismatch})}}}function serializeStatusReport(report){return serializeJsonReport(report)}function diffInstalledCapabilities(params){let{repoDir,projectRoot,capabilities,layout}=params,expected=collectExpectedInstallPaths({repoDir,capabilities,layout});return compareExpected(expected,projectRoot)}function compareExpected(expected,baseDir){let modified=[],missing=[],unreadable=[],okCount=0;for(let[rel,repoPath]of expected){let state=readDiskState(baseDir,rel);state.kind==="absent"?missing.push(rel):state.kind==="unreadable"?unreadable.push({rel,reason:state.reason}):state.hash===contentHash(repoPath)?okCount+=1:modified.push(rel)}return modified.sort(),missing.sort(),unreadable.sort((a,b)=>+(a.rel>b.rel)-+(a.rel<b.rel)),{modified,missing,unreadable,okCount}}async function runStatus(opts={}){let strict=opts.strict??!1,drift=opts.drift??!0,json=opts.json??!1;json||intro("pharn status");let cwd=process.cwd(),config=loadArchetypeConfig(cwd,{json});warnIfOlderCli(config,{json});let node=nodeFloorStatus(process.versions.node);json||note(nodeFloorLines(node).join(`
2
+ `),"NODE");let proxyNotice=detectProxyNotice(process.env);if(proxyNotice){let message=proxyNoticeMessage(proxyNotice);json?logErrorPlain(message):log.warn(message)}let channel=channelOf(config),s=json?null:spinner(),input;if(drift){s?.start(`Comparing against ${REPO}`);let repo;try{repo=await fetchRepo(await resolveSource(channel)),s?.stop(`Compared against ${sourceLabel(repo.source)}`)}catch(err){throw s?.stop(`Failed to reach ${REPO}`),CliError.failure(err,{json})}try{input=cloneInput(repo,{node,config,channel,strict},cwd)}catch(err){throw CliError.failure(err,{json})}finally{repo.cleanup()}}else{s?.start("Checking for updates");let found;try{found=await latestWithoutClone(channel),s?.stop(`Latest skills v${found.latest}`)}catch(err){throw s?.stop("Failed to check for updates"),CliError.failure(err,{json})}input={node,config,channel,...found,drift:null,prettierignore:statusPrettierignore(cwd),strict}}let report=buildStatusReport(input);if(json){console.log(serializeStatusReport(report)),report.strict.failed&&(process.exitCode=1);return}if(renderStatus(report,input),report.strict.failed)throw CliError.reported();outro(color_default.dim(drift?"Read-only \u2014 nothing changed.":"Read-only \u2014 nothing changed (drift check skipped)."))}function cloneInput(repo,base,cwd){let{config}=base,index=parseCapabilityIndex(repo.dir),frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`)),recordedLayout=configLayout(config),upstreamLayout=detectLayout(repo.dir),files=layoutMismatch(recordedLayout,upstreamLayout)?{diff:null,absentUpstream:null}:{diff:diffInstalledCapabilities({repoDir:repo.dir,projectRoot:cwd,capabilities:(config.capabilities??[]).filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`)),layout:recordedLayout}),absentUpstream:absentInstallSurfaces({repoDir:repo.dir,layout:upstreamLayout})};return{...base,latest:readSkillsVersion(repo.dir),source:repo.source,drift:{...files,hooks:diffHookWiring(repo.dir,cwd),unknown:index.unknown,orphans:statusOrphans(repo.dir,cwd,config,frozen),upstreamLayout},prettierignore:statusPrettierignore(cwd)}}function renderStatus(report,input){printArchetypeVersion(report,input.source);let deprecation=flatDeprecationLines(report.layout.recorded);deprecation&&note(deprecation.join(`
3
+ `),"DEPRECATED"),printModels(input.config),printPrettierignore(input.prettierignore);let drift=input.drift;if(drift===null)return;let unknownWarning=unknownCapabilitiesWarning(drift.unknown);unknownWarning&&log.warn(unknownWarning),report.drift===null?printLayoutNote(report.layout.recorded,drift.upstreamLayout):printDriftSection(report.drift,sourceLabel(input.source));let orphanLines=orphanNoteLines(report.orphans??[]);orphanLines&&note(orphanLines.join(`
4
+ `),"ORPHANED");let hookLines=hookWiringLines(drift.hooks);hookLines&&note(hookLines.join(`
5
+ `),"HOOKS")}async function latestWithoutClone(channel){if(channel==="latest"){let release=await resolveLatestReleaseVersion();return{latest:release.version,source:release}}return{latest:await fetchRemoteSkillsVersion(),source:await resolveSource("main")}}function channelRow(channel){return channel==="latest"?row("Channel","latest \u2014 verified releases"):`${row("Channel","main \u2014 the pharn-oss tip")} ${color_default.dim("(`pharn update --ref latest` follows verified releases)")}`}function printArchetypeVersion(report,source){let{ahead,outdated,latest,channel}=report.version,installed=terminalSafe(report.version.installed),aheadNote=source.kind==="release"?`(ahead of the latest verified release v${latest} \u2014 installed from main)`:`(ahead of pharn-oss main (v${latest}) \u2014 main has moved back; \`pharn update --force\` downgrades)`,outdatedNote=source.kind==="release"?`(newer verified release ${source.tag} \u2014 run \`pharn update\`)`:"(update available, run `pharn update`)",currentNote=source.kind==="release"?"(no newer verified release)":"(up to date)",skillsLine=ahead?`${row("Skills version",`v${installed}`)} ${color_default.dim(aheadNote)}`:outdated?`${row("Skills version",`v${installed} \u2192 v${latest}`)} ${color_default.dim(outdatedNote)}`:`${row("Skills version",`v${installed}`)} ${color_default.dim(currentNote)}`;note([skillsLine,channelRow(channel),row("Source",sourceDescription(source)),"",row("Archetypes",report.archetypes.join(", ")||"(none)"),row("Capabilities",String(report.capabilities.count))].join(`
6
+ `),"VERSION")}function printModels(config){if(config.models===void 0)return;let floor=layoutPaths(configLayout(config)).floor;note(modelsNoteLines(config.models,floor).join(`
7
+ `),"MODELS")}function modelsNoteLines(block,floor){let check=checkModelsBlock(block);return check.kind==="invalid"?["pharn-oss's rules reject this block:",...check.reds.map(red=>` ${terminalSafe(red.detail,{max:300})}`),color_default.dim("Fix it by hand. The checker installed with PHARN says the same:"),color_default.dim(modelsCheckerCommand(floor,"validate"))]:check.kind==="no-stages"?["Declares no stages: pharn-oss's checker reads that as none declared."]:[...resolvedStageLines(check.stages),"",...modelsLabelLines(floor).map(line=>color_default.dim(line))]}function statusPrettierignore(cwd){let{records}=recordsBaseline(readRecords(cwd));return records===null?null:planPrettierignore(cwd,Object.keys(records))}function printPrettierignore(plan){let lines=plan===null?null:prettierignoreLines(plan,{status:!0});lines!==null&&note(lines.text,"PRETTIER")}function statusOrphans(repoDir,cwd,config,frozen){let{records}=recordsBaseline(readRecords(cwd));if(records===null)return null;let layout=configLayout(config);if(detectLayout(repoDir)!==layout)return null;let all=config.capabilities??[],isFrozen=cap2=>frozen.has(`${cap2.role}:${cap2.name}`),expected=collectExpectedInstallPaths({repoDir,capabilities:all.filter(cap2=>!isFrozen(cap2)),layout});return findOrphans({projectRoot:cwd,records,expected,capabilities:all,frozen:all.filter(isFrozen)}).orphans}function printLayoutNote(recorded,upstream){note([`Recorded at the ${recorded} layout; pharn-oss now ships the ${upstream} layout.`,"Drift is not checked across layouts \u2014 your files are not where this","source puts them, so neither the file comparison nor the NOT SHIPPED","UPSTREAM check ran.",color_default.dim("Run `pharn update` to move the install; drift is checked after the move."),color_default.dim("`pharn status --strict` fails until the install is moved.")].join(`
8
+ `),"LAYOUT")}function printDriftSection(result,ref){let{absentUpstream}=result;if(result.modified.length===0&&result.missing.length===0&&result.unreadable.length===0&&absentUpstream.length===0){note(`No drift \u2014 ${result.okCount} file(s) match ${ref}.`,"DRIFT");return}let lines=[];if(result.modified.length){lines.push(` DIFFERS FROM ${ref} (PHARN-owned)`);for(let p of result.modified)lines.push(` ${p}`);lines.push(color_default.dim(" `pharn update` keeps files you've edited and cleanly"),color_default.dim(" upgrades the rest; `--force` overwrites edits too"),color_default.dim(" (backed up to pharn/.backup/ first)."))}if(result.missing.length){lines.length&&lines.push(""),lines.push(" MISSING (expected but absent)");for(let p of result.missing)lines.push(` ${p}`);lines.push(color_default.dim(" Run `pharn update` to restore them (files you edited are kept)."),color_default.dim(" To add a capability not yet in pharn.config.json, use `pharn add`"),color_default.dim(" (additive-only \u2014 already-listed capabilities are a no-op)."))}if(result.unreadable.length){lines.length&&lines.push(""),lines.push(" UNREADABLE \u2014 not a regular readable file");for(let{rel,reason}of result.unreadable)lines.push(` ${rel} \u2014 ${reason}`);lines.push(color_default.dim(" pharn cannot compare these, and `pharn update` skips them too."),color_default.dim(" Inspect each path by hand \u2014 a directory, a symlink, or an"),color_default.dim(" unreadable file sits where pharn expects a regular file."))}if(absentUpstream.length){lines.length&&lines.push(""),lines.push(` NOT SHIPPED UPSTREAM \u2014 ${ref} has no file here`);for(let{surface,path}of absentUpstream)lines.push(` ${terminalSafe(path)} (${surface})`);lines.push(color_default.dim(" Installed commands, hooks and checkers that use these will"),color_default.dim(" not find them. If pharn-oss moved them, a newer pharn may"),color_default.dim(" know where: npm i -g @pharn-dev/pharn@latest"))}lines.push("",color_default.dim(` ${result.okCount} file(s) match ${ref}.`)),note(lines.join(`
9
+ `),"DRIFT")}export{runStatus};
@@ -0,0 +1,4 @@
1
+ import{planUninstall,reclassifyDeletes}from"./chunk-PDDT7V7X.js";import{BACKUP_DIR,LOCK_DIR,ProjectLockedError,backupDirIgnored,createBackup,interactiveAllowed,printBackupNotice,withProjectLock}from"./chunk-ZQWLF3HH.js";import"./chunk-BCURDSJC.js";import{displayHook,hooksReferencing}from"./chunk-KKY6HERY.js";import"./chunk-KZCUUHJT.js";import{RECORDS_FILE,isInstallRootPath,readRecords,recordsBaseline,recordsPath,warnIfOlderCli}from"./chunk-FUQURK5N.js";import{CLAUDE_HOOKS_DIR,CLAUDE_SETTINGS_FILE}from"./chunk-SQLIXTIY.js";import"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,assertConfigFingerprintUnchanged,color_default,configFingerprint,configPath,loadArchetypeConfig}from"./chunk-LF4PFADC.js";import{safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe}from"./chunk-A77BLCF4.js";import{lstatSync,readdirSync,rmdirSync,unlinkSync}from"node:fs";import{posix}from"node:path";import{confirm,intro,isCancel,note,outro}from"@clack/prompts";var MAX_LISTED=10,UninstallError=class extends Error{constructor(message){super(message),this.name="UninstallError"}};async function runUninstall(opts={}){intro("pharn uninstall");let cwd=process.cwd(),result;try{result=await withProjectLock(cwd,"uninstall",()=>uninstallProject(cwd,opts))}catch(err){throw err instanceof ProjectLockedError||err instanceof UninstallError?CliError.error(err.message):err}result!==null&&(reportResult(cwd,result,finishPharnDir(cwd)),outro(`${color_default.green("\u2714")} PHARN was uninstalled.`))}async function uninstallProject(cwd,opts){if(lstatSync(configPath(cwd),{throwIfNoEntry:!1})===void 0)return outro(`PHARN is not installed here (no ${CONFIG_FILENAME}). Nothing was removed.`),null;let fingerprint=configFingerprint(cwd);warnIfOlderCli(loadArchetypeConfig(cwd));let records=usableRecords(cwd);if(typeof records=="string")throw CliError.error(records);let preview=planUninstall(cwd,records);if(preview.unsafe.length>0)throw CliError.error(unsafeMessage(preview));if(note(planLines(preview,settingsRecorded(records)).join(`
2
+ `),"PLAN"),!opts.yes){if(!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("`pharn uninstall` asks for confirmation, and this is not an interactive terminal. Re-run it in a terminal, or pass --yes to uninstall without asking. Nothing was removed.");let ok=await confirm({message:`Uninstall PHARN \u2014 delete ${preview.delete.length} file(s), ${RECORDS_FILE} and ${CONFIG_FILENAME}?`,initialValue:!1});if(isCancel(ok)||ok!==!0)throw CliError.cancel()}return applyUninstall(cwd,records,preview,fingerprint)}function usableRecords(cwd){let read=readRecords(cwd),baseline=recordsBaseline(read);return baseline.records!==null?baseline.records:`Cannot uninstall: ${read.kind==="invalid"?escapeUnsafe(read.message):`there is no ${RECORDS_FILE}`}. ${RECORDS_FILE} is the only proof of which files pharn wrote, so without a usable one nothing was removed. Remove PHARN by hand instead (docs/troubleshooting.md, "Removing PHARN by hand").`}function unsafeMessage(plan){let first=plan.unsafe[0];return`Refusing to uninstall: ${escapeUnsafe(first.component)} is a symbolic link, so deleting ${escapeUnsafe(first.rel)} through it would delete a file OUTSIDE the project. Nothing was removed.`}async function applyUninstall(cwd,records,planned,fingerprint){assertConfigFingerprintUnchanged(cwd,fingerprint,"uninstall");let proof=usableRecords(cwd);if(typeof proof=="string")throw new UninstallError(proof);let plan=reclassifyDeletes(cwd,records,planned);if(plan.unsafe.length>0)throw new UninstallError(unsafeMessage(plan));let backupDir;try{backupDir=createBackup(cwd,[CONFIG_FILENAME])}catch(err){throw new UninstallError(`Could not back up ${CONFIG_FILENAME} before uninstalling: ${errorMessage(err).replace(/\.$/,"")}. Nothing was removed.`)}printBackupNotice({dir:backupDir,saved:CONFIG_FILENAME,gitignored:backupDirIgnored(cwd)});let deleted=[];for(let rel of plan.delete)try{unlinkSync(safeJoin(cwd,rel)),deleted.push(rel)}catch(err){if(err.code==="ENOENT")continue;throw new UninstallError(`Could not delete ${escapeUnsafe(rel)}: ${errorMessage(err).replace(/\.$/,"")}. ${deleted.length} file(s) were deleted before it; ${RECORDS_FILE} and ${CONFIG_FILENAME} were kept, so re-running \`pharn uninstall\` continues from here.`)}let{removedDirs,keptDirs}=removeEmptyDirs(cwd,deleted);return unlinkIfPresent(recordsPath(cwd),RECORDS_FILE),unlinkIfPresent(configPath(cwd),CONFIG_FILENAME),{plan,deleted,removedDirs,keptDirs,backupDir,records}}function unlinkIfPresent(abs,label){try{unlinkSync(abs)}catch(err){if(err.code==="ENOENT")return;throw new UninstallError(`Could not delete ${label}: ${errorMessage(err).replace(/\.$/,"")}. Every file pharn could prove it wrote is already gone; delete ${label} yourself to finish.`)}}function removeEmptyDirs(cwd,deleted){let candidates=new Set;for(let rel of deleted)for(let dir=posix.dirname(rel);dir!==".";dir=posix.dirname(dir))candidates.add(dir);let deepestFirst=[...candidates].sort((a,b)=>b.split("/").length-a.split("/").length||a.localeCompare(b)),removedDirs=[],keptDirs=[],blocked=new Set;for(let dir of deepestFirst)if(!blocked.has(dir))try{rmdirSync(safeJoin(cwd,dir)),removedDirs.push(dir)}catch(err){if(err.code==="ENOENT")continue;keptDirs.push(dir);for(let up=posix.dirname(dir);up!==".";up=posix.dirname(up))blocked.add(up)}return{removedDirs:removedDirs.sort(),keptDirs:keptDirs.sort()}}function listed(rels){let shown=rels.slice(0,MAX_LISTED).map(r=>` \u2022 ${escapeUnsafe(r)}`),more=rels.length-MAX_LISTED;return more>0?[...shown,` \u2026and ${more} more`]:shown}function settingsRecorded(records){return Object.hasOwn(records,CLAUDE_SETTINGS_FILE)}function untouchedLine(settingsIsRecorded){return`${settingsIsRecorded?"":`${CLAUDE_SETTINGS_FILE}, `}.claude/settings.local.json, every ${BACKUP_DIR}/ directory and the lines pharn added to .gitignore and .prettierignore are left untouched.`}function planLines(plan,settingsIsRecorded){let lines=[`Delete ${plan.delete.length} file(s) pharn installed and nobody changed.`];return plan.edited.length>0&&lines.push(`Keep ${plan.edited.length} file(s) you changed (they stay where they are):`,...listed(plan.edited)),plan.unverifiable.length>0&&lines.push(`Keep ${plan.unverifiable.length} path(s) that cannot be verified (not a regular file, or unreadable):`,...listed(plan.unverifiable)),plan.outside.length>0&&lines.push(`Leave ${plan.outside.length} recorded path(s) outside pharn's install paths (never deleted, whatever their hash):`,...listed(plan.outside)),plan.absent.length>0&&lines.push(`${plan.absent.length} recorded file(s) are already gone.`),lines.push(`Then remove directories left empty, and delete ${RECORDS_FILE} and ${CONFIG_FILENAME} (backed up to ${BACKUP_DIR}/ first).`,`Files pharn has no record of are never deleted. ${untouchedLine(settingsIsRecorded)}`),lines}function finishPharnDir(cwd){let dir=safeJoin(cwd,LOCK_DIR);try{return rmdirSync(dir),null}catch(err){if(err.code==="ENOENT")return null;try{return readdirSync(dir).sort()}catch{return[]}}}function reportResult(cwd,result,pharnLeft){let{plan,deleted,removedDirs,keptDirs,backupDir}=result,lines=[`Deleted ${deleted.length} file(s) and ${removedDirs.length} empty director${removedDirs.length===1?"y":"ies"}, plus ${RECORDS_FILE} and ${CONFIG_FILENAME}.`],kept=[...plan.edited,...plan.unverifiable].sort();if(kept.length>0&&lines.push(`Kept ${kept.length} file(s) pharn could not prove are unchanged \u2014 they are yours now:`,...listed(kept)),keptDirs.length>0&&lines.push(`Left ${keptDirs.length} director${keptDirs.length===1?"y":"ies"} that still hold other files:`,...listed(keptDirs)),lines.push(`${CONFIG_FILENAME} was backed up to ${backupDir}.`,`${untouchedLine(settingsRecorded(result.records))} Delete ${BACKUP_DIR}/ yourself once you no longer need it.`),pharnLeft!==null){let names=pharnLeft.slice(0,MAX_LISTED).map(n=>escapeUnsafe(n)),more=pharnLeft.length-names.length;lines.push(`${LOCK_DIR}/ was left because it still holds files pharn has no record of${names.length>0?` (${names.join(", ")}${more>0?`, \u2026and ${more} more`:""})`:""} \u2014 you may delete it once you no longer need them.`)}note(lines.join(`
3
+ `),"UNINSTALLED");let hookLines=danglingHookLines(cwd,result.records);hookLines.length>0&&note(hookLines.join(`
4
+ `),"HOOKS")}function danglingHookLines(cwd,records){let gone=Object.keys(records).filter(rel=>rel.startsWith(`${CLAUDE_HOOKS_DIR}/`)&&isInstallRootPath(rel)&&isGone(cwd,rel)),refs=hooksReferencing(cwd,gone);if(refs.length===0)return[];let lines=[];for(let ref of refs){if(ref.kind==="unreadable"){lines.push(` ${ref.file} could not be read (${ref.reason}); check it for hooks that run a removed script.`);continue}lines.push(` ${ref.file} still wires ${ref.entries.length} hook(s) whose script was removed:`,...ref.entries.map(e=>` ${displayHook(e)}`))}return lines.push(""," pharn never edits these files \u2014 remove those entries by hand."," Matching is textual: a hook that reaches a removed script another way is not listed."),lines}function isGone(cwd,rel){try{return lstatSync(safeJoin(cwd,rel),{throwIfNoEntry:!1})===void 0}catch{return!0}}export{runUninstall};
@@ -0,0 +1,15 @@
1
+ import{CapabilityRemovalError,absentSurfaceLines,deleteRootDocs,planCapabilityRemovals,planRootMigration,readUpstreamModels,removalBackupsNow,resolveCapabilities,rootDocsChangedSincePlan,rootMigrationNoteLines,runNodePrereq}from"./chunk-7LD2OYB4.js";import"./chunk-PDDT7V7X.js";import{decideFileAction,minCliGate,planUpdate}from"./chunk-DFMTJQO7.js";import{deleteCapabilityDir}from"./chunk-6LOUFC5E.js";import{BACKUP_DIR,ProjectLockedError,applyGitignore,backupAction,backupDirIgnored,createBackup,gitignoreLines,gitignorePending,gitignoreReport,interactiveAllowed,planGitignore,printBackupNotice,withProjectLock}from"./chunk-ZQWLF3HH.js";import"./chunk-BCURDSJC.js";import{applyPrettierignore,cap,checkModelsBlock,modelsLabelLines,planPrettierignore,prettierignoreLines,prettierignorePending,prettierignoreReport,serializeJsonReport}from"./chunk-B4EM6WAR.js";import{diffHookWiring,findOrphans,hookWiringLines,orphanNoteLines}from"./chunk-KKY6HERY.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-62AJFPPH.js";import{ApplyError,applyWrites,changedSince,readDiskState}from"./chunk-KZCUUHJT.js";import{channelOf,resolveSource,sourceDescription}from"./chunk-LVAJFL6J.js";import{MODELS_RECORD_KEY,RECORDS_FILE,RECORDS_SCHEMA_VERSION,absentInstallSurfaces,buildRecords,capabilitySubtree,carriedSettingsRecord,collectExpectedInstallPaths,configLayout,contentHash,detectLayout,fetchRemoteSkillsVersion,flatDeprecationLines,isInstalledHookFile,isProductCommandFile,layoutPaths,modelsRecordHash,readRecords,readSkillsVersion,recordsBaseline,recordsUnderCapabilities,resolveFeaturesReadme,warnIfOlderCli,writeRecords}from"./chunk-FUQURK5N.js";import{CLAUDE_COMMANDS_DIR,CLAUDE_HOOKS_DIR,FEATURES_README,PHARN_VERSION,REPO_URL}from"./chunk-SQLIXTIY.js";import{logErrorPlain,reportFatal}from"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,assertConfigFingerprintUnchanged,color_default,configFingerprint,loadArchetypeConfig,row,writePharnConfig}from"./chunk-LF4PFADC.js";import"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";function key(cap2){return`${cap2.role}:${cap2.name}`}function mergeCapabilities(selection,previous,frozen){let resolved=new Set(selection.selected.map(key)),inIndex=new Set([...selection.selected.map(key),...selection.skipped.map(key)]),previousSource=new Map,seenPrevious=new Set;for(let cap2 of previous){let k=key(cap2);seenPrevious.has(k)||(seenPrevious.add(k),previousSource.set(k,cap2.source))}let capabilities=[],changes=[];for(let sel of selection.selected){let k=key(sel);if(!seenPrevious.has(k)){let cap2={name:sel.name,role:sel.role,source:"auto"};capabilities.push(cap2),changes.push({cap:cap2,reason:"added"});continue}let source=previousSource.get(k)==="manual"?"manual":"auto";capabilities.push({name:sel.name,role:sel.role,source})}for(let cap2 of previous){let k=key(cap2);if(resolved.has(k))continue;if(frozen.has(k)){let kept={...cap2};capabilities.push(kept),changes.push({cap:kept,reason:"kept-frozen"});continue}if(cap2.source==="auto"){changes.push({cap:cap2,reason:"dropped-unselected"});continue}let inferred={...cap2,source:"manual"};if(!inIndex.has(k)){changes.push({cap:inferred,reason:"dropped-gone"});continue}capabilities.push(inferred),cap2.source===void 0&&changes.push({cap:inferred,reason:"kept-manual"})}return{capabilities,changes}}function decideModelsUpdate(input){let{current,upstream,recorded,recordsAvailable,force}=input,none={label:null,backup:!1,problems:[],upstreamReasons:[]};if(upstream.kind!=="ok")return{...none,...keep(current),outcome:upstream.kind==="absent"?"upstream-absent":"upstream-invalid",nextRecord:recorded,upstreamReasons:upstream.kind==="invalid"?upstream.reasons:[]};let latestHash=modelsRecordHash(upstream.block),diskHash=current===void 0?null:modelsRecordHash(current),decision=decideFileAction({diskHash,latestHash,recordedHash:recorded,recordsAvailable,force});return decision.action==="write"?{...none,outcome:decision.forced?"forced":decision.label==="restored"?"restored":"updated",label:decision.forced?decision.label:null,next:upstream.block,nextRecord:latestHash,backup:decision.backup}:decision.action==="noop"?{...none,outcome:"ok",next:current,nextRecord:latestHash}:{...none,...keep(current),outcome:"kept",label:decision.label,nextRecord:recorded}}function keep(current){if(current===void 0)return{next:void 0,problems:[]};let check=checkModelsBlock(current);return{next:current,problems:check.kind==="invalid"?check.reds.map(red=>red.detail):[]}}function isExecutableUnitPath(rel,paths){if(rel.startsWith(`${paths.floor}/`))return!0;let hooksPrefix=`${CLAUDE_HOOKS_DIR}/`;if(rel.startsWith(hooksPrefix))return isInstalledHookFile(rel.slice(hooksPrefix.length));let commandsPrefix=`${CLAUDE_COMMANDS_DIR}/`;return rel.startsWith(commandsPrefix)?isProductCommandFile(rel.slice(commandsPrefix.length)):!1}import{isDeepStrictEqual}from"node:util";function nextRecordStore(apply,extra){let orphanRecords=Object.fromEntries(Object.entries(apply.orphanRecords).filter(([rel])=>!extra.retired.has(rel))),files={...apply.frozenRecords,...orphanRecords,...apply.settingsRecords,...apply.plan.nextRecords,...extra.written,...apply.models.nextRecord!==null?{[MODELS_RECORD_KEY]:apply.models.nextRecord}:{}};for(let rel of extra.unwritten??[]){let previous=apply.records?.[rel];previous!==void 0?files[rel]=previous:delete files[rel]}return{skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,files}}function nextConfig(config,report,apply,channel,stamp){let{pendingSkillsVersion:_previousPending,frozenCapabilities:_previousFrozen,ref:_previousRef,...rest}=config;return{...rest,pharnVersion:stamp.pharnVersion,skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,...channel==="latest"?{ref:"latest"}:{},...report.pendingSkillsVersion!==null?{pendingSkillsVersion:report.pendingSkillsVersion}:{},...apply.frozenKeys.length>0?{frozenCapabilities:apply.frozenKeys}:{},capabilities:apply.configCapabilities,layout:report.layout,updatedAt:stamp.updatedAt,models:apply.models.next}}function jsonValue(value){return JSON.parse(JSON.stringify(value))}function loadResolved(config){let{updatedAt:_updatedAt,pharnVersion:_pharnVersion,layout:_layout,ref:_ref,commit:_commit,...rest}=config;return jsonValue({...rest,layout:configLayout(config),commit:config.commit??null,...channelOf(config)==="latest"?{ref:"latest"}:{}})}function planStateChanges(input){let{config,report,apply,channel,loadedRecords}=input,next=nextConfig(config,report,apply,channel,{pharnVersion:"",updatedAt:""}),store={schemaVersion:RECORDS_SCHEMA_VERSION,...nextRecordStore(apply,{written:{},retired:new Set})};return{config:!isDeepStrictEqual(loadResolved(next),loadResolved(config)),records:loadedRecords.kind!=="ok"||!isDeepStrictEqual(jsonValue(store),jsonValue(loadedRecords.store))}}function changesNoFiles(report){return report.writes.length===0&&!report.removals.some(r=>r.present)&&!(report.rootMigration?.docs??[]).some(d=>d.action==="delete")&&!gitignorePending(report.gitignore)&&!prettierignorePending(report.prettierignore)}function changesNothing(report,state){return changesNoFiles(report)&&!state.config&&!state.records}var USER_EDIT_SKIPS=new Set(["modified","unrecorded"]),DROP_REASONS=new Set(["dropped-unselected","dropped-gone"]);function isDrop(reason){return DROP_REASONS.has(reason)}function buildUpdatePlan(input){let{repoDir,sha,config,cwd,force,channel,onUnknownWarning}=input,index=parseCapabilityIndex(repoDir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&onUnknownWarning?.(unknownWarning);let frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`)),selection=resolveCapabilities(config.archetypes??[],index),merged=mergeCapabilities(selection,config.capabilities??[],frozen),configCapabilities=merged.capabilities,manifestCapabilities=configCapabilities.filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`)),installedVersion=readSkillsVersion(repoDir),layout=detectLayout(repoDir),previousLayout=configLayout(config),expected=collectExpectedInstallPaths({repoDir,capabilities:manifestCapabilities,layout}),latestHashes=new Map;for(let[rel,source]of expected)latestHashes.set(rel,contentHash(source));let diskStates=new Map;for(let rel of expected.keys())diskStates.set(rel,readDiskState(cwd,rel));let loadedRecords=readRecords(cwd),{records,note:recordsNote}=recordsBaseline(loadedRecords),unitPaths=layoutPaths(layout),plan=planUpdate({latestHashes,diskStates,records,force,unit:rel=>isExecutableUnitPath(rel,unitPaths),holdUnit:installedVersion!==config.skillsVersion}),removalPaths=layoutPaths(previousLayout),removals=planCapabilityRemovals({cwd,paths:removalPaths,drops:merged.changes.flatMap(({cap:cap2,reason})=>isDrop(reason)?[{cap:cap2,reason}]:[]),records,command:"update"}),models=decideModelsUpdate({current:config.models,upstream:readUpstreamModels(repoDir),recorded:records?.[MODELS_RECORD_KEY]??null,recordsAvailable:records!==null,force}),backups=models.backup?[...plan.backups,CONFIG_FILENAME]:plan.backups,versionWithheld=plan.counts.skipped>0,nextSkillsVersion=versionWithheld?config.skillsVersion:installedVersion,nextCommit=versionWithheld?config.commit:sha,pendingSkillsVersion=versionWithheld&&installedVersion!==nextSkillsVersion&&plan.skipped.every(g=>USER_EDIT_SKIPS.has(g.label)||g.label==="held")?installedVersion:null,paths=layoutPaths(layout),frozenRecords=records===null?{}:recordsUnderCapabilities(records,paths,configCapabilities.filter(cap2=>frozen.has(`${cap2.role}:${cap2.name}`))),orphanScan=findOrphans({projectRoot:cwd,records,expected,capabilities:configCapabilities,frozen:configCapabilities.filter(cap2=>frozen.has(`${cap2.role}:${cap2.name}`))}),rootMigration=plan.held!==null?null:planRootMigration({projectRoot:cwd,repoDir,layout,installedLayout:previousLayout,skillsVersion:installedVersion,records}),retired=new Set((rootMigration?.docs??[]).filter(d=>d.action==="delete").map(d=>d.rel)),orphans=orphanScan.orphans.filter(o=>!retired.has(o.path)),prettierignorePaths=[...expected.keys(),...Object.keys(frozenRecords),...Object.keys(orphanScan.records)],previouslyFrozen=new Set(config.frozenCapabilities??[]),skippedRels=plan.skipped.flatMap(group=>group.rels),hasSkippedFile=cap2=>{let prefix=`${capabilitySubtree(paths,cap2.role)}/${cap2.name}/`;return skippedRels.some(rel=>rel.startsWith(prefix))},frozenKeys=[...new Set(configCapabilities.filter(cap2=>{let key2=`${cap2.role}:${cap2.name}`;return frozen.has(key2)||previouslyFrozen.has(key2)&&hasSkippedFile(cap2)}).map(cap2=>`${cap2.role}:${cap2.name}`))].sort(),report={currentVersion:config.skillsVersion,installedVersion,recordedVersion:nextSkillsVersion,versionWithheld,pendingSkillsVersion,frozenCapabilities:frozenKeys,capCount:configCapabilities.length,layout,abandonedLayout:previousLayout!==layout&&plan.writes.length>0?previousLayout:null,featuresReadmeRelocation:records!==null&&FEATURES_README in records&&resolveFeaturesReadme(repoDir,layout)!==FEATURES_README,capabilityChanges:merged.changes,removals,files:plan.files,writes:plan.writes,backups,skipped:plan.skipped,counts:plan.counts,executableUnit:plan.held,models,modelsFloor:paths.floor,hookWiring:diffHookWiring(repoDir,cwd),absentUpstream:absentInstallSurfaces({repoDir,layout}),recordsNote,unknownWarning,unknownCapabilities:index.unknown,orphans,rootMigration,gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,prettierignorePaths)},apply={expected,records,plan,models,configCapabilities,frozen,frozenRecords,orphanRecords:orphanScan.records,settingsRecords:carriedSettingsRecord(cwd,records),nextSkillsVersion,nextCommit,frozenKeys,removalPaths,prettierignorePaths,seen:new Map(plan.writes.map(rel=>{let disk=diskStates.get(rel);return[rel,disk?.kind==="file"?disk.hash:null]}))},stateChanges=planStateChanges({config,report,apply,channel,loadedRecords});return{report:{...report,stateChanges,changesNothing:changesNothing(report,stateChanges)},apply}}import{log,note,outro}from"@clack/prompts";function defaultChannelNotice(config,ref){return ref!==void 0||channelOf(config)!=="main"?null:"Verified releases are now the default for new installs. This install keeps following pharn-oss main; run `pharn update --ref latest` to switch (recorded on first use)."}function noChangeVerdict(r){return r.counts.skipped===0&&r.recordedVersion===r.installedVersion?"Up to date.":"Nothing to change."}function forcedOverwriteSections(r,verb){let sections=["modified","unrecorded","unverifiable"].map(label=>({heading:`${verb} OVERWRITE (--force) \u2014 ${label}`,rels:r.files.filter(f=>f.action==="write"&&f.forced&&f.label===label).map(f=>f.rel)}));return sections.push({heading:`${verb} OVERWRITE (--force) \u2014 your models block`,rels:r.models.backup?[CONFIG_FILENAME]:[]}),sections.filter(s=>s.rels.length>0)}function reportForcedOverwrites(r){let sections=forcedOverwriteSections(r,"WILL");if(sections.length===0)return;let lines=[];for(let{heading,rels}of sections){lines.push(` ${heading}`);for(let rel of rels)lines.push(` ${rel}`);lines.push("")}lines.push(color_default.dim(` Each is copied to ${BACKUP_DIR}/<timestamp>/ first (${r.backups.length} file(s)).`)),note(lines.join(`
2
+ `),"OVERWRITE")}function reportRootMigration(m,result){let lines=m===null?null:rootMigrationNoteLines(m,result);lines&&note(lines.join(`
3
+ `),"ROOT MIGRATION")}var FORCEABLE_SKIPS=new Set(["modified","unrecorded","unverifiable","held"]),MAX_UNIT_BLOCKERS=20;function executableUnitLines(hold,preview){return hold===null?null:[...unitBlockerLines(hold,preview),...unitMissingLines(hold.missing??[],preview),""," To upgrade the unit: revert the skipped files, or run",` \`pharn update --force\` (it backs them up to ${BACKUP_DIR}/ first).`]}function unitBlockerLines(hold,preview){let shown=hold.blocking.slice(0,MAX_UNIT_BLOCKERS),more=hold.blocking.length-shown.length;return[" The floor, the hooks and the pharn-* commands run together, so pharn"," writes them all or none. These unit files "+(preview?"would be skipped":"were skipped")+":",...shown.map(b=>` ${b.label.padEnd(12)} ${terminalSafe(b.rel,{max:300})}`),...more>0?[` \u2026 and ${more} more`]:[],"",` So ${hold.held.length} other unit file(s) `+(preview?"would not be written":"were not written")+" either, and the"," unit stays at the version you had: upgrading part of it would mix two"," versions that may not load together."]}function unitMissingLines(missing,preview){if(missing.length===0)return[];let shown=missing.slice(0,MAX_UNIT_BLOCKERS),more=missing.length-shown.length;return[""," Of those, these are not on disk, so they "+(preview?"would stay":"stay")+" missing until the hold ends:",...shown.map(rel=>` ${terminalSafe(rel,{max:300})}`),...more>0?[` \u2026 and ${more} more`]:[]]}function reportExecutableUnit(hold,preview){let lines=executableUnitLines(hold,preview);lines&&note(lines.join(`
4
+ `),"EXECUTABLE UNIT")}function reportOutcome(outcome,force){let{plan,recordsNote,versionWithheld}=outcome,{counts}=plan;recordsNote&&log.warn(`\u26A0 ${escapeUnsafe(recordsNote)}`),reportCapabilityChanges(outcome.capabilityChanges,outcome.removals,!1),reportModels(outcome.models,outcome.modelsFloor,outcome.backup);let hookLines=outcome.hookWiring?hookWiringLines(outcome.hookWiring):null;hookLines&&note(hookLines.join(`
5
+ `),"HOOKS"),reportAbsentSurfaces(outcome.absentUpstream??[]),reportExecutableUnit(plan.held,!1);let forceable=reportSkipped(plan.skipped,!1);if(reportOrphans(outcome.orphans),reportRootMigration(outcome.rootMigration,outcome.rootMigrationResult),reportLayoutWarnings(outcome.abandonedLayout,outcome.featuresReadmeRelocation,!1),versionWithheld&&log.warn(withheldVersionLine({skipped:counts.skipped,recordedVersion:outcome.recordedVersion,installedVersion:outcome.installedVersion,forceable,preview:!1})),outcome.unchanged){outro(`${noChangeVerdict({counts,recordedVersion:outcome.recordedVersion,installedVersion:outcome.installedVersion})} ${color_default.dim(`(unchanged ${counts.ok} \xB7 skipped ${counts.skipped} \xB7 ${outcome.capCount} capabilit${outcome.capCount===1?"y":"ies"}, skills v${outcome.recordedVersion})`)}`);return}let summary=`updated ${counts.updated} \xB7 restored ${counts.restored} \xB7 unchanged ${counts.ok}`+(force?` \xB7 forced ${counts.forced}`:"")+` \xB7 skipped ${counts.skipped}`;outro(`${color_default.green("\u2714")} ${summary} ${color_default.dim(`(${outcome.capCount} capabilit${outcome.capCount===1?"y":"ies"}, skills v${outcome.recordedVersion})`)}`)}function reportAbsentSurfaces(absent){let lines=absentSurfaceLines(absent);lines&&note(lines.join(`
6
+ `),"NOT SHIPPED")}function withheldVersionLine(o){let{skipped,recordedVersion,installedVersion,forceable,preview}=o;if(recordedVersion===installedVersion){let action=forceable?`${preview?"run":"re-run"} with --force to overwrite them (backed up to ${BACKUP_DIR}/ first), or keep them as they are`:"resolve them by hand";return`${skipped} file(s) ${preview?"would be":"were"} skipped; your install is already at skills v${installedVersion}, so there is no upgrade to finish \u2014 ${action}.`}return preview?`${skipped} file(s) would be skipped, so your install would stay recorded as skills v${recordedVersion} (upstream is v${installedVersion}) \u2014 resolve them${forceable?", or run with --force,":""} to finish the upgrade.`:`${skipped} file(s) were skipped, so your install is still recorded as skills v${recordedVersion} (upstream is v${installedVersion}) \u2014 resolve them${forceable?", or re-run with --force,":""} to finish the upgrade.`}function reportSkipped(skipped,preview){let forceable=skipped.some(g=>FORCEABLE_SKIPS.has(g.label)),hasUnreadable=skipped.some(g=>!FORCEABLE_SKIPS.has(g.label));if(skipped.length>0){let lines=[];for(let group of skipped){lines.push(` ${skipHeading(group.label)}`);for(let rel of group.rels)lines.push(` ${rel}`);lines.push("")}forceable&&lines.push(color_default.dim(preview?` Run \`pharn update --force\` to overwrite (skipped files would be backed up to ${BACKUP_DIR}/ first).`:` Re-run with --force to overwrite (skipped files are backed up to ${BACKUP_DIR}/ first).`)),hasUnreadable&&lines.push(color_default.dim(" --force cannot clear the UNREADABLE paths above."),color_default.dim(" Inspect each path by hand \u2014 a directory, a symlink, or an"),color_default.dim(" unreadable file sits where pharn expects a regular file.")),note(lines.join(`
7
+ `),"SKIPPED")}return forceable}function reportOrphans(orphans){let lines=orphanNoteLines(orphans);lines&&note(lines.join(`
8
+ `),"ORPHANED")}function reportLayoutWarnings(abandonedLayout,featuresReadmeRelocation,preview){abandonedLayout==="flat"?log.warn(preview?"Your install would move to the pharn/ layout. The old top-level copies would be left behind and no longer managed by pharn \u2014 you would delete them by hand.":"Your install moved to the pharn/ layout. The old top-level copies are left behind and are no longer managed by pharn \u2014 delete them by hand."):abandonedLayout==="pharn"&&log.warn(preview?"Your install would move to the flat layout. The old pharn/ tree (contracts, floor scripts, docs, and capabilities) would be left behind and no longer managed by pharn \u2014 you would delete it by hand.":"Your install moved to the flat layout. The old pharn/ tree (contracts, floor scripts, docs, and capabilities) is left behind and is no longer managed by pharn \u2014 delete it by hand."),featuresReadmeRelocation&&log.warn(preview?"Your install would keep the product-loop boundary contract at pharn/features/README.md. A copy at the project root (features/README.md) would be left behind and no longer managed by pharn \u2014 you would delete it by hand.":"Your install now keeps the product-loop boundary contract at pharn/features/README.md. A copy at the project root (features/README.md) is left behind and is no longer managed by pharn \u2014 delete it by hand.")}function reportDryRun(r,force,channel,config){r.recordsNote&&log.warn(`\u26A0 ${escapeUnsafe(r.recordsNote)}`);let writes=r.files.filter(f=>f.action==="write"),sections=[{heading:"WOULD WRITE \u2014 restored (missing from your project)",rels:writes.filter(f=>f.label==="restored").map(f=>f.rel)},{heading:"WOULD WRITE \u2014 updated (still exactly as pharn wrote them)",rels:writes.filter(f=>f.label==="updated").map(f=>f.rel)},...forcedOverwriteSections(r,"WOULD")],deletes=r.removals.filter(removal=>removal.present);sections.push({heading:"WOULD DELETE \u2014 directories of capabilities dropped from your config",rels:deletes.map(removal=>`${removal.dir}/`)});let backupRels=[...new Set([...r.backups,...r.removals.flatMap(x=>x.backups)])],lines=[];for(let{heading,rels}of sections)if(rels.length!==0){lines.push(` ${heading}`);for(let rel of rels)lines.push(` ${rel}`);lines.push("")}if(backupRels.length>0){lines.push(` WOULD BACK UP ${backupRels.length} file(s) to ${BACKUP_DIR}/<timestamp>/ first`);for(let rel of backupRels)lines.push(` ${rel}`);lines.push("")}let gitignore=gitignoreLines(r.gitignore,{preview:!0});gitignore!==null&&!gitignore.warn&&lines.push(` ${gitignore.text}`,"");let prettierignore=prettierignoreLines(r.prettierignore,{preview:!0});prettierignore!==null&&!prettierignore.warn&&lines.push(` ${prettierignore.text}`,"");let stateFiles=[...r.stateChanges.config?[CONFIG_FILENAME]:[],...r.stateChanges.records?[RECORDS_FILE]:[]];r.changesNothing?lines.push(" Nothing would be written.",""):changesNoFiles(r)&&lines.push(` Would rewrite only ${stateFiles.join(" and ")}.`,""),lines.push(` UNCHANGED ${r.counts.ok} file(s) \xB7 SKIPPED ${r.counts.skipped} file(s)`),channel!==channelOf(config)&&lines.push("",` Would record channel: ${channel}`),note(lines.join(`
9
+ `),"PLAN"),gitignore?.warn&&log.warn(gitignore.text),prettierignore?.warn&&log.warn(prettierignore.text),reportCapabilityChanges(r.capabilityChanges,r.removals,!0),reportModels(r.models,r.modelsFloor,null,!0);let hookLines=hookWiringLines(r.hookWiring);hookLines&&note(hookLines.join(`
10
+ `),"HOOKS"),reportAbsentSurfaces(r.absentUpstream),reportExecutableUnit(r.executableUnit,!0);let forceable=reportSkipped(r.skipped,!0);if(reportOrphans(r.orphans),reportRootMigration(r.rootMigration,null),reportLayoutWarnings(r.abandonedLayout,r.featuresReadmeRelocation,!0),r.versionWithheld?(log.warn(withheldVersionLine({skipped:r.counts.skipped,recordedVersion:r.recordedVersion,installedVersion:r.installedVersion,forceable,preview:!0})),r.pendingSkillsVersion!==null&&log.info(`Would record skills v${r.pendingSkillsVersion} as pending, so \`pharn add\` installs at it.`)):log.info(`Would record skills v${r.recordedVersion}.`),r.frozenCapabilities.length>0&&log.info(`Would keep unread upstream capabilities as they are: ${r.frozenCapabilities.join(", ")}.`),r.changesNothing){outro(`Dry run \u2014 ${noChangeVerdict(r)} Unchanged ${r.counts.ok} \xB7 skipped ${r.counts.skipped}. A real run would ask nothing and write nothing.`);return}outro(`Dry run \u2014 would write ${writes.length}${deletes.length>0?` \xB7 delete ${deletes.length} director${deletes.length===1?"y":"ies"}`:""} \xB7 back up ${backupRels.length} \xB7 unchanged ${r.counts.ok} \xB7 skipped ${r.counts.skipped}. Nothing was changed. Run \`pharn update${force?" --force":""}\` to apply.`)}function reportBackup(backup,opts){let output=opts.aborted?process.stderr:process.stdout;opts.aborted&&log.warn(`The update stopped part-way \u2014 some originals may already have been ${ABORTED_PHRASE[backup.action]}.`,{output}),printBackupNotice({dir:backup.dir,saved:backup.count,action:backup.action,gitignored:backup.gitignored},opts)}var ABORTED_PHRASE={overwriting:"overwritten",removing:"removed","overwriting and removing":"overwritten or removed"},CHANGE_ORDER=[{reason:"added",heading:"ADDED \u2014 newly selected for your archetypes"},{reason:"dropped-unselected",heading:"REMOVED \u2014 no longer selected for your archetypes"},{reason:"dropped-gone",heading:"REMOVED \u2014 no longer exists upstream (was a manual add)"},{reason:"kept-manual",heading:"KEPT \u2014 your manual add, not selected by your archetypes"},{reason:"kept-frozen",heading:"KEPT \u2014 pharn could not read these upstream this run, so they were left exactly as they are"}];function reportCapabilityChanges(changes,removals,preview){if(changes.length===0)return;let removalOf=new Map(removals.map(r=>[`${r.cap.role}:${r.cap.name}`,r])),lines=[];for(let{reason,heading}of CHANGE_ORDER){let inGroup=changes.filter(c=>c.reason===reason);if(inGroup.length!==0){lines.push(` ${heading}`);for(let{cap:cap2}of inGroup){let key2=`${cap2.role}:${cap2.name}`,removal=removalOf.get(key2);lines.push(removal===void 0?` ${key2}`:` ${key2} \u2014 ${removalPhrase(removal,preview)}`)}lines.push("")}}removals.length>0&&(lines.push(color_default.dim(preview?" Removed capabilities\u2019 directories would be deleted, so PHARN would no longer run them.":" Removed capabilities\u2019 directories are deleted, so PHARN no longer runs them.")),removals.some(r=>r.backups.length>0)&&lines.push(color_default.dim(preview?` Files in them pharn did not write would be copied to ${BACKUP_DIR}/ first.`:` Files in them pharn did not write were copied to ${BACKUP_DIR}/ first.`))),note(lines.join(`
11
+ `),"CAPABILITIES")}function removalPhrase(removal,preview){if(!removal.present)return"already gone";let n=removal.backups.length,deleted=preview?"directory would be deleted":"directory deleted";return n===0?deleted:preview?`${deleted} (${n} file(s) would be backed up first)`:`${deleted} (${n} file(s) backed up first)`}function reportModels(models,floor,backup,preview=!1){let lines=modelsReportLines(models,backup,preview);lines.length!==0&&(models.next!==void 0&&lines.push("",...modelsLabelLines(floor).map(line=>color_default.dim(line))),note(lines.join(`
12
+ `),"MODELS"))}function modelsReportLines(models,backup,preview){let quoted=text=>` ${terminalSafe(text,{max:300})}`,lines=[];switch(models.outcome){case"ok":return[];case"restored":lines.push(preview?"Your config has no models block \u2014 would write pharn-oss's.":"Your config had no models block \u2014 wrote pharn-oss's.");break;case"updated":lines.push(preview?"Would move your models block to pharn-oss's current one: you have":"Moved your models block to pharn-oss's current one: you had","not changed it since pharn wrote it.");break;case"forced":lines.push(preview?"Would replace your models block with pharn-oss's (--force).":"Replaced your models block with pharn-oss's (--force).",preview?`Your current ${CONFIG_FILENAME} would be copied to ${BACKUP_DIR}/<timestamp>/ first.`:`Your previous ${CONFIG_FILENAME} is in ${backup?.dir??`${BACKUP_DIR}/`}.`);break;case"kept":lines.push(keptModelsHeading(models.label));break;case"upstream-invalid":lines.push("pharn-oss's models block was not applied; this pharn rejects it:",...models.upstreamReasons.map(quoted),"If pharn-oss changed its models format, upgrade pharn","(npm i -g @pharn-dev/pharn@latest) and run `pharn update` again.");break;case"upstream-absent":if(models.problems.length===0)return[];lines.push("pharn-oss ships no models block, so yours is kept.");break}return models.outcome==="kept"&&models.problems.length>0?(lines.push("","pharn-oss's rules reject your models block:",...models.problems.map(quoted),"","Replace it by hand, or delete the `models` key from",`${CONFIG_FILENAME} so the next \`pharn update\` restores pharn-oss's.`,color_default.dim("--force also replaces it, after backing up the config,"),color_default.dim("but it overwrites every file you edited, too.")),lines):(models.problems.length>0&&lines.push("","pharn-oss's rules still reject your models block \u2014 left as is,","fix it by hand:",...models.problems.map(quoted)),models.outcome==="kept"&&lines.push("",color_default.dim("--force replaces it with pharn-oss's, after copying"),color_default.dim(`${CONFIG_FILENAME} to ${BACKUP_DIR}/.`)),lines)}function keptModelsHeading(label){switch(label){case"modified":return"Kept your models block \u2014 you changed it since pharn wrote it.";case"unrecorded":return"Kept your models block \u2014 pharn has no record of writing it.";default:return`Kept your models block \u2014 no usable ${RECORDS_FILE} to check it.`}}function skipHeading(label){switch(label){case"modified":return"MODIFIED \u2014 you changed these since pharn wrote them";case"unrecorded":return"UNRECORDED \u2014 pharn has no record of writing these";case"unverifiable":return`UNVERIFIABLE \u2014 no usable ${RECORDS_FILE} to compare against`;case"held":return"HELD \u2014 not written, so the executable unit stays at one version";default:return"UNREADABLE \u2014 not a regular readable file"}}import{confirm,intro,isCancel,log as log2,note as note2,outro as outro2,spinner}from"@clack/prompts";var UPDATE_SCHEMA_VERSION=1,MAX_REASON=300,MAX_UNKNOWN_FIELD=200,capAll=(values,max)=>values.map(v=>cap(v,max));function planReport(p,compact){let kept=compact?p.files.filter(f=>f.action!=="noop"):p.files;return{layout:p.layout,abandonedLayout:p.abandonedLayout,featuresReadmeRelocation:p.featuresReadmeRelocation,rootMigration:p.rootMigration===null?null:{docs:p.rootMigration.docs.map(d=>({rel:d.rel,action:d.action})),moves:[],scratchNotice:p.rootMigration.scratchNotice,gitignoreHints:[...p.rootMigration.gitignoreHints]},capabilities:{count:p.capCount,changes:p.capabilityChanges.map(c=>({role:c.cap.role,name:c.cap.name,source:c.cap.source??null,reason:c.reason})),...p.removals.length>0?{removals:p.removals.map(r=>({role:r.cap.role,name:r.cap.name,reason:r.reason,dir:r.dir,present:r.present,backups:[...r.backups]}))}:{}},files:kept.map(f=>({rel:f.rel,action:f.action,label:f.label,backup:f.backup,forced:f.forced})),...compact?{filesOmitted:{action:"noop",count:p.files.length-kept.length}}:{},writes:[...p.writes],backups:[...new Set(p.backups)],skipped:p.skipped.map(g=>({label:g.label,rels:[...g.rels]})),counts:{updated:p.counts.updated,restored:p.counts.restored,ok:p.counts.ok,forced:p.counts.forced,skipped:p.counts.skipped},...p.executableUnit!==null?{executableUnit:{blocking:p.executableUnit.blocking.map(b=>({rel:b.rel,label:b.label})),held:[...p.executableUnit.held],...(p.executableUnit.missing??[]).length>0?{missing:[...p.executableUnit.missing]}:{}}}:{},models:{outcome:p.models.outcome,label:p.models.label,replacedLegacyDefault:!1,backup:p.models.backup,conversion:null,problems:capAll(p.models.problems,MAX_REASON),upstreamReasons:capAll(p.models.upstreamReasons,MAX_REASON)},hooks:{status:p.hookWiring.status,missing:p.hookWiring.missing,localOnly:p.hookWiring.localOnly??[],file:p.hookWiring.file??null,reason:p.hookWiring.reason??null,...p.hookWiring.replace?.length?{replace:p.hookWiring.replace}:{}},...p.absentUpstream.length>0?{absentUpstream:p.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))}:{},frozenCapabilities:[...p.frozenCapabilities],unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),recordsNote:p.recordsNote===null?null:cap(p.recordsNote,MAX_REASON),...p.orphans.length>0?{orphans:p.orphans.map(o=>({path:o.path,state:o.state,...o.reason!==void 0?{reason:cap(o.reason,MAX_REASON)}:{}}))}:{},...gitignoreKey(p.gitignore),...prettierignoreKey(p.prettierignore)}}function prettierignoreKey(plan){let report=prettierignoreReport(plan);return report===null?{}:{prettierignore:report}}function gitignoreKey(plan){let report=gitignoreReport(plan);return report===null?{}:{gitignore:report}}function buildUpdateReport(input){let{plan}=input,compact=input.compact??!1;return{schemaVersion:UPDATE_SCHEMA_VERSION,command:"update",dryRun:!0,...compact?{compact:!0}:{},status:input.status,force:input.force,channel:input.channel,channelChange:input.channel===input.currentChannel?null:{from:input.currentChannel,to:input.channel},source:{kind:input.source.kind,tag:input.source.kind==="release"?input.source.tag:null},version:{installed:input.installed,latest:plan?plan.installedVersion:input.latest,recorded:plan?plan.recordedVersion:null,withheld:plan?plan.versionWithheld:null,pending:plan?plan.pendingSkillsVersion:null},archetypes:[...input.archetypes],plan:plan?planReport(plan,compact):null}}async function runUpdate(opts={}){let compact=opts.compact??!1,json=(opts.json??!1)||compact,dryRun=(opts.dryRun??!1)||json;json||intro(dryRun?"pharn update --dry-run":"pharn update"),runNodePrereq("update",{json});let cwd=process.cwd(),run=()=>updateProject(cwd,{...opts,dryRun,json,compact});if(dryRun){await run();return}try{await withProjectLock(cwd,"update",run)}catch(err){throw err instanceof ProjectLockedError?CliError.refusal(err.message):err}}async function updateProject(cwd,opts){let{dryRun,json,compact}=opts,fingerprint=configFingerprint(cwd),config=loadArchetypeConfig(cwd,{json});warnIfOlderCli(config,{json});let yes=opts.yes??!1;if(!dryRun&&!yes&&!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("pharn update needs to confirm before it writes. Run it in an interactive terminal, or pass --yes to confirm automatically (e.g. `pharn update --yes`).");let channelNotice=defaultChannelNotice(config,opts.ref);channelNotice!==null&&!json&&log2.info(channelNotice);let deprecation=flatDeprecationLines(configLayout(config));deprecation!==null&&!json&&note2(deprecation.join(`
13
+ `),"DEPRECATED"),await runArchetypeUpdate(config,cwd,opts.force??!1,yes,opts.ref??channelOf(config),dryRun,json,compact,fingerprint)}async function runArchetypeUpdate(config,cwd,force,yes,channel,dryRun,json,compact,fingerprint){let proxyNotice=detectProxyNotice(process.env);proxyNotice&&(json?logErrorPlain(proxyNoticeMessage(proxyNotice)):log2.warn(proxyNoticeMessage(proxyNotice)));let s=json?silentSpinner():spinner();s.start("Checking for updates");let latest,source;try{source=await resolveSource(channel),latest=source.kind==="release"?source.version:await fetchRemoteSkillsVersion(),s.stop(`Latest skills v${latest} (${sourceDescription(source)})`)}catch(err){throw s.stop("Failed to check for updates"),CliError.failure(err,{json})}let emitEarlyReturn=status=>{emitJson(buildUpdateReport({status,force,channel,currentChannel:channelOf(config),source,installed:config.skillsVersion,latest,archetypes:config.archetypes??[],plan:null,compact}))},aheadOf=force?null:[config.pendingSkillsVersion,config.skillsVersion].find(held=>held!==void 0&&versionStatus({installed:held,latest}).ahead)??null;if(aheadOf!==null){if(json){emitEarlyReturn(source.kind==="release"?"ahead-of-release":"ahead-of-main");return}let held=aheadOf===config.skillsVersion?`skills v${terminalSafe(config.skillsVersion)}`:`skills v${terminalSafe(config.skillsVersion)}, partly upgraded to v${terminalSafe(aheadOf)}`;outro2(source.kind==="release"?`Your install (${held}) is ahead of the latest verified release (${source.tag}) \u2014 it came from pharn-oss main. Nothing changed. \`pharn update --ref main\` switches back to main; \`pharn update --force\` goes back to ${source.tag}.`:`Your install (${held}) is newer than pharn-oss main (v${latest}) \u2014 main has moved back to an older version. Nothing changed. \`pharn update --force\` downgrades to v${latest}; otherwise wait for main to move forward again.`);return}if(dryRun){await runDryRun(config,cwd,force,channel,source,json,latest,compact);return}let pre=spinner();pre.start(`Planning from ${REPO_URL}`);let repo;try{repo=await fetchRepo(source)}catch(err){throw pre.stop("Update failed"),CliError.failure(err)}let outcome;try{let planned=planFromClone(repo,config,cwd,force,channel,{spin:pre,warn:m=>log2.warn(m),json:!1});if(planned.report.changesNothing)outcome=unchangedOutcome(planned);else{let confirmed=planned.report;printHeader(config,latest,source,force,!1),reportCapabilityChanges(confirmed.capabilityChanges,confirmed.removals,!0),reportRootMigration(confirmed.rootMigration,null),reportExecutableUnit(confirmed.executableUnit,!0),force&&reportForcedOverwrites(confirmed);let deletes=confirmed.removals.filter(r=>r.present).length;if(!yes){let ok=await confirm({message:confirmMessage(force,deletes),initialValue:deletes===0});if(isCancel(ok)||ok!==!0)throw CliError.cancel()}outcome=await applyConfirmed(planned,{config,cwd,channel,repoDir:repo.dir,fingerprint})}}catch(err){throw err instanceof CapabilityRemovalError?CliError.refusal(err.message):CliError.failure(err)}finally{repo.cleanup()}let gitignore=outcome.gitignore===void 0?null:gitignoreLines(outcome.gitignore);gitignore?.warn?log2.warn(gitignore.text):gitignore!==null&&log2.info(gitignore.text);let prettierignore=outcome.prettierignore===void 0?null:prettierignoreLines(outcome.prettierignore);prettierignore?.warn?log2.warn(prettierignore.text):prettierignore!==null&&log2.info(prettierignore.text),reportOutcome(outcome,force)}function printHeader(config,latest,source,force,preview){note2([config.skillsVersion===latest?row("Skills version",`v${terminalSafe(config.skillsVersion)} (re-applying)`):row("Skills version",`v${terminalSafe(config.skillsVersion)} \u2192 v${latest}`),row("Source",sourceDescription(source)),"",row("Archetypes",(config.archetypes??[]).join(", ")||"(none)"),"",force?color_default.dim(` --force: files you changed will be OVERWRITTEN (each is copied to ${BACKUP_DIR}/ first).`):color_default.dim(" Files you have changed are kept, not overwritten \u2014 they are listed at the end."),color_default.dim(" Re-resolves your archetypes against the latest capabilities and re-copies them."),...preview?[color_default.dim(" Preview only \u2014 nothing will be written.")]:[],color_default.dim(" https://github.com/pharn-dev/pharn-oss/blob/main/CHANGELOG.md")].join(`
14
+ `))}function confirmMessage(force,deletes){let base=force?"Apply this update and overwrite your changes?":"Apply this update?";return deletes===0?base:`${base} It deletes ${deletes} capability director${deletes===1?"y":"ies"}.`}var MAX_CHANGED_SHOWN=10;function changedWhileWaiting(changed){let shown=changed.slice(0,MAX_CHANGED_SHOWN).map(rel=>` ${terminalSafe(rel)}`),more=changed.length-shown.length;return[`${changed.length===1?"A file":`${changed.length} files`} changed while \`pharn update\` was waiting for your answer:`,...shown,...more>0?[` \u2026and ${more} more`]:[],"Nothing was written, and your edit is kept. Run `pharn update` again: it plans the file as changed by you and leaves it alone (or, with --force, backs it up first)."].join(`
15
+ `)}async function applyConfirmed(planned,ctx){let{config,cwd,channel,repoDir,fingerprint}=ctx;assertConfigFingerprintUnchanged(cwd,fingerprint,"update");let changed=[...changedSince(cwd,planned.apply.seen,planned.report.writes,planned.apply.expected),...rootDocsChangedSincePlan(cwd,planned.report.rootMigration?.docs??[],planned.apply.records)];if(changed.length>0)throw CliError.refusal(changedWhileWaiting(changed));let s=spinner();s.start("Updating");let backup=null;try{let applied=await applyPlannedUpdate(planned,config,cwd,repoDir,channel,written=>{backup=written,s.stop("Backup written"),reportBackup(written,{aborted:!1}),s=spinner(),s.start("Writing files")});return s.stop(applied.plan.writes.length?"Capabilities updated":"Nothing to write"),applied}catch(err){let refused=err instanceof CliError||err instanceof CapabilityRemovalError;throw s.stop(refused?"Update refused":"Update failed"),refused||backup===null?err:(reportFatal(errorMessage(err),{err}),reportBackup(backup,{aborted:!0}),CliError.reported())}}async function applyPlannedUpdate(planned,config,cwd,repoDir,channel,onBackup){let{report,apply}=planned,{expected,records,plan,models}=apply,removalBackups=removalBackupsNow({cwd,removals:report.removals,records,command:"update"}),backupRels=[...new Set([...report.backups,...removalBackups])],deletes=report.removals.some(r=>r.present),backup=backupRels.length>0?{dir:createBackup(cwd,backupRels),count:backupRels.length,action:backupAction(report.backups.length>0,deletes),gitignored:backupDirIgnored(cwd,report.gitignore)}:null;backup&&onBackup(backup);for(let removal of report.removals)removal.present&&deleteCapabilityDir(cwd,apply.removalPaths,removal.cap);let written,unwritten;try{({written,changed:unwritten}=applyWrites({projectRoot:cwd,expected,writes:plan.writes,seen:apply.seen}))}catch(err){throw err instanceof ApplyError&&err.written.length>0&&records!==null&&await writeRecords(cwd,{skillsVersion:config.skillsVersion,commit:config.commit,files:{...records,...buildRecords(cwd,err.written)}}),err}let migration=report.rootMigration,docResult=migration===null?{deleted:[],kept:[]}:deleteRootDocs(cwd,repoDir,migration.docs,records),retired=new Set(docResult.deleted);await writeRecords(cwd,nextRecordStore(apply,{written:buildRecords(cwd,written),retired,unwritten})),await writePharnConfig(cwd,nextConfig(config,report,apply,channel,{pharnVersion:PHARN_VERSION,updatedAt:new Date().toISOString()}));let gitignore=await applyGitignore(cwd),prettierignore=await applyPrettierignore(cwd,apply.prettierignorePaths);return{installedVersion:report.installedVersion,recordedVersion:report.recordedVersion,capCount:report.capCount,capabilityChanges:report.capabilityChanges,removals:report.removals,plan,backup,recordsNote:report.recordsNote,versionWithheld:report.versionWithheld,abandonedLayout:report.abandonedLayout,featuresReadmeRelocation:report.featuresReadmeRelocation,hookWiring:report.hookWiring,absentUpstream:report.absentUpstream,models,modelsFloor:report.modelsFloor,orphans:report.orphans,gitignore,prettierignore,rootMigration:migration,rootMigrationResult:migration===null?null:docResult}}function unchangedOutcome(planned){let{report,apply}=planned;return{installedVersion:report.installedVersion,recordedVersion:report.recordedVersion,capCount:report.capCount,capabilityChanges:report.capabilityChanges,removals:report.removals,plan:apply.plan,backup:null,recordsNote:report.recordsNote,versionWithheld:report.versionWithheld,abandonedLayout:report.abandonedLayout,featuresReadmeRelocation:report.featuresReadmeRelocation,hookWiring:report.hookWiring,absentUpstream:report.absentUpstream,models:apply.models,modelsFloor:report.modelsFloor,orphans:report.orphans,gitignore:report.gitignore,prettierignore:report.prettierignore,rootMigration:report.rootMigration,rootMigrationResult:report.rootMigration===null?null:{deleted:[],kept:[]},unchanged:!0}}function checkMinCli(repoDir,warn=message=>log2.warn(message)){let gate=minCliGate(repoDir,PHARN_VERSION);return gate.warning&&warn(gate.warning),{refusal:gate.refusal??null}}function silentSpinner(){return{start:()=>{},stop:()=>{}}}function emitJson(report){console.log(serializeJsonReport(report))}function planFromClone(repo,config,cwd,force,channel,ui){let{spin,warn,json}=ui,planned;try{let refusal=checkMinCli(repo.dir,warn).refusal;if(refusal)throw CliError.refusal(refusal,{json});planned=buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel,onUnknownWarning:warn})}catch(err){let removal=err instanceof CapabilityRemovalError;throw spin.stop(removal||err instanceof CliError?"Update refused":"Planning failed"),removal?CliError.refusal(err.message,{json}):CliError.failure(err,{json})}return spin.stop("Plan ready"),planned}async function fetchAndPlan(config,cwd,force,channel,source,ui){ui.spin.start(`Planning from ${REPO_URL}`);let repo;try{repo=await fetchRepo(source)}catch(err){throw ui.spin.stop("Planning failed"),CliError.failure(err,{json:ui.json})}try{return planFromClone(repo,config,cwd,force,channel,ui)}finally{repo.cleanup()}}async function runDryRun(config,cwd,force,channel,source,json,latest,compact){let planned=await fetchAndPlan(config,cwd,force,channel,source,{spin:json?silentSpinner():spinner(),warn:json?message=>logErrorPlain(message):message=>log2.warn(message),json}),{report}=planned;if(json){let empty=report.changesNothing;emitJson(buildUpdateReport({status:empty?"up-to-date":"planned",force,channel,currentChannel:channelOf(config),source,installed:config.skillsVersion,latest,archetypes:config.archetypes??[],plan:empty?null:report,compact}));return}report.changesNothing||printHeader(config,latest,source,force,!0),reportDryRun(report,force,channel,config)}export{runUpdate};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pharn-dev/pharn",
3
- "version": "0.18.5",
3
+ "version": "0.20.0",
4
4
  "description": "Install and update PHARN in any git project. PHARN gets features shipped right with Claude Code, with spec, plan and checks kept in Git.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -52,13 +52,11 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@clack/prompts": "^1.8.1",
55
- "minimist": "^1.2.8",
56
55
  "picocolors": "^1.1.1"
57
56
  },
58
57
  "devDependencies": {
59
58
  "@eslint/js": "^10.0.1",
60
59
  "@pharn-dev/phargus": "^0.2.0",
61
- "@types/minimist": "^1.2.5",
62
60
  "@types/node": "^26.1.1",
63
61
  "@vitest/coverage-v8": "^5.0.5",
64
62
  "esbuild": "^0.28.1",