@pharn-dev/pharn 0.17.0 → 0.18.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.
- package/dist/index.js +8 -7
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -17,7 +17,7 @@ Replace it with a real directory and re-run.`);let stat=lstatSync10(safeJoin(cwd
|
|
|
17
17
|
Move it out of the way and re-run.`);return stat!==void 0};if(check())return!1;try{return mkdirSync3(safeJoin(cwd,LOCK_DIR)),!0}catch(err){if(err.code!=="EEXIST")throw err;return check(),!1}}function removeLockDirIfEmpty(cwd){try{rmdirSync(safeJoin(cwd,LOCK_DIR))}catch{}}function checkLegacyLock(cwd){let legacy=legacySite(cwd),stat;try{stat=lstatSync10(lockPath(legacy),{throwIfNoEntry:!1})}catch{return}if(stat===void 0||stat.isDirectory())return;let observedRaw=readRawAt(lockPath(legacy)),held=observedRaw===null?null:parsePayload(observedRaw);if(!isStale(held,lockAgeMs(legacy)))throw new ProjectLockedError(refusal2(held,legacy));breakStaleLock(legacy,"legacy",observedRaw,!1)}function sayInterrupted(command){try{process.stderr.write(`pharn ${command} was interrupted while writing to this project \u2014 it may be partially updated. Re-run \`pharn ${command}\`.
|
|
18
18
|
`)}catch{}}var HTTPS_VARS=["https_proxy","HTTPS_PROXY"],HTTP_VARS=["http_proxy","HTTP_PROXY"],READ_SPELLINGS=new Set([...HTTPS_VARS,...HTTP_VARS]);function currentProxyRuntime(){return{supportsEnvProxy:process.allowedNodeEnvironmentFlags.has("--use-env-proxy"),execArgv:process.execArgv,nodeVersion:process.versions.node}}var FLAG_RE=/^--(no[-_])?use[-_]env[-_]proxy(?:=.*)?$/;function lastFlag(env,execArgv){let state=null;for(let token of[...(env.NODE_OPTIONS??"").split(/\s+/),...execArgv]){let m=FLAG_RE.exec(token);m&&(state=m[1]===void 0)}return state}function isEarly24(nodeVersion){let[major,minor]=nodeVersion.split(".").map(Number);return major===24&&minor!==void 0&&minor<=4}function envProxyState(env,runtime){if(runtime.supportsEnvProxy){let flag=lastFlag(env,runtime.execArgv);return flag===!1?{envProxy:"available",optedOut:!0}:{envProxy:flag===!0||env.NODE_USE_ENV_PROXY==="1"?"on":"available"}}return isEarly24(runtime.nodeVersion)?{envProxy:isSet(env.NODE_USE_ENV_PROXY)?"on":"available"}:{envProxy:"unsupported"}}function isSet(value){return value!==void 0&&value!==""}function firstPresent(env,names){for(let name of names){let value=env[name];if(value!==void 0)return{name,value}}return null}function readVariable(env){let https=firstPresent(env,HTTPS_VARS);if(https!==null&&https.value!=="")return https;let http=firstPresent(env,HTTP_VARS);return http!==null&&http.value!==""?http:null}function ignoredSpelling(env){let name=Object.keys(env).filter(key3=>!READ_SPELLINGS.has(key3)&&READ_SPELLINGS.has(key3.toLowerCase())&&isSet(env[key3])).sort()[0];return name===void 0?null:{name,value:env[name]}}function detectProxyNotice(env,runtime=currentProxyRuntime()){let read=readVariable(env);if(read!==null)return{...read,...envProxyState(env,runtime)};let ignored=ignoredSpelling(env);return ignored===null?null:{...ignored,envProxy:"ignored-spelling"}}var MAX_RENDERED=120;function redactProxyUrl(value){let url;try{url=new URL(value)}catch{return"(set)"}let auth=url.username!==""||url.password!==""?"***@":"",path=url.pathname==="/"?"":url.pathname,rendered=`${url.protocol}//${auth}${url.host}${path}`;return rendered.length>MAX_RENDERED?`${rendered.slice(0,MAX_RENDERED)}\u2026`:rendered}function proxyNoticeMessage(notice){let shown2=`${notice.name} is set (${redactProxyUrl(notice.value)})`;if(notice.envProxy==="on")return`${shown2} and NODE_USE_ENV_PROXY / --use-env-proxy is on, so pharn's downloads go through that proxy (Node's fetch then also honours NO_PROXY).`;let direct="The download connects DIRECTLY, and fails if direct egress is blocked (LIMITS.md \xA73a).";if(notice.envProxy==="ignored-spelling")return`${shown2}, but pharn will not use it: Node reads only https_proxy, HTTPS_PROXY, http_proxy and HTTP_PROXY, spelled exactly so. ${direct}`;let base=`${shown2}, but pharn will not use it: its network calls go through Node's global fetch, which reads no proxy environment variable by default. ${direct}`;return notice.envProxy==="available"?notice.optedOut?`${base} A --no-use-env-proxy flag (in NODE_OPTIONS or on the command line) turns Node's proxy support off \u2014 remove it to route fetch through the proxy.`:`${base} This Node can route fetch through the proxy \u2014 re-run with NODE_USE_ENV_PROXY=1 set.`:`${base} This Node (${process.version}) cannot route fetch through a proxy; Node 22.21+ and 24+ can, with NODE_USE_ENV_PROXY=1.`}import{closeSync as closeSync7,constants as constants3,fstatSync as fstatSync4,openSync as openSync7,readSync as readSync4}from"node:fs";import{dirname as dirname4}from"node:path";var LOCAL_SETTINGS_FILE=".claude/settings.local.json",MAX_SETTINGS_BYTES=256*1024,PROJECT_OPEN=constants3.O_RDONLY|(constants3.O_NONBLOCK??0),UPSTREAM_OPEN=PROJECT_OPEN|(constants3.O_NOFOLLOW??0);function readSettings(base,rel,followLeaf){let linked;try{linked=findSymlinkComponent(base,followLeaf?dirname4(rel):rel)}catch{return{kind:"unreadable",reason:"a path component is not a directory"}}if(linked!==null)return{kind:"unreadable",reason:`${linked} is a symbolic link`};let fd;try{fd=openSync7(safeJoin(base,rel),followLeaf?PROJECT_OPEN:UPSTREAM_OPEN)}catch(err){let code=err.code;return code==="ENOENT"?{kind:"absent"}:code==="ENOTDIR"?{kind:"unreadable",reason:"a path component is not a directory"}:{kind:"unreadable",reason:"it cannot be opened"}}try{let st=fstatSync4(fd);if(!st.isFile())return{kind:"unreadable",reason:"it is not a regular file"};if(st.size>MAX_SETTINGS_BYTES)return{kind:"unreadable",reason:"it is larger than 256 KB"};let buf=Buffer.alloc(st.size),off=0;for(;off<buf.length;){let n=readSync4(fd,buf,off,buf.length-off,off);if(n===0)break;off+=n}try{return{kind:"ok",value:JSON.parse(buf.subarray(0,off).toString("utf8"))}}catch{return{kind:"unreadable",reason:"it is not valid JSON"}}}catch{return{kind:"unreadable",reason:"it cannot be read"}}finally{closeSync7(fd)}}function hookEntries(settings){if(!isPlainObject(settings)||!isPlainObject(settings.hooks))return null;let out=[];for(let[event,groups]of Object.entries(settings.hooks))if(Array.isArray(groups))for(let group of groups){if(!isPlainObject(group)||!Array.isArray(group.hooks))continue;let matcher=typeof group.matcher=="string"?group.matcher:"";for(let hook of group.hooks){if(!isPlainObject(hook)||typeof hook.command!="string")continue;let args=Array.isArray(hook.args)?hook.args.filter(a=>typeof a=="string"):[];out.push({event,matcher,command:hook.command,args})}}return out}function entryKey(e){return JSON.stringify([e.event,e.matcher,e.command,e.args])}function projectEntries(result){return result.kind==="ok"?hookEntries(result.value)??[]:[]}function entryMentions(e,rels){let mentions=text=>rels.some(rel=>text.includes(rel));return mentions(e.command)||e.args.some(mentions)}var HOOK_SCRIPT_RE=/\.claude\/hooks\/[A-Za-z0-9._-]+/g;function hookScriptRels(e){let out=new Set;for(let text of[e.command,...e.args])for(let m of text.matchAll(HOOK_SCRIPT_RE))out.add(m[0]);return[...out]}function findReplacements(missing,upstreamKeys,project){let out=[];for(let upstream of missing){let rels=hookScriptRels(upstream);if(rels.length===0)continue;let existing=[];for(let{file,entries}of project)for(let entry of entries)entry.event===upstream.event&&entry.matcher===upstream.matcher&&!upstreamKeys.has(entryKey(entry))&&entryMentions(entry,rels)&&existing.push({file,entry});existing.length>0&&out.push({upstream,existing})}return out}function diffHookWiring(repoDir,projectRoot){let upstream=readSettings(repoDir,CLAUDE_SETTINGS_FILE,!1),upstreamEntries=upstream.kind==="ok"?hookEntries(upstream.value):null;if(upstreamEntries===null||upstreamEntries.length===0)return{status:"no-upstream",missing:[]};let shared=readSettings(projectRoot,CLAUDE_SETTINGS_FILE,!0),local=readSettings(projectRoot,LOCAL_SETTINGS_FILE,!0);for(let[file,result]of[[CLAUDE_SETTINGS_FILE,shared],[LOCAL_SETTINGS_FILE,local]])if(result.kind==="unreadable")return{status:"unreadable",missing:upstreamEntries,file,reason:result.reason};if(shared.kind==="absent"&&local.kind==="absent")return{status:"project-absent",missing:upstreamEntries};let sharedEntries=projectEntries(shared),localEntries=projectEntries(local),inShared=new Set(sharedEntries.map(entryKey)),inLocal=new Set(localEntries.map(entryKey)),missing=upstreamEntries.filter(e=>!inShared.has(entryKey(e))&&!inLocal.has(entryKey(e))),localOnly=upstreamEntries.filter(e=>!inShared.has(entryKey(e))&&inLocal.has(entryKey(e)));if(missing.length){let replace=findReplacements(missing,new Set(upstreamEntries.map(entryKey)),[{file:CLAUDE_SETTINGS_FILE,entries:sharedEntries},{file:LOCAL_SETTINGS_FILE,entries:localEntries}]);return replace.length>0?{status:"missing",missing,replace}:{status:"missing",missing}}return localOnly.length?{status:"local-only",missing,localOnly}:{status:"match",missing}}function hooksReferencing(projectRoot,scriptRels){if(scriptRels.length===0)return[];let out=[];for(let file of[CLAUDE_SETTINGS_FILE,LOCAL_SETTINGS_FILE]){let read=readSettings(projectRoot,file,!0);if(read.kind==="absent")continue;if(read.kind==="unreadable"){out.push({file,kind:"unreadable",reason:read.reason});continue}let entries=(hookEntries(read.value)??[]).filter(e=>entryMentions(e,scriptRels));entries.length>0&&out.push({file,kind:"ok",entries})}return out}function hookWiringFails(diff){return diff.status==="missing"||diff.status==="unreadable"||diff.status==="project-absent"}var MAX_LINE=300;function displayHook(e){let hook=e.args.length>0?{type:"command",command:e.command,args:e.args}:{type:"command",command:e.command},where=e.matcher?`${e.event} [${e.matcher}]`:e.event,line=`${escapeUnsafe(where)}: ${escapeUnsafe(JSON.stringify(hook))}`;return line.length>MAX_LINE?`${line.slice(0,MAX_LINE)}\u2026`:line}var FILES=`${CLAUDE_SETTINGS_FILE} or ${LOCAL_SETTINGS_FILE}`;function hookWiringLines(diff){if(diff.status==="match"||diff.status==="no-upstream")return null;if(diff.status==="local-only"){let only=diff.localOnly??[];return[` Every hook upstream wires is wired \u2014 ${only.length} of them only in ${LOCAL_SETTINGS_FILE}.`," They run for you, not for teammates or CI:",...only.map(e=>` ${displayHook(e)}`)]}let replace=diff.status==="missing"?diff.replace??[]:[];return replace.length>0?replaceAndAddLines(diff.missing,replace):[diff.status==="project-absent"?` Neither ${FILES} exists. Upstream wires:`:diff.status==="unreadable"?` ${diff.file??CLAUDE_SETTINGS_FILE} could not be read (${diff.reason??"unknown"}). Upstream wires:`:` Upstream wires ${diff.missing.length} hook(s) that neither ${FILES} does:`,...diff.missing.map(e=>` ${displayHook(e)}`),"",` pharn never writes ${CLAUDE_SETTINGS_FILE} after init \u2014 merge these by hand:`,...FOOTER]}var FOOTER=[" each line is one hook, as JSON, under its event [matcher]. Matching is"," textual: an equivalent hook you wrote differently is listed too."];function replaceAndAddLines(missing,replace){let replaced=new Set(replace.map(r=>r.upstream)),add=missing.filter(e=>!replaced.has(e)),lines=[` Upstream wires ${missing.length} hook(s) that neither ${FILES} does.`,"",` REPLACE \u2014 ${replace.length} of them run a script you already wire under the same`," event [matcher], spelled differently. Replace your line with upstream's;"," adding it beside yours would run the script twice:"];for(let r of replace){for(let{file,entry}of r.existing)lines.push(` yours (${file}): ${displayHook(entry)}`);lines.push(` upstream: ${displayHook(r.upstream)}`)}return add.length>0&&lines.push("",` ADD \u2014 ${add.length} wired in neither file:`,...add.map(e=>` ${displayHook(e)}`)),[...lines,"",` pharn never writes ${CLAUDE_SETTINGS_FILE} after init \u2014 edit these by hand:`,...FOOTER]}function preservedSettingsHookLines(diff){let lines=hookWiringLines(diff);return lines===null?null:hookWiringFails(diff)?[...lines," `pharn status --strict` fails until they are wired."]:lines}function cap(value,max){return value.length>max?`${value.slice(0,max)}\u2026`:value}function serializeJsonReport(report){return JSON.stringify(report,null,2).split(`
|
|
19
19
|
`).map(escapeUnsafe).join(`
|
|
20
|
-
`)}import{copyFileSync,existsSync as existsSync5,lstatSync as lstatSync11,mkdirSync as mkdirSync4}from"node:fs";import{dirname as dirname5}from"node:path";import{log as log3}from"@clack/prompts";var BACKUP_DIR="pharn/.backup",MAX_COLLISION_SUFFIX=100;function backupTimestamp(date){let pad=n=>String(n).padStart(2,"0");return`${date.getFullYear()}${pad(date.getMonth()+1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`}function createBackup(projectRoot,rels,date=new Date){for(let rel of[BACKUP_DIR.split("/")[0],BACKUP_DIR]){let stat=lstatSync11(safeJoin(projectRoot,rel),{throwIfNoEntry:!1});if(stat===void 0)break;if(stat.isSymbolicLink())throw new ManifestValidationError(`${rel} is a symlink; refusing to write backups through it.`);if(!stat.isDirectory())throw new ManifestValidationError(`${rel} is not a directory; refusing to write backups under it.`)}let dirRel=uniqueBackupDir(projectRoot,backupTimestamp(date)),dir=safeJoin(projectRoot,dirRel);mkdirSync4(dir,{recursive:!0});for(let rel of rels){let from=safeJoin(projectRoot,rel),link=findSymlinkComponent(projectRoot,rel);if(link!==null)throw new ManifestValidationError(`Cannot back up ${rel}: ${link} is a symlink.`);if(!lstatSync11(from,{throwIfNoEntry:!1}))throw new ManifestValidationError(`Cannot back up ${rel}: it disappeared before the backup ran.`);let to=safeJoin(dir,rel);mkdirSync4(dirname5(to),{recursive:!0}),copyFileSync(from,to)}return dirRel}function replacedConfigBackup(projectRoot){try{return lstatSync11(safeJoin(projectRoot,PHARN_CONFIG_FILE),{throwIfNoEntry:!1})?.isFile()===!0?[PHARN_CONFIG_FILE]:[]}catch{return[]}}var LEGACY_BACKUP_DIR=".pharn-backup";function legacyBackupNotice(projectRoot){try{let stat=lstatSync11(safeJoin(projectRoot,LEGACY_BACKUP_DIR),{throwIfNoEntry:!1});if(stat===void 0||!stat.isDirectory())return null}catch{return null}return`${LEGACY_BACKUP_DIR}/ holds backups from pharn 0.13.0 or older; new ones go to ${BACKUP_DIR}/. pharn never deletes either \u2014 move what you still need, then delete ${LEGACY_BACKUP_DIR}/.`}function backupAction(overwrites,removals,moves=!1){let parts=[...overwrites?["overwriting"]:[],...removals?["removing"]:[],...moves?["moving"]:[]];return parts.length===0?"overwriting":parts.length===1?parts[0]:`${parts.slice(0,-1).join(", ")} and ${parts.at(-1)}`}function backupNoticeLines(notice,opts={}){let what=typeof notice.saved=="number"?`${notice.saved} file(s)`:notice.saved,before=notice.action===void 0?"":` before ${notice.action}`,lines=[`Backed up ${what} to ${notice.dir}${before}.`];return opts.aborted!==!0&¬ice.gitignored!==!0&&lines.push(`${BACKUP_DIR}/ is not gitignored \u2014 add it to .gitignore or delete it once you are happy.`),lines}function printBackupNotice(notice,opts={}){let output=opts.aborted===!0?process.stderr:process.stdout;for(let line of backupNoticeLines(notice,opts))log3.info(line,{output})}function uniqueBackupDir(projectRoot,timestamp){for(let n=1;n<=MAX_COLLISION_SUFFIX;n+=1){let rel=n===1?`${BACKUP_DIR}/${timestamp}`:`${BACKUP_DIR}/${timestamp}-${n}`;if(!existsSync5(safeJoin(projectRoot,rel)))return rel}throw new ManifestValidationError(`Cannot create a backup directory: ${BACKUP_DIR}/${timestamp} and ${MAX_COLLISION_SUFFIX-1} suffixed variants all exist.`)}import{existsSync as existsSync9}from"node:fs";import{cpSync,existsSync as existsSync6,lstatSync as lstatSync12,mkdirSync as mkdirSync5,readdirSync as readdirSync6}from"node:fs";import{relative}from"node:path";var isTestFile=p=>/\.test\.(mjs|cjs)$/.test(p),inFloorFixtures=(floorFrom,src)=>isFloorTestFixturePath(toPosix(relative(floorFrom,src))),isSymlink=p=>lstatSync12(p).isSymbolicLink(),noSymlinks=src=>!isSymlink(src);function installCapabilityDirs(repoDir,projectRoot,capabilities,paths=layoutPaths(detectLayout(repoDir))){let planned=capabilities.map(cap2=>{assertSafeString(cap2.name,`capability "${cap2.name}"`,CAPABILITY_NAME_RE);let subtree=capabilitySubtree(paths,cap2.role),from=safeJoin(repoDir,`${subtree}/${cap2.name}`);if(!existsSync6(from))throw new ManifestValidationError(`Capability "${cap2.name}" (${cap2.role}) is missing at ${subtree}/${cap2.name} in the fetched repo.`);if(isSymlink(from))throw new ManifestValidationError(`Capability "${cap2.name}" (${cap2.role}) is a symlink at ${subtree}/${cap2.name}; refusing to copy from the untrusted repo.`);return{name:cap2.name,role:cap2.role,subtree,from}}),installed2=[];for(let cap2 of planned){let to=safeJoin(projectRoot,`${cap2.subtree}/${cap2.name}`);cpSync(cap2.from,to,{recursive:!0,force:!0,filter:noSymlinks}),installed2.push({name:cap2.name,role:cap2.role})}return installed2}function prepareInstall(repoDir,projectRoot,capabilities,manifest){let paths=layoutPaths(detectLayout(repoDir)),featuresRel=resolveFeaturesReadme(repoDir,paths.layout),expected=manifest??collectExpectedInstallPaths({repoDir,capabilities,layout:paths.layout});return assertDestinationsInProject(projectRoot,expected),assertDestinationTypes(projectRoot,expected,featuresRel),{paths,featuresRel,manifest:expected}}function installCapabilities(repoDir,projectRoot,selection,manifest){let{paths,featuresRel}=prepareInstall(repoDir,projectRoot,selection.selected,manifest),capabilities=installCapabilityDirs(repoDir,projectRoot,selection.selected,paths);copyFilteredDir(repoDir,projectRoot,CLAUDE_COMMANDS_DIR,isProductCommandFile),copyFilteredDir(repoDir,projectRoot,CLAUDE_HOOKS_DIR,isInstalledHookFile);let settingsFrom=safeJoin(repoDir,CLAUDE_SETTINGS_FILE),settingsTo=safeJoin(projectRoot,CLAUDE_SETTINGS_FILE),settingsPreserved=existsSync6(settingsTo);!settingsPreserved&&existsSync6(settingsFrom)&&!isSymlink(settingsFrom)&&(mkdirSync5(safeJoin(projectRoot,".claude"),{recursive:!0}),cpSync(settingsFrom,settingsTo,{force:!0}));let written=[];for(let doc of resolveTrustedDocs(repoDir,paths.layout)){let from=safeJoin(repoDir,doc);existsSync6(from)&&!isSymlink(from)&&(cpSync(from,safeJoin(projectRoot,doc),{force:!0}),written.push(doc))}let licenseFrom=safeJoin(repoDir,paths.license.from);existsSync6(licenseFrom)&&!isSymlink(licenseFrom)&&cpSync(licenseFrom,safeJoin(projectRoot,paths.license.to),{force:!0});let featuresFrom=safeJoin(repoDir,featuresRel);findSymlinkComponent(repoDir,featuresRel)===null&&existsSync6(featuresFrom)&&!isSymlink(featuresFrom)&&destAcceptsWrite(projectRoot,featuresRel)&&cpSync(featuresFrom,safeJoin(projectRoot,featuresRel),{force:!0});let contractsFrom=safeJoin(repoDir,paths.contracts);existsSync6(contractsFrom)&&!isSymlink(contractsFrom)&&cpSync(contractsFrom,safeJoin(projectRoot,paths.contracts),{recursive:!0,force:!0,filter:noSymlinks});let coreFrom=safeJoin(repoDir,paths.core);existsSync6(coreFrom)&&!isSymlink(coreFrom)&&cpSync(coreFrom,safeJoin(projectRoot,paths.core),{recursive:!0,force:!0,filter:noSymlinks});let floorFrom=safeJoin(repoDir,paths.floor);return existsSync6(floorFrom)&&!isSymlink(floorFrom)&&cpSync(floorFrom,safeJoin(projectRoot,paths.floor),{recursive:!0,force:!0,filter:src=>!isTestFile(src)&&!inFloorFixtures(floorFrom,src)&&noSymlinks(src)}),{capabilities,settingsPreserved,layout:paths.layout,docs:written}}function assertDestinationsInProject(projectRoot,manifest){let dirs=new Set,files=new Set;for(let rel of manifest.keys()){let hit=findSymlinkComponentOr(projectRoot,rel,null);hit!==null&&(hit===rel?files:dirs).add(hit)}let settingsHit=findSymlinkComponentOr(projectRoot,CLAUDE_SETTINGS_FILE,null);if(settingsHit===CLAUDE_SETTINGS_FILE?existsSync6(safeJoin(projectRoot,CLAUDE_SETTINGS_FILE))||files.add(settingsHit):settingsHit!==null&&dirs.add(settingsHit),dirs.size===0&&files.size===0)return;let sentences=[];if(dirs.size>0){let one=dirs.size===1;sentences.push(`${shownList(dirs)} ${one?"is a symbolic link":"are symbolic links"} inside the project, so writing through ${one?"it":"them"} would put files OUTSIDE the project. Replace ${one?"it":"each"} with a real directory (or remove ${one?"it":"them"}).`)}if(files.size>0){let one=files.size===1;sentences.push(`${shownList(files)} ${one?"is a symbolic link":"are symbolic links"} where pharn writes a file, so the install would replace ${one?"it":"them"} with pharn's copy and the link would be lost. Replace ${one?"it":"each"} with a regular file (or remove ${one?"it":"them"}).`),files.has(CLAUDE_SETTINGS_FILE)&&sentences.push(`A link at ${CLAUDE_SETTINGS_FILE} is fine while it points at an existing file \u2014 pharn never writes over an existing one \u2014 but this one points at nothing.`)}throw new ManifestValidationError(`Refusing to install: ${sentences.join(" ")} Nothing was written; re-run \`pharn init\` once that is done.`)}var MAX_LINKED_SHOWN=5;function shownList(items){let shown2=[...items].sort();return shown2.length>MAX_LINKED_SHOWN?`${shown2.slice(0,MAX_LINKED_SHOWN).join(", ")} and ${shown2.length-MAX_LINKED_SHOWN} more`:shown2.join(", ")}function assertDestinationTypes(projectRoot,manifest,featuresRel){let colliding=new Set;for(let rel of manifest.keys()){if(rel===featuresRel)continue;let hit=findTypeCollision(projectRoot,rel);hit!==null&&colliding.add(hit)}for(let rel of[PHARN_CONFIG_FILE,RECORDS_FILE])lstatSync12(safeJoin(projectRoot,rel),{throwIfNoEntry:!1})?.isDirectory()&&colliding.add(rel);if(colliding.size===0)return;let one=colliding.size===1;throw new ManifestValidationError(`Refusing to install: ${shownList(colliding)} ${one?"is in the way":"are in the way"} \u2014 pharn needs a file where you have a directory, or a directory where you have a file. Nothing was written. Move or rename ${one?"it":"them"} and re-run \`pharn init\`.`)}function destAcceptsWrite(projectRoot,rel){try{return findSymlinkComponent(projectRoot,rel)===null&&findTypeCollision(projectRoot,rel)===null}catch{return!1}}function copyFilteredDir(repoDir,projectRoot,relDir,keep2){let fromDir=safeJoin(repoDir,relDir);if(!existsSync6(fromDir))return;let entries=readdirSync6(fromDir,{withFileTypes:!0}),ensured=!1;for(let entry of entries)!entry.isFile()||entry.isSymbolicLink()||keep2(entry.name)&&(assertSafeString(entry.name,`${relDir}/${entry.name}`,COPY_FILENAME_RE),ensured||(mkdirSync5(safeJoin(projectRoot,relDir),{recursive:!0}),ensured=!0),cpSync(safeJoin(fromDir,entry.name),safeJoin(projectRoot,`${relDir}/${entry.name}`),{force:!0}))}import{existsSync as existsSync8}from"node:fs";import{existsSync as existsSync7,rmSync as rmSync3}from"node:fs";function capabilityRelDir(paths,capability){return`${capabilitySubtree(paths,capability.role)}/${capability.name}`}function capabilityDir(cwd,paths,capability){return safeChildJoin(safeJoin(cwd,capabilitySubtree(paths,capability.role)),capability.name)}function linkedComponent(cwd,paths,capability){return findSymlinkComponentOr(cwd,capabilityRelDir(paths,capability),null)}function deleteCapabilityDir(cwd,paths,capability){let dir=capabilityDir(cwd,paths,capability),existed=existsSync7(dir);return existed&&rmSync3(dir,{recursive:!0,force:!0}),existed}import{lstatSync as lstatSync13,readdirSync as readdirSync7}from"node:fs";function removalBackupSet(projectRoot,relDirs,records){let out=new Set;for(let relDir of relDirs)for(let rel of regularFilesAt(projectRoot,relDir))provablyPharns(projectRoot,rel,records)||out.add(rel);return[...out].sort()}function*regularFilesAt(projectRoot,rel){let stat=lstatSync13(safeJoin(projectRoot,rel),{throwIfNoEntry:!1});if(stat!==void 0){if(stat.isFile()){yield rel;return}if(stat.isDirectory())for(let entry of readdirSync7(safeJoin(projectRoot,rel),{withFileTypes:!0})){let child=`${rel}/${entry.name}`;entry.isDirectory()?yield*regularFilesAt(projectRoot,child):entry.isFile()&&(yield child)}}}function provablyPharns(projectRoot,rel,records){return records===null||!Object.hasOwn(records,rel)?!1:contentHash(safeJoin(projectRoot,rel))===records[rel]}var CapabilityRemovalError=class extends Error{constructor(message){super(message),this.name="CapabilityRemovalError"}};function planCapabilityRemovals(params){let{cwd,paths,drops,records,command}=params,removals=[],seen=new Set;for(let{cap:cap2,reason}of drops){let key3=`${cap2.role}:${cap2.name}`;if(seen.has(key3))continue;seen.add(key3);let label=`${cap2.name} (${cap2.role})`,abs=capabilityDir(cwd,paths,cap2),dir=capabilityRelDir(paths,cap2),linked=linkedComponent(cwd,paths,cap2);if(linked!==null)throw new CapabilityRemovalError(`Refusing to ${command}: ${label} is no longer installed, so its directory ${dir} would be deleted \u2014 but ${linked} is a symbolic link, and deleting through it would delete files OUTSIDE the project. Nothing was changed. Delete ${dir} yourself, then run \`pharn ${command}\` again.`);let present,backups;try{present=existsSync8(abs),backups=present?removalBackupSet(cwd,[dir],records):[]}catch(err){throw new CapabilityRemovalError(`Could not check the files in ${label} before removing it: ${errorMessage(err).replace(/\.$/,"")}. Nothing was changed.`)}removals.push({cap:cap2,reason,dir,present,backups})}return removals}function removalBackups(removals){return[...new Set(removals.flatMap(r=>r.backups))]}import{createHash as createHash3}from"node:crypto";import{resolve as resolve5}from"node:path";var SeamConfigError=class extends Error{constructor(message){super(message),this.name="SeamConfigError"}},RESOLUTION_STEPS=["official-skill","pinned-docs","fetch","model","ask"],SEAM_CONFIDENCE_LEVELS=["low","medium","high"],TERMINAL_STEP="ask",DEFAULT_SEAM_CONFIG={resolutionOrder:["official-skill","pinned-docs","model","fetch","ask"],modelConfidenceThreshold:"high",haltOnUnknown:!0},SEAM_KEYS=["resolutionOrder","modelConfidenceThreshold","haltOnUnknown"];function assertNoUnknownKeys(obj,known,label){for(let key3 of Object.keys(obj))if(!known.includes(key3))throw new SeamConfigError(`${label} has unknown key ${JSON.stringify(key3)} (expected one of ${known.join(", ")})`)}function validateSeamConfig(input){if(!isPlainObject(input))throw new SeamConfigError("seam must be an object");assertNoUnknownKeys(input,SEAM_KEYS,"seam");let{resolutionOrder}=input;if(!Array.isArray(resolutionOrder))throw new SeamConfigError(`seam.resolutionOrder must be an array (got ${JSON.stringify(resolutionOrder)})`);for(let i=0;i<resolutionOrder.length;i++){let step=resolutionOrder[i];if(!RESOLUTION_STEPS.includes(step))throw new SeamConfigError(`seam.resolutionOrder[${i}] has invalid step ${JSON.stringify(step)} (expected one of ${RESOLUTION_STEPS.join(", ")})`)}let seen=new Set;for(let step of resolutionOrder){if(seen.has(step))throw new SeamConfigError(`seam.resolutionOrder has duplicate step ${JSON.stringify(step)} (each step may appear at most once)`);seen.add(step)}if(!resolutionOrder.includes(TERMINAL_STEP))throw new SeamConfigError(`seam.resolutionOrder must contain "${TERMINAL_STEP}" \u2014 the terminal fallback cannot be configured away (fail-closed)`);let config={resolutionOrder};if(input.modelConfidenceThreshold!==void 0){let threshold=input.modelConfidenceThreshold;if(typeof threshold!="string"||!SEAM_CONFIDENCE_LEVELS.includes(threshold))throw new SeamConfigError(`seam.modelConfidenceThreshold ${JSON.stringify(threshold)} is invalid (expected one of ${SEAM_CONFIDENCE_LEVELS.join(", ")})`);config.modelConfidenceThreshold=threshold}if(input.modelConfidenceThreshold!==void 0&&!resolutionOrder.includes("model"))throw new SeamConfigError('seam.modelConfidenceThreshold is set but resolutionOrder has no "model" step for it to gate (add "model" or remove the threshold)');if(input.haltOnUnknown!==void 0){if(typeof input.haltOnUnknown!="boolean")throw new SeamConfigError(`seam.haltOnUnknown must be a boolean (got ${JSON.stringify(input.haltOnUnknown)})`);config.haltOnUnknown=input.haltOnUnknown}return config}var CONFIG_FILENAME="pharn.config.json",CAPABILITY_SOURCES=["auto","manual"],CapabilitySourceError=class extends Error{constructor(message){super(message),this.name="CapabilitySourceError"}},CapabilityEntryError=class extends Error{constructor(message){super(message),this.name="CapabilityEntryError"}};function validateCapabilityEntries(raw){if(raw!==void 0){if(!Array.isArray(raw))throw new CapabilityEntryError(`${CONFIG_FILENAME}: capabilities must be an array of {"name", "role"} entries (found ${describeOffender(raw)}). Fix it by hand \u2014 do NOT run \`pharn init\` to clear it: init overwrites this config.`);raw.forEach((entry,i)=>{let at=`${CONFIG_FILENAME}: capabilities[${i}]`;if(!isPlainObject(entry))throw new CapabilityEntryError(`${at} must be an object with "name" and "role" (found ${JSON.stringify(entry)}). Fix it by hand.`);try{assertSafeString(entry.name,`${at}.name`,CAPABILITY_NAME_RE)}catch(err){throw new CapabilityEntryError(`${errorMessage(err)}. A capability name is one lowercase, hyphen-separated segment (e.g. "a11y", "n-plus-one"). Fix it by hand.`)}if(!ROLE_VALUES.some(r=>r===entry.role))throw new CapabilityEntryError(`${at}.role must be ${ROLE_VALUES.map(r=>`"${r}"`).join(" or ")} (found ${JSON.stringify(entry.role)}). Fix it by hand.`)})}}function validateCapabilitySources(raw){Array.isArray(raw)&&raw.forEach((entry,i)=>{if(!isPlainObject(entry)||!("source"in entry))return;let source=entry.source;if(typeof source!="string"||!CAPABILITY_SOURCES.includes(source))throw new CapabilitySourceError(`${CONFIG_FILENAME}: capabilities[${i}].source must be ${CAPABILITY_SOURCES.map(s=>`"${s}"`).join(" or ")} (found ${JSON.stringify(source)}). Fix it by hand, or delete the field \u2014 an absent \`source\` is valid and the next \`pharn update\` will set it.`)})}var ArchetypesError=class extends Error{constructor(message){super(message),this.name="ArchetypesError"}};function describeOffender(value){return terminalSafe(escapeUnsafe(JSON.stringify(value)??String(value)),{max:80})}function validateArchetypes(raw){if(raw===void 0)return;let allowed=ARCHETYPE_VALUES.map(a=>`"${a}"`).join(", ");if(!Array.isArray(raw))throw new ArchetypesError(`${CONFIG_FILENAME}: archetypes must be an array of ${allowed} (found ${describeOffender(raw)}). Fix it by hand (e.g. ["ssr"]).`);raw.forEach((entry,i)=>{if(!ARCHETYPE_VALUES.some(a=>a===entry))throw new ArchetypesError(`${CONFIG_FILENAME}: archetypes[${i}] must be one of ${allowed} (found ${describeOffender(entry)}). Fix it by hand.`)})}var ConfigStampError=class extends Error{constructor(message){super(message),this.name="ConfigStampError"}};function validateStamp(raw){let where="Fix it by hand \u2014 `pharn.records.json`, if present, carries the same stamp.";if(typeof raw.skillsVersion=="string"&&!VERSION_RE.test(raw.skillsVersion))throw new ConfigStampError(`${CONFIG_FILENAME}: skillsVersion must be a version like "1.2.3" (found ${describeOffender(raw.skillsVersion)}). ${where}`);if(raw.commit!==void 0&&raw.commit!==null&&(typeof raw.commit!="string"||!COMMIT_RE.test(raw.commit)))throw new ConfigStampError(`${CONFIG_FILENAME}: commit must be a full 40-character lowercase hex commit SHA, or null (found ${describeOffender(raw.commit)}). ${where}`)}var ConfigParseError=class extends Error{constructor(message){super(message),this.name="ConfigParseError"}};function parseLocation(err){let at=/\(line (\d{1,9}) column (\d{1,9})\)$/.exec(errorMessage(err));return at?` (line ${at[1]}, column ${at[2]})`:""}var CONTROL_CHARS_GLOBAL_RE=new RegExp(CONTROL_CHARS_RE.source,"g");function displayPath(path){return path.replace(CONTROL_CHARS_GLOBAL_RE,c=>`\\x${c.charCodeAt(0).toString(16).padStart(2,"0")}`)}function configPath(cwd){return resolve5(cwd,CONFIG_FILENAME)}var CLI_OWNED_KEYS=new Set(Object.keys({pharnVersion:!0,skillsVersion:!0,pendingSkillsVersion:!0,frozenCapabilities:!0,repo:!0,commit:!0,ref:!0,constitution:!0,isMultiTenant:!0,modules:!0,installedAt:!0,updatedAt:!0,models:!0,seam:!0,stackAnswers:!0,installedSkills:!0,archetypes:!0,capabilities:!0,layout:!0}));function userOwnedConfigEntries(raw){return Object.fromEntries(Object.entries(raw).filter(([key3])=>!CLI_OWNED_KEYS.has(key3)))}function readPharnConfig(cwd){let path=configPath(cwd),read=readJsonBounded(path);if(read.kind==="absent"||read.kind==="unusable")return null;if(read.kind==="invalid-json")throw new ConfigParseError(`${displayPath(path)} is not valid JSON${parseLocation(read.error)}. The file exists \u2014 fix its syntax by hand. Do NOT run \`pharn init\` to clear it: init OVERWRITES this config, discarding your recorded capabilities, any manual \`pharn add\` provenance, and hand-edited models/seam blocks. If it is beyond repair, move it aside first (\`mv ${CONFIG_FILENAME} ${CONFIG_FILENAME}.bak\`), then run \`pharn init\`.`);let raw=read.value;if(!isPlainObject(raw)||typeof raw.skillsVersion!="string"||!Array.isArray(raw.modules))return null;let seam=raw.seam!==void 0?validateSeamConfig(raw.seam):void 0;validateCapabilityEntries(raw.capabilities),validateCapabilitySources(raw.capabilities),Array.isArray(raw.capabilities)&&(validateArchetypes(raw.archetypes),validateStamp(raw));let config={...raw,...seam!==void 0?{seam}:{}};return config.layout!=="pharn"&&config.layout!=="flat"&&delete config.layout,config.ref!==void 0&&config.ref!=="latest"&&delete config.ref,config.pendingSkillsVersion!==void 0&&(typeof config.pendingSkillsVersion!="string"||!VERSION_RE.test(config.pendingSkillsVersion))&&delete config.pendingSkillsVersion,config.frozenCapabilities!==void 0&&!isFrozenKeyList(config.frozenCapabilities)&&delete config.frozenCapabilities,config}function isFrozenKeyList(value){return Array.isArray(value)&&value.every(key3=>{if(typeof key3!="string")return!1;let sep2=key3.indexOf(":");if(sep2===-1)return!1;let role=key3.slice(0,sep2),name=key3.slice(sep2+1);return ROLE_VALUES.some(r=>r===role)&&CAPABILITY_NAME_RE.test(name)})}function loadConfigOrExit(cwd,opts={}){let fail2=message=>{reportLoadError(message,opts.json??!1),process.exit(1)};try{let config=readPharnConfig(cwd);if(config)return config}catch(err){throw isConfigValidationError(err)&&fail2(err.message),err}return fail2("No pharn.config.json found. Run `pharn init` first.")}function reportLoadError(message,json){json?logErrorPlain(message):logError(message)}function assertConfigUnchanged(cwd,snapshot,command){let current;try{current=readPharnConfig(cwd)}catch{current=null}if(!(current!==null&&JSON.stringify(current)===JSON.stringify(snapshot)))throw configChangedError(command)}function configChangedError(command){return new ProjectChangedError(`${CONFIG_FILENAME} changed while \`pharn ${command}\` was running \u2014 another pharn process (or an edit) wrote it after this command read it. Nothing was written. Re-run \`pharn ${command}\` to act on the current state.`)}function configFingerprint(cwd){let read=readBoundedFile(configPath(cwd));return read.kind==="absent"?"absent":read.kind==="unusable"?`unreadable:${read.code}`:`sha256:${createHash3("sha256").update(read.bytes).digest("hex")}`}function assertConfigFingerprintUnchanged(cwd,fingerprint,command){if(configFingerprint(cwd)!==fingerprint)throw configChangedError(command)}function isConfigValidationError(err){return err instanceof ConfigParseError||err instanceof SeamConfigError||err instanceof CapabilityEntryError||err instanceof CapabilitySourceError||err instanceof ArchetypesError||err instanceof ConfigStampError}async function writePharnConfig(cwd,config){await writeJsonAtomic(configPath(cwd),config)}function isArchetypeConfig(config){return Array.isArray(config.capabilities)}var LEGACY_CONFIG_MESSAGE="This project uses the legacy module layout (pre-archetype), which is no longer supported. Re-run `pharn init` to reinstall with the archetype/capability model.";function loadArchetypeConfigOrExit(cwd,opts={}){let config=loadConfigOrExit(cwd,opts);return isArchetypeConfig(config)||(reportLoadError(LEGACY_CONFIG_MESSAGE,opts.json??!1),process.exit(1)),config}function resolveCapabilities(archetypes,index){let detected=new Set(archetypes),selected=[],skipped=[];for(let entry of index.capabilities){if(entry.applies==="universal"){selected.push({name:entry.name,role:entry.role,matched:"universal"});continue}let matched=entry.applies.filter(a=>detected.has(a));matched.length>0?selected.push({name:entry.name,role:entry.role,matched}):skipped.push({name:entry.name,role:entry.role,reason:`applies to [${entry.applies.join(", ")}]; detected [${archetypes.join(", ")}]`})}return{selected,skipped}}var PRODUCT_STAGES=["spec","plan","grill","build","regress","verify","ship","loop","review","memory-promote","ac-test"],MODEL_ALIASES=["sonnet","opus","haiku","fable","inherit"],MODEL_ID_RE=/^claude-[a-z0-9][a-z0-9-]*$/,EFFORT_LEVELS=["low","medium","high","xhigh","max"];function isValidModel(model){return typeof model=="string"&&(MODEL_ALIASES.includes(model)||MODEL_ID_RE.test(model))}function isValidEffort(effort){return typeof effort=="string"&&EFFORT_LEVELS.includes(effort)}function checkModelsBlock(models){if(models==null)return{kind:"no-stages"};if(!isPlainObject(models))return invalid("shape","`models` is present but is not an object");let stages=models.stages;if(stages==null)return{kind:"no-stages"};if(!isPlainObject(stages))return invalid("shape","`models.stages` is present but is not an object");let reds=[];Object.hasOwn(stages,"default")||reds.push({kind:"default",detail:"missing required `default` stage entry (the resolution fallback)"});for(let[name,entry]of Object.entries(stages)){let stage=`stage ${JSON.stringify(name)}`;if(name!=="default"&&!PRODUCT_STAGES.includes(name)){reds.push({kind:"stage",detail:`${stage} is not a product stage \u2014 expected one of {${PRODUCT_STAGES.join(", ")}} or "default"`});continue}if(!isPlainObject(entry)){reds.push({kind:"entry",detail:`${stage} is not an object with {model, effort}`});continue}Object.hasOwn(entry,"model")?isValidModel(entry.model)||reds.push({kind:"model",detail:`${stage} model ${JSON.stringify(entry.model)} is not an alias {${MODEL_ALIASES.join(", ")}} nor a claude-* id`}):reds.push({kind:"model",detail:`${stage} missing \`model\``}),Object.hasOwn(entry,"effort")?isValidEffort(entry.effort)||reds.push({kind:"effort",detail:`${stage} effort ${JSON.stringify(entry.effort)} not in {${EFFORT_LEVELS.join(", ")}}`}):reds.push({kind:"effort",detail:`${stage} missing \`effort\``})}return reds.length>0?{kind:"invalid",reds}:{kind:"valid",stages}}function invalid(kind,detail){return{kind:"invalid",reds:[{kind,detail}]}}function resolveStageModel(stages,stage){let entry=Object.hasOwn(stages,stage)?stages[stage]:stages.default,{model,effort}=entry;return{model,effort}}var UPSTREAM_CONFIG_FILE="pharn.config.json",MAX_UPSTREAM_CONFIG_BYTES=1024*1024;function readUpstreamModels(repoDir){let read=readJsonBounded(safeJoin(repoDir,UPSTREAM_CONFIG_FILE),MAX_UPSTREAM_CONFIG_BYTES);if(read.kind==="absent")return{kind:"absent"};if(read.kind==="unusable")return{kind:"invalid",reasons:[`pharn-oss's ${UPSTREAM_CONFIG_FILE} ${read.reason}`]};if(read.kind==="invalid-json")return{kind:"invalid",reasons:[`pharn-oss's ${UPSTREAM_CONFIG_FILE} is not valid JSON`]};let config=read.value;if(!isPlainObject(config))return{kind:"invalid",reasons:[`pharn-oss's ${UPSTREAM_CONFIG_FILE} is valid JSON but is not an object`]};let block=config.models;if(block==null)return{kind:"absent"};let check=checkModelsBlock(block);if(check.kind==="invalid")return{kind:"invalid",reasons:check.reds.map(red=>red.detail)};try{JSON.stringify(block)}catch{return{kind:"invalid",reasons:["pharn-oss's models block is nested too deeply to copy"]}}return{kind:"ok",block}}function versionStatus(input){let ahead=compareVersionCore(input.installed,input.latest)===1,outdated=!ahead&&input.installed!==input.latest;return{ahead,outdated}}import{lstatSync as lstatSync14}from"node:fs";import{relative as relative2}from"node:path";function decideFileAction(input){let{diskHash,latestHash,recordedHash,recordsAvailable,force}=input;return diskHash===null?{action:"write",label:"restored",backup:!1,refreshRecord:!0,forced:!1}:diskHash===latestHash?{action:"noop",label:"ok",backup:!1,refreshRecord:!0,forced:!1}:recordsAvailable?recordedHash===null?skipOrForce("unrecorded",force):diskHash===recordedHash?{action:"write",label:"updated",backup:!1,refreshRecord:!0,forced:!1}:skipOrForce("modified",force):skipOrForce("unverifiable",force)}function skipOrForce(label,force){return force?{action:"write",label,backup:!0,refreshRecord:!0,forced:!0}:{action:"skip",label,backup:!1,refreshRecord:!1,forced:!1}}var SKIP_ORDER=["modified","unrecorded","unverifiable","unreadable"];function planUpdate(params){let{latestHashes,diskStates,records,force}=params,files=[],writes=[],backups=[],nextRecords={},groups=new Map,counts={updated:0,restored:0,ok:0,forced:0,skipped:0};for(let[rel,latestHash]of latestHashes){let disk=diskStates.get(rel)??{kind:"absent"},previous=records?.[rel];if(disk.kind==="unreadable"){files.push({rel,action:"skip",label:"unreadable",backup:!1,forced:!1}),pushGroup(groups,"unreadable",rel),counts.skipped+=1,previous!==void 0&&(nextRecords[rel]=previous);continue}let decision=decideFileAction({diskHash:disk.kind==="file"?disk.hash:null,latestHash,recordedHash:previous??null,recordsAvailable:records!==null,force});files.push({rel,action:decision.action,label:decision.label,backup:decision.backup,forced:decision.forced}),decision.action==="write"?(writes.push(rel),decision.backup&&backups.push(rel),decision.forced?counts.forced+=1:decision.label==="restored"?counts.restored+=1:counts.updated+=1):decision.action==="noop"?counts.ok+=1:(pushGroup(groups,decision.label,rel),counts.skipped+=1),decision.refreshRecord?nextRecords[rel]=latestHash:previous!==void 0&&(nextRecords[rel]=previous)}let skipped=SKIP_ORDER.filter(label=>groups.has(label)).map(label=>({label,rels:groups.get(label).slice().sort()}));return{files,writes,backups,skipped,counts,nextRecords}}function pushGroup(groups,label,rel){let existing=groups.get(label);existing?existing.push(rel):groups.set(label,[rel])}function scanDest(params){let{repoDir,projectRoot,rels,sources}=params,records=params.records??null,drifted=[],labels=new Map,unsafe=[];for(let rel of rels){let srcRel=sources?.get(rel)??rel,dest=safeJoin(projectRoot,rel),src=safeJoin(repoDir,srcRel),destLink=findSymlinkComponentOr(projectRoot,rel,UNREADABLE);if(destLink===UNREADABLE)continue;if(destLink!==null){unsafe.push({rel,link:destLink});continue}if(!lstatSync14(dest,{throwIfNoEntry:!1})?.isFile()||findSymlinkComponentOr(repoDir,srcRel,UNREADABLE)!==null||!lstatSync14(src,{throwIfNoEntry:!1})?.isFile())continue;let label=driftLabel(decideFileAction({diskHash:contentHash(dest),latestHash:contentHash(src),recordedHash:records!==null&&Object.hasOwn(records,rel)?records[rel]??null:null,recordsAvailable:records!==null,force:!0}));label!==null&&(drifted.push(rel),labels.set(rel,label))}return{drifted:drifted.sort(),labels,unsafe:unsafe.sort((a,b)=>a.rel<b.rel?-1:a.rel>b.rel?1:0)}}function manifestSources(repoDir,manifest){let sources=new Map;for(let[dest,from]of manifest)sources.set(dest,toPosix(relative2(repoDir,from)));return sources}function driftLabel(decision){if(!decision.backup)return null;let{label}=decision;return label==="modified"||label==="unrecorded"?label:"unverifiable"}var UNREADABLE=Symbol("unreadable");var MAX_LISTED2=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}=scanDest({repoDir,projectRoot,rels:conflicts.filter(p=>manifest.has(p)),sources:manifestSources(repoDir,manifest),records}),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,shown2=max===void 0?paths:paths.slice(0,max),lines=shown2.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-shown2.length;return more>0&&lines.push(` \u2026and ${more} more`),lines}var OverwriteRefusedError=class extends Error{constructor(message){super(message),this.name="OverwriteRefusedError"}};function assertNoExistingTargets(params){let plan=planWriteTargets(params),deletes=removalLines(plan.removals);if(deletes.length>0)throw new OverwriteRefusedError([`pharn init --yes never deletes, and this install would delete ${deletes.length} capability director${deletes.length===1?"y":"ies"} it drops from pharn.config.json:`,...deletes,"Run `pharn init` in a terminal to review and confirm, `pharn init --dry-run` to see the whole plan, or `pharn update` to refresh an existing install."].join(`
|
|
20
|
+
`)}import{copyFileSync,existsSync as existsSync5,lstatSync as lstatSync11,mkdirSync as mkdirSync4}from"node:fs";import{dirname as dirname5}from"node:path";import{log as log3}from"@clack/prompts";var BACKUP_DIR="pharn/.backup",MAX_COLLISION_SUFFIX=100;function backupTimestamp(date){let pad=n=>String(n).padStart(2,"0");return`${date.getFullYear()}${pad(date.getMonth()+1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`}function createBackup(projectRoot,rels,date=new Date){for(let rel of[BACKUP_DIR.split("/")[0],BACKUP_DIR]){let stat=lstatSync11(safeJoin(projectRoot,rel),{throwIfNoEntry:!1});if(stat===void 0)break;if(stat.isSymbolicLink())throw new ManifestValidationError(`${rel} is a symlink; refusing to write backups through it.`);if(!stat.isDirectory())throw new ManifestValidationError(`${rel} is not a directory; refusing to write backups under it.`)}let dirRel=uniqueBackupDir(projectRoot,backupTimestamp(date)),dir=safeJoin(projectRoot,dirRel);mkdirSync4(dir,{recursive:!0});for(let rel of rels){let from=safeJoin(projectRoot,rel),link=findSymlinkComponent(projectRoot,rel);if(link!==null)throw new ManifestValidationError(`Cannot back up ${rel}: ${link} is a symlink.`);if(!lstatSync11(from,{throwIfNoEntry:!1}))throw new ManifestValidationError(`Cannot back up ${rel}: it disappeared before the backup ran.`);let to=safeJoin(dir,rel);mkdirSync4(dirname5(to),{recursive:!0}),copyFileSync(from,to)}return dirRel}function replacedConfigBackup(projectRoot){try{return lstatSync11(safeJoin(projectRoot,PHARN_CONFIG_FILE),{throwIfNoEntry:!1})?.isFile()===!0?[PHARN_CONFIG_FILE]:[]}catch{return[]}}var LEGACY_BACKUP_DIR=".pharn-backup";function legacyBackupNotice(projectRoot){try{let stat=lstatSync11(safeJoin(projectRoot,LEGACY_BACKUP_DIR),{throwIfNoEntry:!1});if(stat===void 0||!stat.isDirectory())return null}catch{return null}return`${LEGACY_BACKUP_DIR}/ holds backups from pharn 0.13.0 or older; new ones go to ${BACKUP_DIR}/. pharn never deletes either \u2014 move what you still need, then delete ${LEGACY_BACKUP_DIR}/.`}function backupAction(overwrites,removals,moves=!1){let parts=[...overwrites?["overwriting"]:[],...removals?["removing"]:[],...moves?["moving"]:[]];return parts.length===0?"overwriting":parts.length===1?parts[0]:`${parts.slice(0,-1).join(", ")} and ${parts.at(-1)}`}function backupNoticeLines(notice,opts={}){let what=typeof notice.saved=="number"?`${notice.saved} file(s)`:notice.saved,before=notice.action===void 0?"":` before ${notice.action}`,lines=[`Backed up ${what} to ${notice.dir}${before}.`];return opts.aborted!==!0&¬ice.gitignored!==!0&&lines.push(`${BACKUP_DIR}/ is not gitignored \u2014 add it to .gitignore or delete it once you are happy.`),lines}function printBackupNotice(notice,opts={}){let output=opts.aborted===!0?process.stderr:process.stdout;for(let line of backupNoticeLines(notice,opts))log3.info(line,{output})}function uniqueBackupDir(projectRoot,timestamp){for(let n=1;n<=MAX_COLLISION_SUFFIX;n+=1){let rel=n===1?`${BACKUP_DIR}/${timestamp}`:`${BACKUP_DIR}/${timestamp}-${n}`;if(!existsSync5(safeJoin(projectRoot,rel)))return rel}throw new ManifestValidationError(`Cannot create a backup directory: ${BACKUP_DIR}/${timestamp} and ${MAX_COLLISION_SUFFIX-1} suffixed variants all exist.`)}import{existsSync as existsSync9}from"node:fs";import{cpSync,existsSync as existsSync6,lstatSync as lstatSync12,mkdirSync as mkdirSync5,readdirSync as readdirSync6}from"node:fs";import{relative}from"node:path";var isTestFile=p=>/\.test\.(mjs|cjs)$/.test(p),inFloorFixtures=(floorFrom,src)=>isFloorTestFixturePath(toPosix(relative(floorFrom,src))),isSymlink=p=>lstatSync12(p).isSymbolicLink(),noSymlinks=src=>!isSymlink(src);function installCapabilityDirs(repoDir,projectRoot,capabilities,paths=layoutPaths(detectLayout(repoDir))){let planned=capabilities.map(cap2=>{assertSafeString(cap2.name,`capability "${cap2.name}"`,CAPABILITY_NAME_RE);let subtree=capabilitySubtree(paths,cap2.role),from=safeJoin(repoDir,`${subtree}/${cap2.name}`);if(!existsSync6(from))throw new ManifestValidationError(`Capability "${cap2.name}" (${cap2.role}) is missing at ${subtree}/${cap2.name} in the fetched repo.`);if(isSymlink(from))throw new ManifestValidationError(`Capability "${cap2.name}" (${cap2.role}) is a symlink at ${subtree}/${cap2.name}; refusing to copy from the untrusted repo.`);return{name:cap2.name,role:cap2.role,subtree,from}}),installed2=[];for(let cap2 of planned){let to=safeJoin(projectRoot,`${cap2.subtree}/${cap2.name}`);cpSync(cap2.from,to,{recursive:!0,force:!0,filter:noSymlinks}),installed2.push({name:cap2.name,role:cap2.role})}return installed2}function prepareInstall(repoDir,projectRoot,capabilities,manifest){let paths=layoutPaths(detectLayout(repoDir)),featuresRel=resolveFeaturesReadme(repoDir,paths.layout),expected=manifest??collectExpectedInstallPaths({repoDir,capabilities,layout:paths.layout});return assertDestinationsInProject(projectRoot,expected),assertDestinationTypes(projectRoot,expected,featuresRel),{paths,featuresRel,manifest:expected}}function installCapabilities(repoDir,projectRoot,selection,manifest){let{paths,featuresRel}=prepareInstall(repoDir,projectRoot,selection.selected,manifest),capabilities=installCapabilityDirs(repoDir,projectRoot,selection.selected,paths);copyFilteredDir(repoDir,projectRoot,CLAUDE_COMMANDS_DIR,isProductCommandFile),copyFilteredDir(repoDir,projectRoot,CLAUDE_HOOKS_DIR,isInstalledHookFile);let settingsFrom=safeJoin(repoDir,CLAUDE_SETTINGS_FILE),settingsTo=safeJoin(projectRoot,CLAUDE_SETTINGS_FILE),settingsPreserved=existsSync6(settingsTo);!settingsPreserved&&existsSync6(settingsFrom)&&!isSymlink(settingsFrom)&&(mkdirSync5(safeJoin(projectRoot,".claude"),{recursive:!0}),cpSync(settingsFrom,settingsTo,{force:!0}));let written=[];for(let doc of resolveTrustedDocs(repoDir,paths.layout)){let from=safeJoin(repoDir,doc);existsSync6(from)&&!isSymlink(from)&&(cpSync(from,safeJoin(projectRoot,doc),{force:!0}),written.push(doc))}let licenseFrom=safeJoin(repoDir,paths.license.from);existsSync6(licenseFrom)&&!isSymlink(licenseFrom)&&cpSync(licenseFrom,safeJoin(projectRoot,paths.license.to),{force:!0});let featuresFrom=safeJoin(repoDir,featuresRel);findSymlinkComponent(repoDir,featuresRel)===null&&existsSync6(featuresFrom)&&!isSymlink(featuresFrom)&&destAcceptsWrite(projectRoot,featuresRel)&&cpSync(featuresFrom,safeJoin(projectRoot,featuresRel),{force:!0});let contractsFrom=safeJoin(repoDir,paths.contracts);existsSync6(contractsFrom)&&!isSymlink(contractsFrom)&&cpSync(contractsFrom,safeJoin(projectRoot,paths.contracts),{recursive:!0,force:!0,filter:noSymlinks});let coreFrom=safeJoin(repoDir,paths.core);existsSync6(coreFrom)&&!isSymlink(coreFrom)&&cpSync(coreFrom,safeJoin(projectRoot,paths.core),{recursive:!0,force:!0,filter:noSymlinks});let floorFrom=safeJoin(repoDir,paths.floor);return existsSync6(floorFrom)&&!isSymlink(floorFrom)&&cpSync(floorFrom,safeJoin(projectRoot,paths.floor),{recursive:!0,force:!0,filter:src=>!isTestFile(src)&&!inFloorFixtures(floorFrom,src)&&noSymlinks(src)}),{capabilities,settingsPreserved,layout:paths.layout,docs:written}}function assertDestinationsInProject(projectRoot,manifest){let dirs=new Set,files=new Set;for(let rel of manifest.keys()){let hit=findSymlinkComponentOr(projectRoot,rel,null);hit!==null&&(hit===rel?files:dirs).add(hit)}let settingsHit=findSymlinkComponentOr(projectRoot,CLAUDE_SETTINGS_FILE,null);if(settingsHit===CLAUDE_SETTINGS_FILE?existsSync6(safeJoin(projectRoot,CLAUDE_SETTINGS_FILE))||files.add(settingsHit):settingsHit!==null&&dirs.add(settingsHit),dirs.size===0&&files.size===0)return;let sentences=[];if(dirs.size>0){let one=dirs.size===1;sentences.push(`${shownList(dirs)} ${one?"is a symbolic link":"are symbolic links"} inside the project, so writing through ${one?"it":"them"} would put files OUTSIDE the project. Replace ${one?"it":"each"} with a real directory (or remove ${one?"it":"them"}).`)}if(files.size>0){let one=files.size===1;sentences.push(`${shownList(files)} ${one?"is a symbolic link":"are symbolic links"} where pharn writes a file, so the install would replace ${one?"it":"them"} with pharn's copy and the link would be lost. Replace ${one?"it":"each"} with a regular file (or remove ${one?"it":"them"}).`),files.has(CLAUDE_SETTINGS_FILE)&&sentences.push(`A link at ${CLAUDE_SETTINGS_FILE} is fine while it points at an existing file \u2014 pharn never writes over an existing one \u2014 but this one points at nothing.`)}throw new ManifestValidationError(`Refusing to install: ${sentences.join(" ")} Nothing was written; re-run \`pharn init\` once that is done.`)}var MAX_LINKED_SHOWN=5;function shownList(items){let shown2=[...items].sort();return shown2.length>MAX_LINKED_SHOWN?`${shown2.slice(0,MAX_LINKED_SHOWN).join(", ")} and ${shown2.length-MAX_LINKED_SHOWN} more`:shown2.join(", ")}function assertDestinationTypes(projectRoot,manifest,featuresRel){let colliding=new Set;for(let rel of manifest.keys()){if(rel===featuresRel)continue;let hit=findTypeCollision(projectRoot,rel);hit!==null&&colliding.add(hit)}for(let rel of[PHARN_CONFIG_FILE,RECORDS_FILE])lstatSync12(safeJoin(projectRoot,rel),{throwIfNoEntry:!1})?.isDirectory()&&colliding.add(rel);if(colliding.size===0)return;let one=colliding.size===1;throw new ManifestValidationError(`Refusing to install: ${shownList(colliding)} ${one?"is in the way":"are in the way"} \u2014 pharn needs a file where you have a directory, or a directory where you have a file. Nothing was written. Move or rename ${one?"it":"them"} and re-run \`pharn init\`.`)}function destAcceptsWrite(projectRoot,rel){try{return findSymlinkComponent(projectRoot,rel)===null&&findTypeCollision(projectRoot,rel)===null}catch{return!1}}function copyFilteredDir(repoDir,projectRoot,relDir,keep2){let fromDir=safeJoin(repoDir,relDir);if(!existsSync6(fromDir))return;let entries=readdirSync6(fromDir,{withFileTypes:!0}),ensured=!1;for(let entry of entries)!entry.isFile()||entry.isSymbolicLink()||keep2(entry.name)&&(assertSafeString(entry.name,`${relDir}/${entry.name}`,COPY_FILENAME_RE),ensured||(mkdirSync5(safeJoin(projectRoot,relDir),{recursive:!0}),ensured=!0),cpSync(safeJoin(fromDir,entry.name),safeJoin(projectRoot,`${relDir}/${entry.name}`),{force:!0}))}import{existsSync as existsSync8}from"node:fs";import{existsSync as existsSync7,rmSync as rmSync3}from"node:fs";function capabilityRelDir(paths,capability){return`${capabilitySubtree(paths,capability.role)}/${capability.name}`}function capabilityDir(cwd,paths,capability){return safeChildJoin(safeJoin(cwd,capabilitySubtree(paths,capability.role)),capability.name)}function linkedComponent(cwd,paths,capability){return findSymlinkComponentOr(cwd,capabilityRelDir(paths,capability),null)}function deleteCapabilityDir(cwd,paths,capability){let dir=capabilityDir(cwd,paths,capability),existed=existsSync7(dir);return existed&&rmSync3(dir,{recursive:!0,force:!0}),existed}import{lstatSync as lstatSync13,readdirSync as readdirSync7}from"node:fs";function removalBackupSet(projectRoot,relDirs,records){let out=new Set;for(let relDir of relDirs)for(let rel of regularFilesAt(projectRoot,relDir))provablyPharns(projectRoot,rel,records)||out.add(rel);return[...out].sort()}function*regularFilesAt(projectRoot,rel){let stat=lstatSync13(safeJoin(projectRoot,rel),{throwIfNoEntry:!1});if(stat!==void 0){if(stat.isFile()){yield rel;return}if(stat.isDirectory())for(let entry of readdirSync7(safeJoin(projectRoot,rel),{withFileTypes:!0})){let child=`${rel}/${entry.name}`;entry.isDirectory()?yield*regularFilesAt(projectRoot,child):entry.isFile()&&(yield child)}}}function provablyPharns(projectRoot,rel,records){return records===null||!Object.hasOwn(records,rel)?!1:contentHash(safeJoin(projectRoot,rel))===records[rel]}var CapabilityRemovalError=class extends Error{constructor(message){super(message),this.name="CapabilityRemovalError"}};function planCapabilityRemovals(params){let{cwd,paths,drops,records,command}=params,removals=[],seen=new Set;for(let{cap:cap2,reason}of drops){let key3=`${cap2.role}:${cap2.name}`;if(seen.has(key3))continue;seen.add(key3);let label=`${cap2.name} (${cap2.role})`,abs=capabilityDir(cwd,paths,cap2),dir=capabilityRelDir(paths,cap2),linked=linkedComponent(cwd,paths,cap2);if(linked!==null)throw new CapabilityRemovalError(`Refusing to ${command}: ${label} is no longer installed, so its directory ${dir} would be deleted \u2014 but ${linked} is a symbolic link, and deleting through it would delete files OUTSIDE the project. Nothing was changed. Delete ${dir} yourself, then run \`pharn ${command}\` again.`);let present,backups;try{present=existsSync8(abs),backups=present?removalBackupSet(cwd,[dir],records):[]}catch(err){throw new CapabilityRemovalError(`Could not check the files in ${label} before removing it: ${errorMessage(err).replace(/\.$/,"")}. Nothing was changed.`)}removals.push({cap:cap2,reason,dir,present,backups})}return removals}function removalBackups(removals){return[...new Set(removals.flatMap(r=>r.backups))]}import{createHash as createHash3}from"node:crypto";import{resolve as resolve5}from"node:path";var SeamConfigError=class extends Error{constructor(message){super(message),this.name="SeamConfigError"}},RESOLUTION_STEPS=["official-skill","pinned-docs","fetch","model","ask"],SEAM_CONFIDENCE_LEVELS=["low","medium","high"],TERMINAL_STEP="ask",DEFAULT_SEAM_CONFIG={resolutionOrder:["official-skill","pinned-docs","model","fetch","ask"],modelConfidenceThreshold:"high",haltOnUnknown:!0},SEAM_KEYS=["resolutionOrder","modelConfidenceThreshold","haltOnUnknown"];function assertNoUnknownKeys(obj,known,label){for(let key3 of Object.keys(obj))if(!known.includes(key3))throw new SeamConfigError(`${label} has unknown key ${JSON.stringify(key3)} (expected one of ${known.join(", ")})`)}function validateSeamConfig(input){if(!isPlainObject(input))throw new SeamConfigError("seam must be an object");assertNoUnknownKeys(input,SEAM_KEYS,"seam");let{resolutionOrder}=input;if(!Array.isArray(resolutionOrder))throw new SeamConfigError(`seam.resolutionOrder must be an array (got ${JSON.stringify(resolutionOrder)})`);for(let i=0;i<resolutionOrder.length;i++){let step=resolutionOrder[i];if(!RESOLUTION_STEPS.includes(step))throw new SeamConfigError(`seam.resolutionOrder[${i}] has invalid step ${JSON.stringify(step)} (expected one of ${RESOLUTION_STEPS.join(", ")})`)}let seen=new Set;for(let step of resolutionOrder){if(seen.has(step))throw new SeamConfigError(`seam.resolutionOrder has duplicate step ${JSON.stringify(step)} (each step may appear at most once)`);seen.add(step)}if(!resolutionOrder.includes(TERMINAL_STEP))throw new SeamConfigError(`seam.resolutionOrder must contain "${TERMINAL_STEP}" \u2014 the terminal fallback cannot be configured away (fail-closed)`);let config={resolutionOrder};if(input.modelConfidenceThreshold!==void 0){let threshold=input.modelConfidenceThreshold;if(typeof threshold!="string"||!SEAM_CONFIDENCE_LEVELS.includes(threshold))throw new SeamConfigError(`seam.modelConfidenceThreshold ${JSON.stringify(threshold)} is invalid (expected one of ${SEAM_CONFIDENCE_LEVELS.join(", ")})`);config.modelConfidenceThreshold=threshold}if(input.modelConfidenceThreshold!==void 0&&!resolutionOrder.includes("model"))throw new SeamConfigError('seam.modelConfidenceThreshold is set but resolutionOrder has no "model" step for it to gate (add "model" or remove the threshold)');if(input.haltOnUnknown!==void 0){if(typeof input.haltOnUnknown!="boolean")throw new SeamConfigError(`seam.haltOnUnknown must be a boolean (got ${JSON.stringify(input.haltOnUnknown)})`);config.haltOnUnknown=input.haltOnUnknown}return config}var CONFIG_FILENAME="pharn.config.json",CAPABILITY_SOURCES=["auto","manual"],CapabilitySourceError=class extends Error{constructor(message){super(message),this.name="CapabilitySourceError"}},CapabilityEntryError=class extends Error{constructor(message){super(message),this.name="CapabilityEntryError"}};function validateCapabilityEntries(raw){if(raw!==void 0){if(!Array.isArray(raw))throw new CapabilityEntryError(`${CONFIG_FILENAME}: capabilities must be an array of {"name", "role"} entries (found ${describeOffender(raw)}). Fix it by hand \u2014 do NOT run \`pharn init\` to clear it: init overwrites this config.`);raw.forEach((entry,i)=>{let at=`${CONFIG_FILENAME}: capabilities[${i}]`;if(!isPlainObject(entry))throw new CapabilityEntryError(`${at} must be an object with "name" and "role" (found ${JSON.stringify(entry)}). Fix it by hand.`);try{assertSafeString(entry.name,`${at}.name`,CAPABILITY_NAME_RE)}catch(err){throw new CapabilityEntryError(`${errorMessage(err)}. A capability name is one lowercase, hyphen-separated segment (e.g. "a11y", "n-plus-one"). Fix it by hand.`)}if(!ROLE_VALUES.some(r=>r===entry.role))throw new CapabilityEntryError(`${at}.role must be ${ROLE_VALUES.map(r=>`"${r}"`).join(" or ")} (found ${JSON.stringify(entry.role)}). Fix it by hand.`)})}}function validateCapabilitySources(raw){Array.isArray(raw)&&raw.forEach((entry,i)=>{if(!isPlainObject(entry)||!("source"in entry))return;let source=entry.source;if(typeof source!="string"||!CAPABILITY_SOURCES.includes(source))throw new CapabilitySourceError(`${CONFIG_FILENAME}: capabilities[${i}].source must be ${CAPABILITY_SOURCES.map(s=>`"${s}"`).join(" or ")} (found ${JSON.stringify(source)}). Fix it by hand, or delete the field \u2014 an absent \`source\` is valid and the next \`pharn update\` will set it.`)})}var ArchetypesError=class extends Error{constructor(message){super(message),this.name="ArchetypesError"}};function describeOffender(value){return terminalSafe(escapeUnsafe(JSON.stringify(value)??String(value)),{max:80})}function validateArchetypes(raw){if(raw===void 0)return;let allowed=ARCHETYPE_VALUES.map(a=>`"${a}"`).join(", ");if(!Array.isArray(raw))throw new ArchetypesError(`${CONFIG_FILENAME}: archetypes must be an array of ${allowed} (found ${describeOffender(raw)}). Fix it by hand (e.g. ["ssr"]).`);raw.forEach((entry,i)=>{if(!ARCHETYPE_VALUES.some(a=>a===entry))throw new ArchetypesError(`${CONFIG_FILENAME}: archetypes[${i}] must be one of ${allowed} (found ${describeOffender(entry)}). Fix it by hand.`)})}var ConfigStampError=class extends Error{constructor(message){super(message),this.name="ConfigStampError"}};function validateStamp(raw){let where="Fix it by hand \u2014 `pharn.records.json`, if present, carries the same stamp.";if(typeof raw.skillsVersion=="string"&&!VERSION_RE.test(raw.skillsVersion))throw new ConfigStampError(`${CONFIG_FILENAME}: skillsVersion must be a version like "1.2.3" (found ${describeOffender(raw.skillsVersion)}). ${where}`);if(raw.commit!==void 0&&raw.commit!==null&&(typeof raw.commit!="string"||!COMMIT_RE.test(raw.commit)))throw new ConfigStampError(`${CONFIG_FILENAME}: commit must be a full 40-character lowercase hex commit SHA, or null (found ${describeOffender(raw.commit)}). ${where}`)}var ConfigParseError=class extends Error{constructor(message){super(message),this.name="ConfigParseError"}};function parseLocation(err){let at=/\(line (\d{1,9}) column (\d{1,9})\)$/.exec(errorMessage(err));return at?` (line ${at[1]}, column ${at[2]})`:""}var CONTROL_CHARS_GLOBAL_RE=new RegExp(CONTROL_CHARS_RE.source,"g");function displayPath(path){return path.replace(CONTROL_CHARS_GLOBAL_RE,c=>`\\x${c.charCodeAt(0).toString(16).padStart(2,"0")}`)}function configPath(cwd){return resolve5(cwd,CONFIG_FILENAME)}var CLI_OWNED_KEYS=new Set(Object.keys({pharnVersion:!0,skillsVersion:!0,pendingSkillsVersion:!0,frozenCapabilities:!0,repo:!0,commit:!0,ref:!0,constitution:!0,isMultiTenant:!0,modules:!0,installedAt:!0,updatedAt:!0,models:!0,seam:!0,stackAnswers:!0,installedSkills:!0,archetypes:!0,capabilities:!0,layout:!0}));function userOwnedConfigEntries(raw){return Object.fromEntries(Object.entries(raw).filter(([key3])=>!CLI_OWNED_KEYS.has(key3)))}function readPharnConfig(cwd){let path=configPath(cwd),read=readJsonBounded(path);if(read.kind==="absent"||read.kind==="unusable")return null;if(read.kind==="invalid-json")throw new ConfigParseError(`${displayPath(path)} is not valid JSON${parseLocation(read.error)}. The file exists \u2014 fix its syntax by hand. Do NOT run \`pharn init\` to clear it: init OVERWRITES this config, discarding your recorded capabilities, any manual \`pharn add\` provenance, and hand-edited models/seam blocks. If it is beyond repair, move it aside first (\`mv ${CONFIG_FILENAME} ${CONFIG_FILENAME}.bak\`), then run \`pharn init\`.`);let raw=read.value;if(!isPlainObject(raw)||typeof raw.skillsVersion!="string"||!Array.isArray(raw.modules))return null;let seam=raw.seam!==void 0?validateSeamConfig(raw.seam):void 0;validateCapabilityEntries(raw.capabilities),validateCapabilitySources(raw.capabilities),Array.isArray(raw.capabilities)&&(validateArchetypes(raw.archetypes),validateStamp(raw));let config={...raw,...seam!==void 0?{seam}:{}};return config.layout!=="pharn"&&config.layout!=="flat"&&delete config.layout,config.ref!==void 0&&config.ref!=="latest"&&delete config.ref,config.pendingSkillsVersion!==void 0&&(typeof config.pendingSkillsVersion!="string"||!VERSION_RE.test(config.pendingSkillsVersion))&&delete config.pendingSkillsVersion,config.frozenCapabilities!==void 0&&!isFrozenKeyList(config.frozenCapabilities)&&delete config.frozenCapabilities,config}function isFrozenKeyList(value){return Array.isArray(value)&&value.every(key3=>{if(typeof key3!="string")return!1;let sep2=key3.indexOf(":");if(sep2===-1)return!1;let role=key3.slice(0,sep2),name=key3.slice(sep2+1);return ROLE_VALUES.some(r=>r===role)&&CAPABILITY_NAME_RE.test(name)})}function loadConfigOrExit(cwd,opts={}){let fail2=message=>{reportLoadError(message,opts.json??!1),process.exit(1)};try{let config=readPharnConfig(cwd);if(config)return config}catch(err){throw isConfigValidationError(err)&&fail2(err.message),err}return fail2("No pharn.config.json found. Run `pharn init` first.")}function reportLoadError(message,json){json?logErrorPlain(message):logError(message)}function assertConfigUnchanged(cwd,snapshot,command){let current;try{current=readPharnConfig(cwd)}catch{current=null}if(!(current!==null&&JSON.stringify(current)===JSON.stringify(snapshot)))throw configChangedError(command)}function configChangedError(command){return new ProjectChangedError(`${CONFIG_FILENAME} changed while \`pharn ${command}\` was running \u2014 another pharn process (or an edit) wrote it after this command read it. Nothing was written. Re-run \`pharn ${command}\` to act on the current state.`)}function configFingerprint(cwd){let read=readBoundedFile(configPath(cwd));return read.kind==="absent"?"absent":read.kind==="unusable"?`unreadable:${read.code}`:`sha256:${createHash3("sha256").update(read.bytes).digest("hex")}`}function assertConfigFingerprintUnchanged(cwd,fingerprint,command){if(configFingerprint(cwd)!==fingerprint)throw configChangedError(command)}function isConfigValidationError(err){return err instanceof ConfigParseError||err instanceof SeamConfigError||err instanceof CapabilityEntryError||err instanceof CapabilitySourceError||err instanceof ArchetypesError||err instanceof ConfigStampError}async function writePharnConfig(cwd,config){await writeJsonAtomic(configPath(cwd),config)}function isArchetypeConfig(config){return Array.isArray(config.capabilities)}var LEGACY_CONFIG_MESSAGE="This project uses the legacy module layout (pre-archetype), which is no longer supported. Re-run `pharn init` to reinstall with the archetype/capability model.";function loadArchetypeConfigOrExit(cwd,opts={}){let config=loadConfigOrExit(cwd,opts);return isArchetypeConfig(config)||(reportLoadError(LEGACY_CONFIG_MESSAGE,opts.json??!1),process.exit(1)),config}function resolveCapabilities(archetypes,index){let detected=new Set(archetypes),selected=[],skipped=[];for(let entry of index.capabilities){if(entry.applies==="universal"){selected.push({name:entry.name,role:entry.role,matched:"universal"});continue}let matched=entry.applies.filter(a=>detected.has(a));matched.length>0?selected.push({name:entry.name,role:entry.role,matched}):skipped.push({name:entry.name,role:entry.role,reason:`applies to [${entry.applies.join(", ")}]; detected [${archetypes.join(", ")}]`})}return{selected,skipped}}var PRODUCT_STAGES=["spec","plan","grill","build","regress","verify","ship","loop","review","memory-promote","ac-test"],MODEL_ALIASES=["sonnet","opus","haiku","fable","inherit"],MODEL_ID_RE=/^claude-[a-z0-9][a-z0-9-]*$/,EFFORT_LEVELS=["low","medium","high","xhigh","max"];function isValidModel(model){return typeof model=="string"&&(MODEL_ALIASES.includes(model)||MODEL_ID_RE.test(model))}function isValidEffort(effort){return typeof effort=="string"&&EFFORT_LEVELS.includes(effort)}function checkModelsBlock(models){if(models==null)return{kind:"no-stages"};if(!isPlainObject(models))return invalid("shape","`models` is present but is not an object");let stages=models.stages;if(stages==null)return{kind:"no-stages"};if(!isPlainObject(stages))return invalid("shape","`models.stages` is present but is not an object");let reds=[];Object.hasOwn(stages,"default")||reds.push({kind:"default",detail:"missing required `default` stage entry (the resolution fallback)"});for(let[name,entry]of Object.entries(stages)){let stage=`stage ${JSON.stringify(name)}`;if(name!=="default"&&!PRODUCT_STAGES.includes(name)){reds.push({kind:"stage",detail:`${stage} is not a product stage \u2014 expected one of {${PRODUCT_STAGES.join(", ")}} or "default"`});continue}if(!isPlainObject(entry)){reds.push({kind:"entry",detail:`${stage} is not an object with {model, effort}`});continue}Object.hasOwn(entry,"model")?isValidModel(entry.model)||reds.push({kind:"model",detail:`${stage} model ${JSON.stringify(entry.model)} is not an alias {${MODEL_ALIASES.join(", ")}} nor a claude-* id`}):reds.push({kind:"model",detail:`${stage} missing \`model\``}),Object.hasOwn(entry,"effort")?isValidEffort(entry.effort)||reds.push({kind:"effort",detail:`${stage} effort ${JSON.stringify(entry.effort)} not in {${EFFORT_LEVELS.join(", ")}}`}):reds.push({kind:"effort",detail:`${stage} missing \`effort\``})}return reds.length>0?{kind:"invalid",reds}:{kind:"valid",stages}}function invalid(kind,detail){return{kind:"invalid",reds:[{kind,detail}]}}function resolveStageModel(stages,stage){let entry=Object.hasOwn(stages,stage)?stages[stage]:stages.default,{model,effort}=entry;return{model,effort}}var UPSTREAM_CONFIG_FILE="pharn.config.json",MAX_UPSTREAM_CONFIG_BYTES=1024*1024;function readUpstreamModels(repoDir){let read=readJsonBounded(safeJoin(repoDir,UPSTREAM_CONFIG_FILE),MAX_UPSTREAM_CONFIG_BYTES);if(read.kind==="absent")return{kind:"absent"};if(read.kind==="unusable")return{kind:"invalid",reasons:[`pharn-oss's ${UPSTREAM_CONFIG_FILE} ${read.reason}`]};if(read.kind==="invalid-json")return{kind:"invalid",reasons:[`pharn-oss's ${UPSTREAM_CONFIG_FILE} is not valid JSON`]};let config=read.value;if(!isPlainObject(config))return{kind:"invalid",reasons:[`pharn-oss's ${UPSTREAM_CONFIG_FILE} is valid JSON but is not an object`]};let block=config.models;if(block==null)return{kind:"absent"};let check=checkModelsBlock(block);if(check.kind==="invalid")return{kind:"invalid",reasons:check.reds.map(red=>red.detail)};try{JSON.stringify(block)}catch{return{kind:"invalid",reasons:["pharn-oss's models block is nested too deeply to copy"]}}return{kind:"ok",block}}function versionStatus(input){let ahead=compareVersionCore(input.installed,input.latest)===1,outdated=!ahead&&input.installed!==input.latest;return{ahead,outdated}}import{lstatSync as lstatSync14}from"node:fs";import{relative as relative2}from"node:path";function decideFileAction(input){let{diskHash,latestHash,recordedHash,recordsAvailable,force}=input;return diskHash===null?{action:"write",label:"restored",backup:!1,refreshRecord:!0,forced:!1}:diskHash===latestHash?{action:"noop",label:"ok",backup:!1,refreshRecord:!0,forced:!1}:recordsAvailable?recordedHash===null?skipOrForce("unrecorded",force):diskHash===recordedHash?{action:"write",label:"updated",backup:!1,refreshRecord:!0,forced:!1}:skipOrForce("modified",force):skipOrForce("unverifiable",force)}function skipOrForce(label,force){return force?{action:"write",label,backup:!0,refreshRecord:!0,forced:!0}:{action:"skip",label,backup:!1,refreshRecord:!1,forced:!1}}var SKIP_ORDER=["modified","unrecorded","unverifiable","unreadable","held"];function planUpdate(params){let{latestHashes,diskStates,records,force,unit,holdUnit}=params,files=[],writes=[],backups=[],nextRecords={},groups=new Map,counts={updated:0,restored:0,ok:0,forced:0,skipped:0};for(let[rel,latestHash]of latestHashes){let disk=diskStates.get(rel)??{kind:"absent"},previous=records?.[rel];if(disk.kind==="unreadable"){files.push({rel,action:"skip",label:"unreadable",backup:!1,forced:!1}),pushGroup(groups,"unreadable",rel),counts.skipped+=1,previous!==void 0&&(nextRecords[rel]=previous);continue}let decision=decideFileAction({diskHash:disk.kind==="file"?disk.hash:null,latestHash,recordedHash:previous??null,recordsAvailable:records!==null,force});files.push({rel,action:decision.action,label:decision.label,backup:decision.backup,forced:decision.forced}),decision.action==="write"?(writes.push(rel),decision.backup&&backups.push(rel),decision.forced?counts.forced+=1:decision.label==="restored"?counts.restored+=1:counts.updated+=1):decision.action==="noop"?counts.ok+=1:(pushGroup(groups,decision.label,rel),counts.skipped+=1),decision.refreshRecord?nextRecords[rel]=latestHash:previous!==void 0&&(nextRecords[rel]=previous)}let held=force||!holdUnit||!unit?null:holdUnitWrites({files,writes,groups,counts,unit,records,nextRecords}),skipped=SKIP_ORDER.filter(label=>groups.has(label)).map(label=>({label,rels:groups.get(label).slice().sort()}));return{files,writes,backups,skipped,counts,nextRecords,held}}function holdUnitWrites(acc){let{files,writes,groups,counts,unit,records,nextRecords}=acc,blocking=files.filter(f=>f.action==="skip"&&unit(f.rel)).map(f=>({rel:f.rel,label:f.label})).sort((a,b)=>a.rel<b.rel?-1:a.rel>b.rel?1:0);if(blocking.length===0)return null;let heldRels=[];for(let file of files){if(file.action!=="write"||!unit(file.rel))continue;file.label==="restored"?counts.restored-=1:counts.updated-=1,counts.skipped+=1,file.action="skip",file.label="held",heldRels.push(file.rel),pushGroup(groups,"held",file.rel);let previous=records?.[file.rel];previous!==void 0?nextRecords[file.rel]=previous:delete nextRecords[file.rel]}if(heldRels.length===0)return null;let heldSet=new Set(heldRels);for(let i=writes.length-1;i>=0;i-=1)heldSet.has(writes[i])&&writes.splice(i,1);return{blocking,held:heldRels.slice().sort()}}function pushGroup(groups,label,rel){let existing=groups.get(label);existing?existing.push(rel):groups.set(label,[rel])}function scanDest(params){let{repoDir,projectRoot,rels,sources}=params,records=params.records??null,drifted=[],labels=new Map,unsafe=[];for(let rel of rels){let srcRel=sources?.get(rel)??rel,dest=safeJoin(projectRoot,rel),src=safeJoin(repoDir,srcRel),destLink=findSymlinkComponentOr(projectRoot,rel,UNREADABLE);if(destLink===UNREADABLE)continue;if(destLink!==null){unsafe.push({rel,link:destLink});continue}if(!lstatSync14(dest,{throwIfNoEntry:!1})?.isFile()||findSymlinkComponentOr(repoDir,srcRel,UNREADABLE)!==null||!lstatSync14(src,{throwIfNoEntry:!1})?.isFile())continue;let label=driftLabel(decideFileAction({diskHash:contentHash(dest),latestHash:contentHash(src),recordedHash:records!==null&&Object.hasOwn(records,rel)?records[rel]??null:null,recordsAvailable:records!==null,force:!0}));label!==null&&(drifted.push(rel),labels.set(rel,label))}return{drifted:drifted.sort(),labels,unsafe:unsafe.sort((a,b)=>a.rel<b.rel?-1:a.rel>b.rel?1:0)}}function manifestSources(repoDir,manifest){let sources=new Map;for(let[dest,from]of manifest)sources.set(dest,toPosix(relative2(repoDir,from)));return sources}function driftLabel(decision){if(!decision.backup)return null;let{label}=decision;return label==="modified"||label==="unrecorded"?label:"unverifiable"}var UNREADABLE=Symbol("unreadable");var MAX_LISTED2=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}=scanDest({repoDir,projectRoot,rels:conflicts.filter(p=>manifest.has(p)),sources:manifestSources(repoDir,manifest),records}),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,shown2=max===void 0?paths:paths.slice(0,max),lines=shown2.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-shown2.length;return more>0&&lines.push(` \u2026and ${more} more`),lines}var OverwriteRefusedError=class extends Error{constructor(message){super(message),this.name="OverwriteRefusedError"}};function assertNoExistingTargets(params){let plan=planWriteTargets(params),deletes=removalLines(plan.removals);if(deletes.length>0)throw new OverwriteRefusedError([`pharn init --yes never deletes, and this install would delete ${deletes.length} capability director${deletes.length===1?"y":"ies"} it drops from pharn.config.json:`,...deletes,"Run `pharn init` in a terminal to review and confirm, `pharn init --dry-run` to see the whole plan, or `pharn update` to refresh an existing install."].join(`
|
|
21
21
|
`));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_LISTED2),"--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."].join(`
|
|
22
22
|
`))}function capabilityKey(cap2){return`${cap2.role}:${cap2.name}`}function readPreviousConfig(cwd){let fingerprint=configFingerprint(cwd),config;try{config=readPharnConfig(cwd)}catch{config=null}return{fingerprint,config}}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){let drops=carry.dropped??[];return drops.length===0?[]:planCapabilityRemovals({cwd,paths:layoutPaths(carry.previousLayout??"flat"),drops,records:reinstallBaseline(cwd,carry.previousStamp),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,previousStamp){return previousStamp===null?null:recordsBaseline(readRecords(cwd),previousStamp).records}function initRecordedPaths(params){let{cwd,manifest,carry,capabilities,layout}=params,baseline=reinstallBaseline(cwd,carry.previousStamp),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){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:reinstallBaseline(cwd,carry.previousStamp)})}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"],installed2=previous.skillsVersion;return source.kind==="release"&&typeof installed2=="string"&&versionStatus({installed:installed2,latest:source.version}).ahead&&lines.push(` installed v${terminalSafe(installed2,{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});prepareInstall(repoDir,cwd,selection.selected,manifest);let removals=planInitRemovals(cwd,carry),{conflicts,labels,configBackedUp}=planWriteTargets({repoDir,projectRoot:cwd,capabilities:selection.selected,manifest,records:reinstallBaseline(cwd,carry.previousStamp)}),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),backups=[...new Set([...[...labels.keys()].sort(),...configBackedUp?[PHARN_CONFIG_FILE]:[],...removalBackups(removals),...rootMigration?.backups??[]])],settingsPreserved=existsSync9(safeJoin(cwd,CLAUDE_SETTINGS_FILE)),upstreamModels=readUpstreamModels(repoDir);return{archetypes,archetypeOrigin:origin,previousArchetypes:recordedArchetypes(chosen.previous.config?.archetypes),channelLines:previousChannelLines({previous:chosen.previous.config,channel,explicit:params.refExplicit??!1,source}),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,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:rootMigration?.report??null,gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,initRecordedPaths({cwd,manifest,carry,capabilities:selection.selected,layout}))}}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&&!p.removals.some(r=>r.present),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.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 existsSync10}from"node:fs";import{resolve as resolve6}from"node:path";function runGitPrereq(opts={}){let cwd=process.cwd();existsSync10(resolve6(cwd,".git"))||fail(`git not found.
|
|
23
23
|
Run: git init && git add -A && git commit -m 'init'
|
|
@@ -48,17 +48,18 @@ ${deleteBlock}`:""}`);let result=await confirm({message:deletes.length>0?"Contin
|
|
|
48
48
|
`)),r.models.outcome==="rejected"&&log6.warn(["pharn-oss's models block would not be written; this pharn rejects it:",...r.models.reasons.map(reason=>` ${terminalSafe(reason,{max:300})}`)].join(`
|
|
49
49
|
`)),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.`)}import{intro as intro2,log as log8,outro as outro3,spinner as spinner3}from"@clack/prompts";function parseCapabilityArg(arg){if(!arg.includes(":"))return{name:arg};let idx=arg.indexOf(":"),role=arg.slice(0,idx),name=arg.slice(idx+1);return role!=="griller"&&role!=="lens"?{name,error:`Unknown role "${role}". Use griller:<name> or lens:<name>.`}:{name,role}}import{groupMultiselect,isCancel as isCancel3,log as log7}from"@clack/prompts";async function resolveAddPicker(repoDir,sha,config,cwd,addOne){let index=parseCapabilityIndex(repoDir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&log7.warn(unknownWarning);let installed2=config.capabilities??[],{groups,availableCount}=buildAddSelection(index,installed2);if(availableCount===0)return{kind:"all-installed"};installed2.length>0&&log7.info(`Installed (${installed2.length}): ${installed2.map(c=>`${c.name} (${c.role})`).join(", ")}`);let picked=await groupMultiselect({message:"Select capabilities to add",options:groups,required:!1,selectableGroups:!1});if(isCancel3(picked))return{kind:"cancelled"};let values=picked;if(values.length===0)return{kind:"none"};let added=[],cfg=config;for(let value of values){let parsed=parseCapabilityArg(value),result=await addOne(repoDir,sha,cfg,cwd,parsed,value,index);result.kind==="added"?(log7.info(`${color_default.green("\u2714")} Added ${result.name}`),added.push(result.name),cfg={...cfg,...result.stamp,capabilities:[...cfg.capabilities??[],{name:parsed.name,role:parsed.role,source:"manual"}]}):result.kind==="noop"?log7.info(`${result.name} is already installed.`):logError(`\u26A0 ${result.message}`)}return{kind:"installed",added}}async function runAdd(capabilityArg){intro2("pharn add");let cwd=process.cwd(),config=loadArchetypeConfigOrExit(cwd);await runArchetypeAdd(config,cwd,capabilityArg)}function versionGate(repoDir,config,source){let fetched=readSkillsVersion(repoDir);if(fetched===config.skillsVersion||fetched===config.pendingSkillsVersion)return null;if(versionStatus({installed:config.skillsVersion,latest:fetched}).ahead)return source.kind==="release"?`Your install (skills v${config.skillsVersion}) is ahead of the latest verified ${REPO_URL} release (${source.tag}) \u2014 it came from pharn-oss main, and \`pharn add\` installs only at the version your project is already on. Run \`pharn update --ref main\` to follow main (\`pharn add\` then fetches from it too), or wait for a release at v${config.skillsVersion}.`:`Your install (skills v${config.skillsVersion}) is newer than ${REPO_URL} main (v${fetched}) \u2014 pharn-oss main has moved back to an older version, and \`pharn add\` installs only at the version your project is already on. Wait for main to reach v${config.skillsVersion} again, or run \`pharn update --force\` to downgrade to v${fetched} first (it backs up the files you edited to pharn/.backup/), then re-run \`pharn add\`.`;let base=`Skills version mismatch: pharn.config.json records v${config.skillsVersion}, but the fetched ${REPO_URL} is at v${fetched}. \`pharn add\` installs only at the version your project is already on`;return config.pendingSkillsVersion===void 0?`${base} \u2014 run \`pharn update\` first, then re-run \`pharn add\`.`:`${base} (v${config.pendingSkillsVersion} apart from files you edited). Run \`pharn update\` first; if it keeps skipping your edited files, either revert those edits or run \`pharn update --force\` (it backs them up to pharn/.backup/ first), then re-run \`pharn add\`.`}function addStamp(config,version,sha){return version===config.skillsVersion?{skillsVersion:version,commit:sha}:{skillsVersion:config.skillsVersion,commit:config.commit}}function layoutGate(repoDir,config){let clone=detectLayout(repoDir),recorded=configLayout(config);return clone===recorded?null:`Install layout mismatch: pharn.config.json records the \`${recorded}\` layout, but the fetched ${REPO_URL} uses the \`${clone}\` layout. \`pharn add\` installs only at the layout your project is already recorded at \u2014 adding here would put files where \`pharn remove\` and \`pharn status\` will never look for them. Run \`pharn update --force\` first, then re-run \`pharn add\`.`}async function runArchetypeAdd(config,cwd,arg){if(arg===void 0){await runAddPicker(config,cwd);return}let parsed=parseCapabilityArg(arg);parsed.error&&(logError(parsed.error),process.exit(1));let result;try{result=await withProjectLock(cwd,"add",async()=>{assertConfigUnchanged(cwd,config,"add");let proxyNotice=detectProxyNotice(process.env);proxyNotice&&log8.warn(proxyNoticeMessage(proxyNotice));let s=spinner3();s.start(`Fetching capabilities from ${REPO_URL}`);let repo;try{repo=await fetchRepo(await resolveSource(channelOf(config))),s.stop(`Capabilities fetched from ${sourceLabel(repo.source)}`)}catch(err){throw s.stop("Failed to fetch capabilities"),err}try{let gate=minCliGate(repo.dir,PHARN_VERSION);gate.warning&&log8.warn(gate.warning);let refusal3=gate.refusal??versionGate(repo.dir,config,repo.source)??layoutGate(repo.dir,config);return refusal3?{kind:"error",message:refusal3}:await resolveArchetypeAdd(repo.dir,repo.sha,config,cwd,parsed,arg)}finally{repo.cleanup()}})}catch(err){result=err instanceof ProjectLockedError?{kind:"error",message:err.message}:{kind:"error",message:errorMessage(err),cause:{err}}}if(result.kind==="error"&&(reportFatal(result.message,result.cause),process.exit(1)),result.kind==="noop"){outro3(`${result.name} is already installed.`);return}outro3(`${color_default.green("\u2714")} Added ${result.name} ${color_default.dim(`(skills v${result.version})`)}`)}async function runAddPicker(config,cwd){interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY})||(logError("Specify a capability (e.g. `pharn add a11y` or `pharn add lens:n-plus-one`), or run `pharn add` in an interactive terminal to pick from a list."),process.exit(1));let outcome;try{outcome=await withProjectLock(cwd,"add",async()=>{assertConfigUnchanged(cwd,config,"add");let proxyNotice=detectProxyNotice(process.env);proxyNotice&&log8.warn(proxyNoticeMessage(proxyNotice));let s=spinner3();s.start(`Fetching capabilities from ${REPO_URL}`);let repo;try{repo=await fetchRepo(await resolveSource(channelOf(config))),s.stop(`Capabilities fetched from ${sourceLabel(repo.source)}`)}catch(err){throw s.stop("Failed to fetch capabilities"),err}try{let gate=minCliGate(repo.dir,PHARN_VERSION);gate.warning&&log8.warn(gate.warning);let refusal3=gate.refusal??versionGate(repo.dir,config,repo.source)??layoutGate(repo.dir,config);return refusal3?{kind:"error",message:refusal3}:await resolveAddPicker(repo.dir,repo.sha,config,cwd,resolveArchetypeAdd)}finally{repo.cleanup()}})}catch(err){outcome=err instanceof ProjectLockedError?{kind:"error",message:err.message}:{kind:"error",message:errorMessage(err),cause:{err}}}if(outcome.kind==="error"&&(reportFatal(outcome.message,outcome.cause),process.exit(1)),outcome.kind==="all-installed"){outro3("All available capabilities are already installed.");return}if(outcome.kind==="cancelled"&&cancelAndExit(),outcome.kind==="none"){outro3("Nothing selected. No capabilities were added.");return}outro3(`${color_default.green("\u2714")} Added ${outcome.added.length} ${plural(outcome.added.length)}.`)}function plural(n){return n===1?"capability":"capabilities"}async function resolveArchetypeAdd(repoDir,sha,config,cwd,parsed,arg,parsedIndex){let index=parsedIndex;if(index===void 0){index=parseCapabilityIndex(repoDir);let unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&log8.warn(unknownWarning)}let matches=index.capabilities.filter(c=>c.name===parsed.name&&(parsed.role===void 0||c.role===parsed.role));if(matches.length===0){let valid=index.capabilities.map(c=>`${c.role}:${c.name}`).sort();return{kind:"error",message:`Unknown capability "${arg}". Valid capabilities:
|
|
50
50
|
${valid.join(`
|
|
51
|
-
`)}`}}if(matches.length>1)return{kind:"error",message:`"${parsed.name}" is ambiguous \u2014 use ${matches.map(m=>`${m.role}:${m.name}`).join(" or ")}.`};let cap2=matches[0],existing=config.capabilities??[];if(existing.some(c=>c.name===cap2.name&&c.role===cap2.role))return{kind:"noop",name:cap2.name};let paths=layoutPaths(detectLayout(repoDir)),cloneRels=capabilityCloneFiles(repoDir,paths,cap2),scan=scanDest({repoDir,projectRoot:cwd,rels:cloneRels});if(scan.unsafe.length>0){let first=scan.unsafe[0],more=scan.unsafe.length>1?` (and ${scan.unsafe.length-1} more under the same capability)`:"";return{kind:"error",message:`Refusing to add ${cap2.name}: \`${first.link}\` in your project is a symlink, and \`${first.rel}\` sits under it${more}. \`pharn add\` copies the whole capability directory, which would write THROUGH that link and replace files it points at \u2014 possibly outside your project \u2014 and those cannot be backed up. Replace the symlink with a real directory (or move it aside), then re-run \`pharn add ${cap2.name}\`.`}}if(scan.drifted.length>0){let backupDir=createBackup(cwd,scan.drifted);printBackupNotice({dir:backupDir,saved:scan.drifted.length,action:"overwriting",gitignored:backupDirIgnored(cwd)})}installCapabilityDirs(repoDir,cwd,[{name:cap2.name,role:cap2.role}]);let version=readSkillsVersion(repoDir),stamp=addStamp(config,version,sha),capabilities=[...existing,{name:cap2.name,role:cap2.role,source:"manual"}];return await mergeCapabilityRecords(cwd,config,cloneRels,stamp.skillsVersion,stamp.commit),await writePharnConfig(cwd,{...config,...stamp,capabilities}),{kind:"added",name:cap2.name,version,stamp}}async function mergeCapabilityRecords(cwd,config,cloneRels,skillsVersion,commit){let{records}=recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit});if(records===null)return;let added=buildRecords(cwd,cloneRels);await writeRecords(cwd,{skillsVersion,commit,files:mergeRecords(records,added)})}import{confirm as confirm2,groupMultiselect as groupMultiselect2,intro as intro3,isCancel as isCancel4,log as log9,outro as outro4}from"@clack/prompts";async function runRemove(arg){intro3("pharn remove");let cwd=process.cwd(),config=loadArchetypeConfigOrExit(cwd);try{await removeCapability(cwd,config,arg)}catch(err){throw err instanceof ProjectLockedError&&(logError(err.message),process.exit(1)),err instanceof RemoveBackupError&&(logError(err.message),process.exit(1)),err instanceof SymlinkedTargetError&&(logError(err.message),process.exit(1)),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){let installed2=config.capabilities??[];if(arg===void 0){await runRemovePicker(cwd,config,installed2);return}await removeNamed(cwd,config,installed2,arg)}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,config){return recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit}).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[key3,hash]of Object.entries(records))prefixes.some(prefix=>key3.startsWith(prefix))?dropped++:kept[key3]=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";log9.warn(`${names} ${one?"is":"are"} selected automatically for your archetypes, so ${one?"it comes":"they come"} back: the next \`pharn update\` that re-applies your install \u2014 at the latest the one that moves to a new pharn-oss version \u2014 reinstalls ${pronoun} and names ${pronoun} in its report. Until then \`pharn update\` may answer "Already up to date" and leave ${pronoun} removed; \`pharn update --force\` reinstalls ${pronoun} now.`)}async function removeNamed(cwd,config,installed2,address){let parsed=parseCapabilityArg(address);parsed.error&&(logError(parsed.error),process.exit(1));let matches=installed2.filter(c=>c.name===parsed.name&&(parsed.role===void 0||c.role===parsed.role));if(matches.length===0){let valid=installed2.map(c=>`${c.role}:${c.name}`).sort(),hint=valid.length?` Installed: ${valid.join(", ")}.`:" No capabilities are installed.";logError(`"${address}" is not an installed capability.${hint} Nothing was removed.`),process.exit(1)}matches.length>1&&(logError(`"${parsed.name}" is ambiguous \u2014 use ${matches.map(m=>`${m.role}:${m.name}`).join(" or ")}.`),process.exit(1));let target=matches[0],paths=layoutPaths(configLayout(config));refuseSymlinkedTargets(cwd,paths,[target]);let note9=await withProjectLock(cwd,"remove",async()=>{assertConfigUnchanged(cwd,config,"remove"),refuseSymlinkedTargets(cwd,paths,[target]);let records=readRecordsBaseline(cwd,config);backupBeforeDelete(cwd,paths,[target],records);let existed=deleteCapabilityDir(cwd,paths,target);return await pruneCapabilityRecords(cwd,config,paths,[target],records),await writePharnConfig(cwd,{...config,capabilities:installed2.filter(c=>!(c.name===target.name&&c.role===target.role))}),existed?"":color_default.dim(" (its files were already gone)")});warnIfAutoSelected([target]),outro4(`${color_default.green("\u2714")} Removed ${target.name} (${target.role})${note9}`)}async function runRemovePicker(cwd,config,installed2){if(installed2.length===0){outro4("No capabilities are installed.");return}interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY})||(logError("Specify a capability to remove (e.g. `pharn remove a11y`), or run `pharn remove` in an interactive terminal to pick from a list."),process.exit(1));let{groups}=buildRemoveSelection(installed2),picked=await groupMultiselect2({message:"Select capabilities to remove",options:groups,required:!1,selectableGroups:!1});isCancel4(picked)&&cancelAndExit();let values=picked;if(values.length===0){outro4("Nothing selected. No capabilities were removed.");return}let targets=[];for(let value of values){let parsed=parseCapabilityArg(value),target=installed2.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 confirm2({message:`Remove ${targets.length} ${plural2(targets.length)}: ${targets.map(t=>`${t.name} (${t.role})`).join(", ")}?`,initialValue:!1});(isCancel4(ok)||ok!==!0)&&cancelAndExit(),await withProjectLock(cwd,"remove",async()=>{assertConfigUnchanged(cwd,config,"remove"),refuseSymlinkedTargets(cwd,paths,targets);let records=readRecordsBaseline(cwd,config);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:installed2.filter(c=>!removed.has(`${c.role}:${c.name}`))})}),warnIfAutoSelected(targets),outro4(`${color_default.green("\u2714")} Removed ${targets.length} ${plural2(targets.length)}.`)}function plural2(n){return n===1?"capability":"capabilities"}function key2(cap2){return`${cap2.role}:${cap2.name}`}function mergeCapabilities(selection,previous,frozen){let resolved=new Set(selection.selected.map(key2)),inIndex=new Set([...selection.selected.map(key2),...selection.skipped.map(key2)]),previousSource=new Map,seenPrevious=new Set;for(let cap2 of previous){let k=key2(cap2);seenPrevious.has(k)||(seenPrevious.add(k),previousSource.set(k,cap2.source))}let capabilities=[],changes=[];for(let sel of selection.selected){let k=key2(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=key2(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}}var LEGACY_MODEL_ALIASES=new Map([["opus-4-8","opus"],["sonnet-5","sonnet"],["fable-5","fable"],["haiku-4-5","haiku"]]),LEGACY_DEFAULTS=[JSON.stringify({default:{model:"sonnet-5",effort:"high"},stages:{plan:{model:"opus-4-8",effort:"max"},review:{model:"opus-4-8",effort:"high"}}}),JSON.stringify({default:{model:"sonnet-5",effort:"high"},stages:{plan:{model:"opus-4-8",effort:"max"},review:{model:"fable-5",effort:"max"}}})];function isLegacyDefault(block){return block!==void 0&&LEGACY_DEFAULTS.includes(JSON.stringify(block))}function convertLegacyModels(block){if(!isPlainObject(block))return{block,changes:[],leftovers:[]};let changes=[],leftovers=[],next=block;if(Object.hasOwn(next,"default")){let{default:moved,...rest}=next,stages2=next.stages;stages2==null?(next={...rest,stages:{default:moved}},changes.push("moved `models.default` into `models.stages.default`")):isPlainObject(stages2)&&!Object.hasOwn(stages2,"default")?(next={...rest,stages:{default:moved,...stages2}},changes.push("moved `models.default` into `models.stages.default`")):leftovers.push(isPlainObject(stages2)?"`models.default` was left where it is: `models.stages.default` is already set, and pharn-oss reads only that one":"`models.default` was left where it is: `models.stages` is not an object, so it cannot move into it")}let stages=next.stages;if(isPlainObject(stages)){let mapped=!1,converted=Object.fromEntries(Object.entries(stages).map(([name,entry])=>{if(!isPlainObject(entry)||typeof entry.model!="string")return[name,entry];let alias=LEGACY_MODEL_ALIASES.get(entry.model);return alias===void 0?[name,entry]:(mapped=!0,changes.push(`stage ${JSON.stringify(name)} model ${JSON.stringify(entry.model)} \u2192 ${JSON.stringify(alias)}`),[name,{...entry,model:alias}])}));mapped&&(next={...next,stages:converted})}return{block:changes.length>0?next:block,changes,leftovers}}function needsModelsConversion(block){return convertLegacyModels(block).changes.length>0}function modelsMigrationPending(block,recorded){return needsModelsConversion(block)&&(recorded===null||modelsRecordHash(block)!==recorded)}function decideModelsUpdate(input){let{current,upstream,recorded,recordsAvailable,force}=input,none={label:null,replacedLegacyDefault:!1,backup:!1,conversion:null,problems:[],upstreamReasons:[]};if(upstream.kind!=="ok"){let kept=keep(current),pharns=current!==void 0&&(isLegacyDefault(current)||recorded!==null&&modelsRecordHash(current)===recorded);return{...none,...kept,outcome:upstream.kind==="absent"?"upstream-absent":"upstream-invalid",nextRecord:pharns?modelsRecordHash(kept.next):recorded,upstreamReasons:upstream.kind==="invalid"?upstream.reasons:[]}}let latestHash=modelsRecordHash(upstream.block),diskHash=current===void 0?null:modelsRecordHash(current),legacyDefault=isLegacyDefault(current),decision=decideFileAction({diskHash,latestHash,recordedHash:legacyDefault?diskHash:recorded,recordsAvailable:legacyDefault||recordsAvailable,force});return decision.action==="write"?{...none,outcome:decision.forced?"forced":decision.label==="restored"?"restored":"updated",label:decision.forced?decision.label:null,replacedLegacyDefault:legacyDefault,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,conversion:null,problems:[]};let conversion=convertLegacyModels(current),check=checkModelsBlock(conversion.block);return{next:conversion.block,conversion:conversion.changes.length>0?conversion:null,problems:[...conversion.leftovers,...check.kind==="invalid"?check.reds.map(red=>red.detail):[]]}}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,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{records,note:recordsNote}=recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit}),plan=planUpdate({latestHashes,diskStates,records,force}),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))?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=planRootMigration({projectRoot:cwd,repoDir,layout,installedLayout:previousLayout,skillsVersion:installedVersion,records}),retired=new Set((rootMigration?.report.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 key3=`${cap2.role}:${cap2.name}`;return frozen.has(key3)||previouslyFrozen.has(key3)&&hasSkippedFile(cap2)}).map(cap2=>`${cap2.role}:${cap2.name}`))].sort();return{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,models,modelsFloor:paths.floor,hookWiring:diffHookWiring(repoDir,cwd),absentUpstream:absentInstallSurfaces({repoDir,layout}),recordsNote,unknownWarning,unknownCapabilities:index.unknown,orphans,rootMigration:rootMigration?.report??null,rootMoveBackups:rootMigration?.backups??[],gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,prettierignorePaths)},apply:{expected,records,plan,models,configCapabilities,frozen,frozenRecords,orphanRecords:orphanScan.records,nextSkillsVersion,nextCommit,frozenKeys,removalPaths,rootMoveBackups:rootMigration?.backups??[],prettierignorePaths}}}import{log as log10,note as note4,outro as outro5}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 reportRootMigration(m,result){let lines=m===null?null:rootMigrationNoteLines(m,result);lines&¬e4(lines.join(`
|
|
52
|
-
`),"ROOT MIGRATION")}var FORCEABLE_SKIPS=new Set(["modified","unrecorded","unverifiable"]);function
|
|
53
|
-
`),"
|
|
51
|
+
`)}`}}if(matches.length>1)return{kind:"error",message:`"${parsed.name}" is ambiguous \u2014 use ${matches.map(m=>`${m.role}:${m.name}`).join(" or ")}.`};let cap2=matches[0],existing=config.capabilities??[];if(existing.some(c=>c.name===cap2.name&&c.role===cap2.role))return{kind:"noop",name:cap2.name};let paths=layoutPaths(detectLayout(repoDir)),cloneRels=capabilityCloneFiles(repoDir,paths,cap2),scan=scanDest({repoDir,projectRoot:cwd,rels:cloneRels});if(scan.unsafe.length>0){let first=scan.unsafe[0],more=scan.unsafe.length>1?` (and ${scan.unsafe.length-1} more under the same capability)`:"";return{kind:"error",message:`Refusing to add ${cap2.name}: \`${first.link}\` in your project is a symlink, and \`${first.rel}\` sits under it${more}. \`pharn add\` copies the whole capability directory, which would write THROUGH that link and replace files it points at \u2014 possibly outside your project \u2014 and those cannot be backed up. Replace the symlink with a real directory (or move it aside), then re-run \`pharn add ${cap2.name}\`.`}}if(scan.drifted.length>0){let backupDir=createBackup(cwd,scan.drifted);printBackupNotice({dir:backupDir,saved:scan.drifted.length,action:"overwriting",gitignored:backupDirIgnored(cwd)})}installCapabilityDirs(repoDir,cwd,[{name:cap2.name,role:cap2.role}]);let version=readSkillsVersion(repoDir),stamp=addStamp(config,version,sha),capabilities=[...existing,{name:cap2.name,role:cap2.role,source:"manual"}];return await mergeCapabilityRecords(cwd,config,cloneRels,stamp.skillsVersion,stamp.commit),await writePharnConfig(cwd,{...config,...stamp,capabilities}),{kind:"added",name:cap2.name,version,stamp}}async function mergeCapabilityRecords(cwd,config,cloneRels,skillsVersion,commit){let{records}=recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit});if(records===null)return;let added=buildRecords(cwd,cloneRels);await writeRecords(cwd,{skillsVersion,commit,files:mergeRecords(records,added)})}import{confirm as confirm2,groupMultiselect as groupMultiselect2,intro as intro3,isCancel as isCancel4,log as log9,outro as outro4}from"@clack/prompts";async function runRemove(arg){intro3("pharn remove");let cwd=process.cwd(),config=loadArchetypeConfigOrExit(cwd);try{await removeCapability(cwd,config,arg)}catch(err){throw err instanceof ProjectLockedError&&(logError(err.message),process.exit(1)),err instanceof RemoveBackupError&&(logError(err.message),process.exit(1)),err instanceof SymlinkedTargetError&&(logError(err.message),process.exit(1)),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){let installed2=config.capabilities??[];if(arg===void 0){await runRemovePicker(cwd,config,installed2);return}await removeNamed(cwd,config,installed2,arg)}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,config){return recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit}).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[key3,hash]of Object.entries(records))prefixes.some(prefix=>key3.startsWith(prefix))?dropped++:kept[key3]=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";log9.warn(`${names} ${one?"is":"are"} selected automatically for your archetypes, so ${one?"it comes":"they come"} back: the next \`pharn update\` that re-applies your install \u2014 at the latest the one that moves to a new pharn-oss version \u2014 reinstalls ${pronoun} and names ${pronoun} in its report. Until then \`pharn update\` may answer "Already up to date" and leave ${pronoun} removed; \`pharn update --force\` reinstalls ${pronoun} now.`)}async function removeNamed(cwd,config,installed2,address){let parsed=parseCapabilityArg(address);parsed.error&&(logError(parsed.error),process.exit(1));let matches=installed2.filter(c=>c.name===parsed.name&&(parsed.role===void 0||c.role===parsed.role));if(matches.length===0){let valid=installed2.map(c=>`${c.role}:${c.name}`).sort(),hint=valid.length?` Installed: ${valid.join(", ")}.`:" No capabilities are installed.";logError(`"${address}" is not an installed capability.${hint} Nothing was removed.`),process.exit(1)}matches.length>1&&(logError(`"${parsed.name}" is ambiguous \u2014 use ${matches.map(m=>`${m.role}:${m.name}`).join(" or ")}.`),process.exit(1));let target=matches[0],paths=layoutPaths(configLayout(config));refuseSymlinkedTargets(cwd,paths,[target]);let note9=await withProjectLock(cwd,"remove",async()=>{assertConfigUnchanged(cwd,config,"remove"),refuseSymlinkedTargets(cwd,paths,[target]);let records=readRecordsBaseline(cwd,config);backupBeforeDelete(cwd,paths,[target],records);let existed=deleteCapabilityDir(cwd,paths,target);return await pruneCapabilityRecords(cwd,config,paths,[target],records),await writePharnConfig(cwd,{...config,capabilities:installed2.filter(c=>!(c.name===target.name&&c.role===target.role))}),existed?"":color_default.dim(" (its files were already gone)")});warnIfAutoSelected([target]),outro4(`${color_default.green("\u2714")} Removed ${target.name} (${target.role})${note9}`)}async function runRemovePicker(cwd,config,installed2){if(installed2.length===0){outro4("No capabilities are installed.");return}interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY})||(logError("Specify a capability to remove (e.g. `pharn remove a11y`), or run `pharn remove` in an interactive terminal to pick from a list."),process.exit(1));let{groups}=buildRemoveSelection(installed2),picked=await groupMultiselect2({message:"Select capabilities to remove",options:groups,required:!1,selectableGroups:!1});isCancel4(picked)&&cancelAndExit();let values=picked;if(values.length===0){outro4("Nothing selected. No capabilities were removed.");return}let targets=[];for(let value of values){let parsed=parseCapabilityArg(value),target=installed2.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 confirm2({message:`Remove ${targets.length} ${plural2(targets.length)}: ${targets.map(t=>`${t.name} (${t.role})`).join(", ")}?`,initialValue:!1});(isCancel4(ok)||ok!==!0)&&cancelAndExit(),await withProjectLock(cwd,"remove",async()=>{assertConfigUnchanged(cwd,config,"remove"),refuseSymlinkedTargets(cwd,paths,targets);let records=readRecordsBaseline(cwd,config);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:installed2.filter(c=>!removed.has(`${c.role}:${c.name}`))})}),warnIfAutoSelected(targets),outro4(`${color_default.green("\u2714")} Removed ${targets.length} ${plural2(targets.length)}.`)}function plural2(n){return n===1?"capability":"capabilities"}function key2(cap2){return`${cap2.role}:${cap2.name}`}function mergeCapabilities(selection,previous,frozen){let resolved=new Set(selection.selected.map(key2)),inIndex=new Set([...selection.selected.map(key2),...selection.skipped.map(key2)]),previousSource=new Map,seenPrevious=new Set;for(let cap2 of previous){let k=key2(cap2);seenPrevious.has(k)||(seenPrevious.add(k),previousSource.set(k,cap2.source))}let capabilities=[],changes=[];for(let sel of selection.selected){let k=key2(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=key2(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}}var LEGACY_MODEL_ALIASES=new Map([["opus-4-8","opus"],["sonnet-5","sonnet"],["fable-5","fable"],["haiku-4-5","haiku"]]),LEGACY_DEFAULTS=[JSON.stringify({default:{model:"sonnet-5",effort:"high"},stages:{plan:{model:"opus-4-8",effort:"max"},review:{model:"opus-4-8",effort:"high"}}}),JSON.stringify({default:{model:"sonnet-5",effort:"high"},stages:{plan:{model:"opus-4-8",effort:"max"},review:{model:"fable-5",effort:"max"}}})];function isLegacyDefault(block){return block!==void 0&&LEGACY_DEFAULTS.includes(JSON.stringify(block))}function convertLegacyModels(block){if(!isPlainObject(block))return{block,changes:[],leftovers:[]};let changes=[],leftovers=[],next=block;if(Object.hasOwn(next,"default")){let{default:moved,...rest}=next,stages2=next.stages;stages2==null?(next={...rest,stages:{default:moved}},changes.push("moved `models.default` into `models.stages.default`")):isPlainObject(stages2)&&!Object.hasOwn(stages2,"default")?(next={...rest,stages:{default:moved,...stages2}},changes.push("moved `models.default` into `models.stages.default`")):leftovers.push(isPlainObject(stages2)?"`models.default` was left where it is: `models.stages.default` is already set, and pharn-oss reads only that one":"`models.default` was left where it is: `models.stages` is not an object, so it cannot move into it")}let stages=next.stages;if(isPlainObject(stages)){let mapped=!1,converted=Object.fromEntries(Object.entries(stages).map(([name,entry])=>{if(!isPlainObject(entry)||typeof entry.model!="string")return[name,entry];let alias=LEGACY_MODEL_ALIASES.get(entry.model);return alias===void 0?[name,entry]:(mapped=!0,changes.push(`stage ${JSON.stringify(name)} model ${JSON.stringify(entry.model)} \u2192 ${JSON.stringify(alias)}`),[name,{...entry,model:alias}])}));mapped&&(next={...next,stages:converted})}return{block:changes.length>0?next:block,changes,leftovers}}function needsModelsConversion(block){return convertLegacyModels(block).changes.length>0}function modelsMigrationPending(block,recorded){return needsModelsConversion(block)&&(recorded===null||modelsRecordHash(block)!==recorded)}function decideModelsUpdate(input){let{current,upstream,recorded,recordsAvailable,force}=input,none={label:null,replacedLegacyDefault:!1,backup:!1,conversion:null,problems:[],upstreamReasons:[]};if(upstream.kind!=="ok"){let kept=keep(current),pharns=current!==void 0&&(isLegacyDefault(current)||recorded!==null&&modelsRecordHash(current)===recorded);return{...none,...kept,outcome:upstream.kind==="absent"?"upstream-absent":"upstream-invalid",nextRecord:pharns?modelsRecordHash(kept.next):recorded,upstreamReasons:upstream.kind==="invalid"?upstream.reasons:[]}}let latestHash=modelsRecordHash(upstream.block),diskHash=current===void 0?null:modelsRecordHash(current),legacyDefault=isLegacyDefault(current),decision=decideFileAction({diskHash,latestHash,recordedHash:legacyDefault?diskHash:recorded,recordsAvailable:legacyDefault||recordsAvailable,force});return decision.action==="write"?{...none,outcome:decision.forced?"forced":decision.label==="restored"?"restored":"updated",label:decision.forced?decision.label:null,replacedLegacyDefault:legacyDefault,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,conversion:null,problems:[]};let conversion=convertLegacyModels(current),check=checkModelsBlock(conversion.block);return{next:conversion.block,conversion:conversion.changes.length>0?conversion:null,problems:[...conversion.leftovers,...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}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,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{records,note:recordsNote}=recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit}),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))?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?.report.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 key3=`${cap2.role}:${cap2.name}`;return frozen.has(key3)||previouslyFrozen.has(key3)&&hasSkippedFile(cap2)}).map(cap2=>`${cap2.role}:${cap2.name}`))].sort();return{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:rootMigration?.report??null,rootMoveBackups:rootMigration?.backups??[],gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,prettierignorePaths)},apply:{expected,records,plan,models,configCapabilities,frozen,frozenRecords,orphanRecords:orphanScan.records,nextSkillsVersion,nextCommit,frozenKeys,removalPaths,rootMoveBackups:rootMigration?.backups??[],prettierignorePaths}}}import{log as log10,note as note4,outro as outro5}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 reportRootMigration(m,result){let lines=m===null?null:rootMigrationNoteLines(m,result);lines&¬e4(lines.join(`
|
|
52
|
+
`),"ROOT MIGRATION")}var FORCEABLE_SKIPS=new Set(["modified","unrecorded","unverifiable","held"]),MAX_UNIT_BLOCKERS=20;function executableUnitLines(hold,preview){if(hold===null)return null;let shown2=hold.blocking.slice(0,MAX_UNIT_BLOCKERS),more=hold.blocking.length-shown2.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")+":",...shown2.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.",""," To upgrade the unit: revert the files above, or run",` \`pharn update --force\` (it backs them up to ${BACKUP_DIR}/ first).`]}function reportExecutableUnit(hold,preview){let lines=executableUnitLines(hold,preview);lines&¬e4(lines.join(`
|
|
53
|
+
`),"EXECUTABLE UNIT")}function reportOutcome(outcome,force){let{plan,recordsNote,versionWithheld}=outcome,{counts}=plan;recordsNote&&log10.warn(`\u26A0 ${recordsNote}`),reportCapabilityChanges(outcome.capabilityChanges,outcome.removals,!1),reportModels(outcome.models,outcome.modelsFloor,outcome.backup);let hookLines=outcome.hookWiring?hookWiringLines(outcome.hookWiring):null;hookLines&¬e4(hookLines.join(`
|
|
54
|
+
`),"HOOKS"),reportAbsentSurfaces(outcome.absentUpstream??[]),reportExecutableUnit(plan.held,!1);let forceable=reportSkipped(plan.skipped,!1);reportOrphans(outcome.orphans),reportRootMigration(outcome.rootMigration,outcome.rootMigrationResult),reportLayoutWarnings(outcome.abandonedLayout,outcome.featuresReadmeRelocation,!1),versionWithheld&&log10.warn(`${counts.skipped} file(s) were skipped, so your install is still recorded as skills v${outcome.recordedVersion} (upstream is v${outcome.installedVersion}) \u2014 resolve them${forceable?", or re-run with --force,":""} to finish the upgrade.`);let summary=`updated ${counts.updated} \xB7 restored ${counts.restored} \xB7 unchanged ${counts.ok}`+(force?` \xB7 forced ${counts.forced}`:"")+` \xB7 skipped ${counts.skipped}`;outro5(`${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&¬e4(lines.join(`
|
|
54
55
|
`),"NOT SHIPPED")}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.")),note4(lines.join(`
|
|
55
56
|
`),"SKIPPED")}return forceable}function reportOrphans(orphans){let lines=orphanNoteLines(orphans);lines&¬e4(lines.join(`
|
|
56
57
|
`),"ORPHANED")}function reportLayoutWarnings(abandonedLayout,featuresReadmeRelocation,preview){abandonedLayout==="flat"?log10.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"&&log10.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&&log10.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&&log10.warn(`\u26A0 ${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)},...["modified","unrecorded","unverifiable"].map(label=>({heading:`WOULD OVERWRITE (--force) \u2014 ${label}`,rels:writes.filter(f=>f.forced&&f.label===label).map(f=>f.rel)}))],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),...r.rootMoveBackups])],migrates=(r.rootMigration?.docs??[]).some(d=>d.action==="delete")||(r.rootMigration?.moves??[]).some(m=>m.action==="move"),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}`,""),writes.length===0&&deletes.length===0&&!migrates&&!gitignorePending(r.gitignore)&&!prettierignorePending(r.prettierignore)&&lines.push(" Nothing would be written.",""),lines.push(` UNCHANGED ${r.counts.ok} file(s) \xB7 SKIPPED ${r.counts.skipped} file(s)`),channel!==channelOf(config)&&lines.push("",` Would record channel: ${channel}`),note4(lines.join(`
|
|
57
58
|
`),"PLAN"),gitignore?.warn&&log10.warn(gitignore.text),prettierignore?.warn&&log10.warn(prettierignore.text),reportCapabilityChanges(r.capabilityChanges,r.removals,!0),reportModels(r.models,r.modelsFloor,null,!0);let hookLines=hookWiringLines(r.hookWiring);hookLines&¬e4(hookLines.join(`
|
|
58
|
-
`),"HOOKS"),reportAbsentSurfaces(r.absentUpstream);let forceable=reportSkipped(r.skipped,!0);reportOrphans(r.orphans),reportRootMigration(r.rootMigration,null),reportLayoutWarnings(r.abandonedLayout,r.featuresReadmeRelocation,!0),r.versionWithheld?(log10.warn(`${r.counts.skipped} file(s) would be skipped, so your install would stay recorded as skills v${r.recordedVersion} (upstream is v${r.installedVersion}) \u2014 resolve them${forceable?", or run with --force,":""} to finish the upgrade.`),r.pendingSkillsVersion!==null&&log10.info(`Would record skills v${r.pendingSkillsVersion} as pending, so \`pharn add\` installs at it.`)):log10.info(`Would record skills v${r.recordedVersion}.`),r.frozenCapabilities.length>0&&log10.info(`Would keep unread upstream capabilities as they are: ${r.frozenCapabilities.join(", ")}.`),outro5(`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&&log10.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",moving:"moved","overwriting and moving":"overwritten or moved","removing and moving":"removed or moved","overwriting, removing and moving":"overwritten, removed or moved"},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 key3=`${cap2.role}:${cap2.name}`,removal=removalOf.get(key3);lines.push(removal===void 0?` ${key3}`:` ${key3} \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.`))),note4(lines.join(`
|
|
59
|
+
`),"HOOKS"),reportAbsentSurfaces(r.absentUpstream),reportExecutableUnit(r.executableUnit,!0);let forceable=reportSkipped(r.skipped,!0);reportOrphans(r.orphans),reportRootMigration(r.rootMigration,null),reportLayoutWarnings(r.abandonedLayout,r.featuresReadmeRelocation,!0),r.versionWithheld?(log10.warn(`${r.counts.skipped} file(s) would be skipped, so your install would stay recorded as skills v${r.recordedVersion} (upstream is v${r.installedVersion}) \u2014 resolve them${forceable?", or run with --force,":""} to finish the upgrade.`),r.pendingSkillsVersion!==null&&log10.info(`Would record skills v${r.pendingSkillsVersion} as pending, so \`pharn add\` installs at it.`)):log10.info(`Would record skills v${r.recordedVersion}.`),r.frozenCapabilities.length>0&&log10.info(`Would keep unread upstream capabilities as they are: ${r.frozenCapabilities.join(", ")}.`),outro5(`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&&log10.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",moving:"moved","overwriting and moving":"overwritten or moved","removing and moving":"removed or moved","overwriting, removing and moving":"overwritten, removed or moved"},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 key3=`${cap2.role}:${cap2.name}`,removal=removalOf.get(key3);lines.push(removal===void 0?` ${key3}`:` ${key3} \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.`))),note4(lines.join(`
|
|
59
60
|
`),"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))),note4(lines.join(`
|
|
60
|
-
`),"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(...models.replacedLegacyDefault?[preview?"Would replace the models block an earlier pharn wrote with pharn-oss's.":"Replaced the models block an earlier pharn wrote with pharn-oss's.","Its model ids, such as opus-4-8, are rejected by Claude Code","and by pharn-oss's checker."]:[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.conversion===null&&models.problems.length===0)return[];lines.push("pharn-oss ships no models block, so yours is kept.");break}return models.conversion!==null&&lines.push("",preview?"Would convert your models block from the format pharn wrote before 0.7.0,":"Converted your models block from the format pharn wrote before 0.7.0,","keeping your values:",...models.conversion.changes.map(quoted)),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`;default:return"UNREADABLE \u2014 not a regular readable file"}}import{confirm as confirm3,intro as intro4,isCancel as isCancel5,log as log11,note as note5,outro as outro6,spinner as spinner4}from"@clack/prompts";var UPDATE_SCHEMA_VERSION=1,MAX_REASON2=300,MAX_UNKNOWN_FIELD2=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:p.rootMigration.moves.map(m=>({from:m.from,to:m.to,action:m.action})),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,...p.rootMoveBackups])],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},models:{outcome:p.models.outcome,label:p.models.label,replacedLegacyDefault:p.models.replacedLegacyDefault,backup:p.models.backup,conversion:p.models.conversion===null?null:{changes:capAll(p.models.conversion.changes,MAX_REASON2),leftovers:capAll(p.models.conversion.leftovers,MAX_REASON2)},problems:capAll(p.models.problems,MAX_REASON2),upstreamReasons:capAll(p.models.upstreamReasons,MAX_REASON2)},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_FIELD2)}))}:{},frozenCapabilities:[...p.frozenCapabilities],unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD2),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD2),reason:cap(u.reason,MAX_UNKNOWN_FIELD2)})),recordsNote:p.recordsNote===null?null:cap(p.recordsNote,MAX_REASON2),...p.orphans.length>0?{orphans:p.orphans.map(o=>({path:o.path,state:o.state,...o.reason!==void 0?{reason:cap(o.reason,MAX_REASON2)}:{}}))}:{},...gitignoreKey2(p.gitignore),...prettierignoreKey2(p.prettierignore)}}function prettierignoreKey2(plan){let report=prettierignoreReport(plan);return report===null?{}:{prettierignore:report}}function gitignoreKey2(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}}import{lstatSync as lstatSync15}from"node:fs";function findMissingInstalled(cwd,config,records){let paths=layoutPaths(configLayout(config));for(let cap2 of config.capabilities??[]){let rel=`${capabilitySubtree(paths,cap2.role)}/${cap2.name}`;if(provablyAbsent2(cwd,rel))return rel}if(records===null)return null;for(let rel of Object.keys(records).sort())if(rel!==MODELS_RECORD_KEY&&provablyAbsent2(cwd,rel))return rel;return null}function provablyAbsent2(base,rel){try{return findSymlinkComponent(base,rel)!==null?!1:lstatSync15(safeJoin(base,rel),{throwIfNoEntry:!1})===void 0}catch{return!1}}async function runUpdate(opts={}){let dryRun=opts.dryRun??!1,json=opts.json??!1,compact=opts.compact??!1;json&&!dryRun&&(reportFatalPlain("--json is only available with --dry-run."),process.exit(1)),compact&&!json&&(reportFatalPlain("--compact is only available with --json."),process.exit(1)),json||intro4(dryRun?"pharn update --dry-run":"pharn update"),runNodePrereq("update",{json});let cwd=process.cwd(),config=loadArchetypeConfigOrExit(cwd,{json}),yes=opts.yes??!1;!dryRun&&!yes&&!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY})&&(logError("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`)."),process.exit(1));let channelNotice=defaultChannelNotice(config,opts.ref);channelNotice!==null&&!json&&log11.info(channelNotice),await runArchetypeUpdate(config,cwd,opts.force??!1,yes,opts.ref??channelOf(config),dryRun,json,compact)}async function runArchetypeUpdate(config,cwd,force,yes,channel,dryRun,json,compact){let proxyNotice=detectProxyNotice(process.env);proxyNotice&&(json?logErrorPlain(proxyNoticeMessage(proxyNotice)):log11.warn(proxyNoticeMessage(proxyNotice)));let s=json?silentSpinner2():spinner4();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){s.stop("Failed to check for updates"),(json?reportFatalPlain:reportFatal)(errorMessage(err),{err}),process.exit(1)}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)}, every file you did not edit at v${terminalSafe(aheadOf)}`;outro6(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}let current=config.skillsVersion===latest,recheckFrozen=(config.frozenCapabilities??[]).length>0,recordsRead=readRecords(cwd),recordsStamp={skillsVersion:config.skillsVersion,commit:config.commit},baselineRecords=recordsBaseline(recordsRead,recordsStamp).records,convertModels=modelsMigrationPending(config.models,baselineRecords?.[MODELS_RECORD_KEY]??null),switchChannel=channel!==channelOf(config),missing=current&&!force?findMissingInstalled(cwd,config,baselineRecords):null,staleRecords=current&&!force&&recordsStampStale(recordsRead,recordsStamp),rootDoc=current&&!force?pendingRootMigration(cwd,config,baselineRecords):null,gitignoreMissing=current&&!force&&gitignorePending(planGitignore(cwd)),prettierignoreMissing=current&&!force&&baselineRecords!==null&&prettierignorePending(planPrettierignore(cwd,Object.keys(baselineRecords)));if(current&&!force&&!recheckFrozen&&!convertModels&&!switchChannel&&missing===null&&!staleRecords&&rootDoc===null&&!gitignoreMissing&&!prettierignoreMissing){if(json){emitEarlyReturn("up-to-date");return}outro6(`Already up to date (skills v${terminalSafe(config.skillsVersion)}).`);return}if(json||note5([current?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."),...convertModels?[color_default.dim(" Your models block is in the format pharn wrote before 0.7.0 \u2014 this run converts it.")]:[],...missing!==null?[color_default.dim(` ${terminalSafe(missing)} is missing \u2014 this run re-applies the install, restoring it if upstream still ships it.`)]:[],...rootDoc!==null?[color_default.dim(` ${terminalSafe(rootDoc)} is still at the project root \u2014 this run re-applies the install, which keeps it under pharn/.`)]:[],...gitignoreMissing?[color_default.dim(" .gitignore does not yet keep PHARN's run state and backups out of git \u2014 this run re-applies the install and adds them.")]:[],...prettierignoreMissing?[color_default.dim(" .prettierignore does not yet cover the files pharn installs and rewrites \u2014 this run re-applies the install and adds them.")]:[],...staleRecords?[color_default.dim(` ${RECORDS_FILE} is stamped for a different install state than pharn.config.json (an interrupted run?) \u2014 this run re-applies the install and records it again.`)]:[],color_default.dim(" Re-resolves your archetypes against the latest capabilities and re-copies them."),...dryRun?[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(`
|
|
61
|
-
`)),dryRun){await runDryRun(config,cwd,force,channel,source,json,latest,compact);return}let pre=spinner4();pre.start(`Planning from ${REPO_URL}`);let repo=await fetchRepo(source).catch(err=>{pre.stop("Update failed"),reportFatal(errorMessage(err),{err}),process.exit(1)}),outcome=null,cancelled=!1,backupRef={current:null},spinnerRef={current:null},refusalRef={current:null},failure=null;try{let snapshot=planFromClone(repo,config,cwd,force,channel,m=>log11.warn(m));if(pre.stop(planStopMessage(snapshot)),snapshot.kind==="refused")refusalRef.current=snapshot.refusal;else if(snapshot.kind==="failed")failure=snapshot.failure;else{let confirmed=snapshot.planned.report;reportCapabilityChanges(confirmed.capabilityChanges,confirmed.removals,!0),reportRootMigration(confirmed.rootMigration,null);let deletes=confirmed.removals.filter(r=>r.present).length;if(!yes){let ok=await confirm3({message:confirmMessage(force,deletes),initialValue:deletes===0});cancelled=isCancel5(ok)||ok!==!0}cancelled||(outcome=await applyUnderLock(confirmed,{config,cwd,force,channel,repo,backupRef,spinnerRef,refusalRef}))}}catch(err){err instanceof ProjectLockedError||err instanceof CapabilityRemovalError?(spinnerRef.current?.stop("Update refused"),refusalRef.current=err.message):(spinnerRef.current?.stop("Update failed"),failure={err})}finally{repo.cleanup()}cancelled&&cancelAndExit();let refusal3=refusalRef.current;refusal3&&(reportFatal(refusal3),process.exit(1)),(failure||!outcome)&&(failure?reportFatal(errorMessage(failure.err),failure):reportFatal("Update failed."),backupRef.current&&reportBackup(backupRef.current,{aborted:!0}),process.exit(1));let legacyBackups=legacyBackupNotice(cwd);legacyBackups&&log11.info(legacyBackups);let gitignore=outcome.gitignore===void 0?null:gitignoreLines(outcome.gitignore);gitignore?.warn?log11.warn(gitignore.text):gitignore!==null&&log11.info(gitignore.text);let prettierignore=outcome.prettierignore===void 0?null:prettierignoreLines(outcome.prettierignore);prettierignore?.warn?log11.warn(prettierignore.text):prettierignore!==null&&log11.info(prettierignore.text),reportOutcome(outcome,force),rootMigrationFailed(outcome.rootMigration,outcome.rootMigrationResult)&&(process.exitCode=1)}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"}.`}function membershipKeys(r){return[...r.capabilityChanges.map(c=>`${c.reason} ${c.cap.role}:${c.cap.name}`),...r.removals.filter(x=>x.present).map(x=>`delete ${x.dir}/`),...(r.rootMigration?.docs??[]).filter(d=>d.action==="delete").map(d=>`delete ${d.rel}`),...(r.rootMigration?.moves??[]).filter(m=>m.action==="move").map(m=>`move ${m.from} \u2192 ${m.to}`)]}function membershipDrift(confirmed,now){let before=membershipKeys(confirmed),after=membershipKeys(now);if(before.length===after.length&&before.every((key3,i)=>key3===after[i]))return null;let shown2=before.filter(key3=>!after.includes(key3)),added=after.filter(key3=>!before.includes(key3)),list=keys=>keys.length>0?keys.join(", "):"(nothing)";return`The capabilities this update would change are no longer what you confirmed \u2014 shown but not planned now: ${list(shown2)}; planned now but not shown: ${list(added)}. Nothing was changed. Run \`pharn update\` again.`}async function applyUnderLock(confirmed,ctx){let{config,cwd,force,channel,repo}=ctx,{backupRef,spinnerRef,refusalRef}=ctx;return withProjectLock(cwd,"update",async()=>{assertConfigUnchanged(cwd,config,"update");let s2=spinner4();spinnerRef.current=s2,s2.start("Updating");let planned=buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel}),drift=membershipDrift(confirmed,planned.report);if(drift!==null)return s2.stop("Update refused"),refusalRef.current=drift,null;let applied=await applyPlannedUpdate(planned,config,cwd,repo.dir,channel,backup=>{backupRef.current=backup,s2.stop("Backup written"),reportBackup(backup,{aborted:!1});let s3=spinner4();spinnerRef.current=s3,s3.start("Writing files")});return spinnerRef.current.stop(applied.plan.writes.length?"Capabilities updated":"Nothing to write"),applied})}async function applyPlannedUpdate(planned,config,cwd,repoDir,channel,onBackup){let{report,apply}=planned,{expected,records,plan,models,configCapabilities}=apply,removalBackups2=report.removals.flatMap(r=>r.backups),backupRels=[...new Set([...report.backups,...removalBackups2,...apply.rootMoveBackups])],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,apply.rootMoveBackups.length>0),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;try{written=applyWrites({projectRoot:cwd,expected,writes:plan.writes})}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),retired=new Set(docResult.deleted),orphanRecords=Object.fromEntries(Object.entries(apply.orphanRecords).filter(([rel])=>!retired.has(rel)));await writeRecords(cwd,{skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,files:{...apply.frozenRecords,...orphanRecords,...plan.nextRecords,...buildRecords(cwd,written),...models.nextRecord!==null?{[MODELS_RECORD_KEY]:models.nextRecord}:{}}});let{pendingSkillsVersion:_previousPending,frozenCapabilities:_previousFrozen,ref:_previousRef,...rest}=config;await writePharnConfig(cwd,{...rest,pharnVersion:PHARN_VERSION,skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,...channel==="latest"?{ref:"latest"}:{},...report.pendingSkillsVersion!==null?{pendingSkillsVersion:report.pendingSkillsVersion}:{},...apply.frozenKeys.length>0?{frozenCapabilities:apply.frozenKeys}:{},capabilities:configCapabilities,layout:report.layout,updatedAt:new Date().toISOString(),models:models.next});let gitignore=await applyGitignore(cwd),prettierignore=await applyPrettierignore(cwd,apply.prettierignorePaths),moveResult=migration===null?{moved:[],failed:[]}:applyRootMoves(cwd,migration.moves);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,...moveResult}}}function checkMinCli(repoDir,warn=message=>log11.warn(message)){let gate=minCliGate(repoDir,PHARN_VERSION);return gate.warning&&warn(gate.warning),{refusal:gate.refusal??null}}function silentSpinner2(){return{start:()=>{},stop:()=>{}}}function emitJson(report){console.log(serializeJsonReport(report))}function planFromClone(repo,config,cwd,force,channel,warn){try{let refusal3=checkMinCli(repo.dir,warn).refusal;return refusal3?{kind:"refused",refusal:refusal3}:{kind:"planned",planned:buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel,onUnknownWarning:warn})}}catch(err){return err instanceof CapabilityRemovalError?{kind:"refused",refusal:err.message}:{kind:"failed",failure:{err}}}}function planStopMessage(outcome){switch(outcome.kind){case"planned":return"Plan ready";case"refused":return"Update refused";case"failed":return"Planning failed"}}async function fetchAndPlan(config,cwd,force,channel,source,ui){let{spin,warn}=ui;spin.start(`Planning from ${REPO_URL}`);let repo;try{repo=await fetchRepo(source)}catch(err){return spin.stop("Planning failed"),{kind:"failed",failure:{err}}}try{let outcome=planFromClone(repo,config,cwd,force,channel,warn);return spin.stop(planStopMessage(outcome)),outcome}finally{repo.cleanup()}}async function runDryRun(config,cwd,force,channel,source,json,latest,compact){let outcome=await fetchAndPlan(config,cwd,force,channel,source,{spin:json?silentSpinner2():spinner4(),warn:json?message=>logErrorPlain(message):message=>log11.warn(message)}),fatal=json?reportFatalPlain:reportFatal;outcome.kind==="refused"&&(fatal(outcome.refusal),process.exit(1)),outcome.kind==="failed"&&(outcome.failure?fatal(errorMessage(outcome.failure.err),outcome.failure):fatal("Update failed."),process.exit(1));let{report}=outcome.planned;if(json){emitJson(buildUpdateReport({status:"planned",force,channel,currentChannel:channelOf(config),source,installed:config.skillsVersion,latest,archetypes:config.archetypes??[],plan:report,compact}));return}let legacyBackups=legacyBackupNotice(cwd);legacyBackups&&log11.info(legacyBackups),reportDryRun(report,force,channel,config)}import{intro as intro5,note as note6,outro as outro7}from"@clack/prompts";async function runList(opts={}){let json=opts.json??!1,cwd=process.cwd();json||intro5("pharn list");let config=loadArchetypeConfigOrExit(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);note6(lines.join(`
|
|
61
|
+
`),"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(...models.replacedLegacyDefault?[preview?"Would replace the models block an earlier pharn wrote with pharn-oss's.":"Replaced the models block an earlier pharn wrote with pharn-oss's.","Its model ids, such as opus-4-8, are rejected by Claude Code","and by pharn-oss's checker."]:[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.conversion===null&&models.problems.length===0)return[];lines.push("pharn-oss ships no models block, so yours is kept.");break}return models.conversion!==null&&lines.push("",preview?"Would convert your models block from the format pharn wrote before 0.7.0,":"Converted your models block from the format pharn wrote before 0.7.0,","keeping your values:",...models.conversion.changes.map(quoted)),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 as confirm3,intro as intro4,isCancel as isCancel5,log as log11,note as note5,outro as outro6,spinner as spinner4}from"@clack/prompts";var UPDATE_SCHEMA_VERSION=1,MAX_REASON2=300,MAX_UNKNOWN_FIELD2=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:p.rootMigration.moves.map(m=>({from:m.from,to:m.to,action:m.action})),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,...p.rootMoveBackups])],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]}}:{},models:{outcome:p.models.outcome,label:p.models.label,replacedLegacyDefault:p.models.replacedLegacyDefault,backup:p.models.backup,conversion:p.models.conversion===null?null:{changes:capAll(p.models.conversion.changes,MAX_REASON2),leftovers:capAll(p.models.conversion.leftovers,MAX_REASON2)},problems:capAll(p.models.problems,MAX_REASON2),upstreamReasons:capAll(p.models.upstreamReasons,MAX_REASON2)},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_FIELD2)}))}:{},frozenCapabilities:[...p.frozenCapabilities],unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD2),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD2),reason:cap(u.reason,MAX_UNKNOWN_FIELD2)})),recordsNote:p.recordsNote===null?null:cap(p.recordsNote,MAX_REASON2),...p.orphans.length>0?{orphans:p.orphans.map(o=>({path:o.path,state:o.state,...o.reason!==void 0?{reason:cap(o.reason,MAX_REASON2)}:{}}))}:{},...gitignoreKey2(p.gitignore),...prettierignoreKey2(p.prettierignore)}}function prettierignoreKey2(plan){let report=prettierignoreReport(plan);return report===null?{}:{prettierignore:report}}function gitignoreKey2(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}}import{lstatSync as lstatSync15}from"node:fs";function findMissingInstalled(cwd,config,records){let paths=layoutPaths(configLayout(config));for(let cap2 of config.capabilities??[]){let rel=`${capabilitySubtree(paths,cap2.role)}/${cap2.name}`;if(provablyAbsent2(cwd,rel))return rel}if(records===null)return null;for(let rel of Object.keys(records).sort())if(rel!==MODELS_RECORD_KEY&&provablyAbsent2(cwd,rel))return rel;return null}function provablyAbsent2(base,rel){try{return findSymlinkComponent(base,rel)!==null?!1:lstatSync15(safeJoin(base,rel),{throwIfNoEntry:!1})===void 0}catch{return!1}}async function runUpdate(opts={}){let dryRun=opts.dryRun??!1,json=opts.json??!1,compact=opts.compact??!1;json&&!dryRun&&(reportFatalPlain("--json is only available with --dry-run."),process.exit(1)),compact&&!json&&(reportFatalPlain("--compact is only available with --json."),process.exit(1)),json||intro4(dryRun?"pharn update --dry-run":"pharn update"),runNodePrereq("update",{json});let cwd=process.cwd(),config=loadArchetypeConfigOrExit(cwd,{json}),yes=opts.yes??!1;!dryRun&&!yes&&!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY})&&(logError("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`)."),process.exit(1));let channelNotice=defaultChannelNotice(config,opts.ref);channelNotice!==null&&!json&&log11.info(channelNotice),await runArchetypeUpdate(config,cwd,opts.force??!1,yes,opts.ref??channelOf(config),dryRun,json,compact)}async function runArchetypeUpdate(config,cwd,force,yes,channel,dryRun,json,compact){let proxyNotice=detectProxyNotice(process.env);proxyNotice&&(json?logErrorPlain(proxyNoticeMessage(proxyNotice)):log11.warn(proxyNoticeMessage(proxyNotice)));let s=json?silentSpinner2():spinner4();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){s.stop("Failed to check for updates"),(json?reportFatalPlain:reportFatal)(errorMessage(err),{err}),process.exit(1)}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)}, every file you did not edit at v${terminalSafe(aheadOf)}`;outro6(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}let current=config.skillsVersion===latest,recheckFrozen=(config.frozenCapabilities??[]).length>0,recordsRead=readRecords(cwd),recordsStamp={skillsVersion:config.skillsVersion,commit:config.commit},baselineRecords=recordsBaseline(recordsRead,recordsStamp).records,convertModels=modelsMigrationPending(config.models,baselineRecords?.[MODELS_RECORD_KEY]??null),switchChannel=channel!==channelOf(config),missing=current&&!force?findMissingInstalled(cwd,config,baselineRecords):null,staleRecords=current&&!force&&recordsStampStale(recordsRead,recordsStamp),rootDoc=current&&!force?pendingRootMigration(cwd,config,baselineRecords):null,gitignoreMissing=current&&!force&&gitignorePending(planGitignore(cwd)),prettierignoreMissing=current&&!force&&baselineRecords!==null&&prettierignorePending(planPrettierignore(cwd,Object.keys(baselineRecords)));if(current&&!force&&!recheckFrozen&&!convertModels&&!switchChannel&&missing===null&&!staleRecords&&rootDoc===null&&!gitignoreMissing&&!prettierignoreMissing){if(json){emitEarlyReturn("up-to-date");return}outro6(`Already up to date (skills v${terminalSafe(config.skillsVersion)}).`);return}if(json||note5([current?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."),...convertModels?[color_default.dim(" Your models block is in the format pharn wrote before 0.7.0 \u2014 this run converts it.")]:[],...missing!==null?[color_default.dim(` ${terminalSafe(missing)} is missing \u2014 this run re-applies the install, restoring it if upstream still ships it.`)]:[],...rootDoc!==null?[color_default.dim(` ${terminalSafe(rootDoc)} is still at the project root \u2014 this run re-applies the install, which keeps it under pharn/.`)]:[],...gitignoreMissing?[color_default.dim(" .gitignore does not yet keep PHARN's run state and backups out of git \u2014 this run re-applies the install and adds them.")]:[],...prettierignoreMissing?[color_default.dim(" .prettierignore does not yet cover the files pharn installs and rewrites \u2014 this run re-applies the install and adds them.")]:[],...staleRecords?[color_default.dim(` ${RECORDS_FILE} is stamped for a different install state than pharn.config.json (an interrupted run?) \u2014 this run re-applies the install and records it again.`)]:[],color_default.dim(" Re-resolves your archetypes against the latest capabilities and re-copies them."),...dryRun?[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(`
|
|
62
|
+
`)),dryRun){await runDryRun(config,cwd,force,channel,source,json,latest,compact);return}let pre=spinner4();pre.start(`Planning from ${REPO_URL}`);let repo=await fetchRepo(source).catch(err=>{pre.stop("Update failed"),reportFatal(errorMessage(err),{err}),process.exit(1)}),outcome=null,cancelled=!1,backupRef={current:null},spinnerRef={current:null},refusalRef={current:null},failure=null;try{let snapshot=planFromClone(repo,config,cwd,force,channel,m=>log11.warn(m));if(pre.stop(planStopMessage(snapshot)),snapshot.kind==="refused")refusalRef.current=snapshot.refusal;else if(snapshot.kind==="failed")failure=snapshot.failure;else{let confirmed=snapshot.planned.report;reportCapabilityChanges(confirmed.capabilityChanges,confirmed.removals,!0),reportRootMigration(confirmed.rootMigration,null),reportExecutableUnit(confirmed.executableUnit,!0);let deletes=confirmed.removals.filter(r=>r.present).length;if(!yes){let ok=await confirm3({message:confirmMessage(force,deletes),initialValue:deletes===0});cancelled=isCancel5(ok)||ok!==!0}cancelled||(outcome=await applyUnderLock(confirmed,{config,cwd,force,channel,repo,backupRef,spinnerRef,refusalRef}))}}catch(err){err instanceof ProjectLockedError||err instanceof CapabilityRemovalError?(spinnerRef.current?.stop("Update refused"),refusalRef.current=err.message):(spinnerRef.current?.stop("Update failed"),failure={err})}finally{repo.cleanup()}cancelled&&cancelAndExit();let refusal3=refusalRef.current;refusal3&&(reportFatal(refusal3),process.exit(1)),(failure||!outcome)&&(failure?reportFatal(errorMessage(failure.err),failure):reportFatal("Update failed."),backupRef.current&&reportBackup(backupRef.current,{aborted:!0}),process.exit(1));let legacyBackups=legacyBackupNotice(cwd);legacyBackups&&log11.info(legacyBackups);let gitignore=outcome.gitignore===void 0?null:gitignoreLines(outcome.gitignore);gitignore?.warn?log11.warn(gitignore.text):gitignore!==null&&log11.info(gitignore.text);let prettierignore=outcome.prettierignore===void 0?null:prettierignoreLines(outcome.prettierignore);prettierignore?.warn?log11.warn(prettierignore.text):prettierignore!==null&&log11.info(prettierignore.text),reportOutcome(outcome,force),rootMigrationFailed(outcome.rootMigration,outcome.rootMigrationResult)&&(process.exitCode=1)}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"}.`}function membershipKeys(r){return[...r.capabilityChanges.map(c=>`${c.reason} ${c.cap.role}:${c.cap.name}`),...r.removals.filter(x=>x.present).map(x=>`delete ${x.dir}/`),...(r.rootMigration?.docs??[]).filter(d=>d.action==="delete").map(d=>`delete ${d.rel}`),...(r.rootMigration?.moves??[]).filter(m=>m.action==="move").map(m=>`move ${m.from} \u2192 ${m.to}`)]}function membershipDrift(confirmed,now){let before=membershipKeys(confirmed),after=membershipKeys(now);if(before.length===after.length&&before.every((key3,i)=>key3===after[i]))return null;let shown2=before.filter(key3=>!after.includes(key3)),added=after.filter(key3=>!before.includes(key3)),list=keys=>keys.length>0?keys.join(", "):"(nothing)";return`The capabilities this update would change are no longer what you confirmed \u2014 shown but not planned now: ${list(shown2)}; planned now but not shown: ${list(added)}. Nothing was changed. Run \`pharn update\` again.`}async function applyUnderLock(confirmed,ctx){let{config,cwd,force,channel,repo}=ctx,{backupRef,spinnerRef,refusalRef}=ctx;return withProjectLock(cwd,"update",async()=>{assertConfigUnchanged(cwd,config,"update");let s2=spinner4();spinnerRef.current=s2,s2.start("Updating");let planned=buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel}),drift=membershipDrift(confirmed,planned.report);if(drift!==null)return s2.stop("Update refused"),refusalRef.current=drift,null;let applied=await applyPlannedUpdate(planned,config,cwd,repo.dir,channel,backup=>{backupRef.current=backup,s2.stop("Backup written"),reportBackup(backup,{aborted:!1});let s3=spinner4();spinnerRef.current=s3,s3.start("Writing files")});return spinnerRef.current.stop(applied.plan.writes.length?"Capabilities updated":"Nothing to write"),applied})}async function applyPlannedUpdate(planned,config,cwd,repoDir,channel,onBackup){let{report,apply}=planned,{expected,records,plan,models,configCapabilities}=apply,removalBackups2=report.removals.flatMap(r=>r.backups),backupRels=[...new Set([...report.backups,...removalBackups2,...apply.rootMoveBackups])],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,apply.rootMoveBackups.length>0),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;try{written=applyWrites({projectRoot:cwd,expected,writes:plan.writes})}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),retired=new Set(docResult.deleted),orphanRecords=Object.fromEntries(Object.entries(apply.orphanRecords).filter(([rel])=>!retired.has(rel)));await writeRecords(cwd,{skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,files:{...apply.frozenRecords,...orphanRecords,...plan.nextRecords,...buildRecords(cwd,written),...models.nextRecord!==null?{[MODELS_RECORD_KEY]:models.nextRecord}:{}}});let{pendingSkillsVersion:_previousPending,frozenCapabilities:_previousFrozen,ref:_previousRef,...rest}=config;await writePharnConfig(cwd,{...rest,pharnVersion:PHARN_VERSION,skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,...channel==="latest"?{ref:"latest"}:{},...report.pendingSkillsVersion!==null?{pendingSkillsVersion:report.pendingSkillsVersion}:{},...apply.frozenKeys.length>0?{frozenCapabilities:apply.frozenKeys}:{},capabilities:configCapabilities,layout:report.layout,updatedAt:new Date().toISOString(),models:models.next});let gitignore=await applyGitignore(cwd),prettierignore=await applyPrettierignore(cwd,apply.prettierignorePaths),moveResult=migration===null?{moved:[],failed:[]}:applyRootMoves(cwd,migration.moves);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,...moveResult}}}function checkMinCli(repoDir,warn=message=>log11.warn(message)){let gate=minCliGate(repoDir,PHARN_VERSION);return gate.warning&&warn(gate.warning),{refusal:gate.refusal??null}}function silentSpinner2(){return{start:()=>{},stop:()=>{}}}function emitJson(report){console.log(serializeJsonReport(report))}function planFromClone(repo,config,cwd,force,channel,warn){try{let refusal3=checkMinCli(repo.dir,warn).refusal;return refusal3?{kind:"refused",refusal:refusal3}:{kind:"planned",planned:buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel,onUnknownWarning:warn})}}catch(err){return err instanceof CapabilityRemovalError?{kind:"refused",refusal:err.message}:{kind:"failed",failure:{err}}}}function planStopMessage(outcome){switch(outcome.kind){case"planned":return"Plan ready";case"refused":return"Update refused";case"failed":return"Planning failed"}}async function fetchAndPlan(config,cwd,force,channel,source,ui){let{spin,warn}=ui;spin.start(`Planning from ${REPO_URL}`);let repo;try{repo=await fetchRepo(source)}catch(err){return spin.stop("Planning failed"),{kind:"failed",failure:{err}}}try{let outcome=planFromClone(repo,config,cwd,force,channel,warn);return spin.stop(planStopMessage(outcome)),outcome}finally{repo.cleanup()}}async function runDryRun(config,cwd,force,channel,source,json,latest,compact){let outcome=await fetchAndPlan(config,cwd,force,channel,source,{spin:json?silentSpinner2():spinner4(),warn:json?message=>logErrorPlain(message):message=>log11.warn(message)}),fatal=json?reportFatalPlain:reportFatal;outcome.kind==="refused"&&(fatal(outcome.refusal),process.exit(1)),outcome.kind==="failed"&&(outcome.failure?fatal(errorMessage(outcome.failure.err),outcome.failure):fatal("Update failed."),process.exit(1));let{report}=outcome.planned;if(json){emitJson(buildUpdateReport({status:"planned",force,channel,currentChannel:channelOf(config),source,installed:config.skillsVersion,latest,archetypes:config.archetypes??[],plan:report,compact}));return}let legacyBackups=legacyBackupNotice(cwd);legacyBackups&&log11.info(legacyBackups),reportDryRun(report,force,channel,config)}import{intro as intro5,note as note6,outro as outro7}from"@clack/prompts";async function runList(opts={}){let json=opts.json??!1,cwd=process.cwd();json||intro5("pharn list");let config=loadArchetypeConfigOrExit(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);note6(lines.join(`
|
|
62
63
|
`),"INSTALLED (archetype)"),outro7(color_default.dim("Read-only \u2014 nothing changed."))}import{intro as intro6,log as log12,note as note7,outro as outro8,spinner as spinner5}from"@clack/prompts";var STATUS_SCHEMA_VERSION=1,MAX_RED_DETAIL=300,MAX_UNKNOWN_FIELD3=200,MAX_RUNNING_NODE=40;function strictFails(input){let{outdated,diff,hooks,absentUpstream}=input;return outdated||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;if(needsModelsConversion(models))return{conversionNeeded:!0,verdict:"old-format",stages:null,reds: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,{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:configLayout(config),upstream:drift===null?null:drift.upstreamLayout},drift:drift===null?null:{modified:drift.diff.modified,missing:drift.diff.missing,unreadable:drift.diff.unreadable,okCount:drift.diff.okCount,absentUpstream:drift.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD3)}))},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_FIELD3),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD3),reason:cap(u.reason,MAX_UNKNOWN_FIELD3)})),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:drift?.diff,hooks:drift?.hooks,absentUpstream:drift?.absentUpstream})}}}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||intro6("pharn status");let cwd=process.cwd(),config=loadArchetypeConfigOrExit(cwd,{json});if(json){await runArchetypeStatusJson(config,{strict,drift},cwd);return}await runArchetypeStatus(config,{strict,drift},cwd)}async function runArchetypeStatusJson(config,opts,cwd){let{strict,drift}=opts,node=nodeFloorStatus(process.versions.node),proxyNotice=detectProxyNotice(process.env);proxyNotice&&logErrorPlain(proxyNoticeMessage(proxyNotice));let channel=channelOf(config),emit=report2=>{console.log(serializeStatusReport(report2)),report2.strict.failed&&(process.exitCode=1)};if(!drift){let latest,source;try{({latest,source}=await latestWithoutClone(channel))}catch(err){reportFatalPlain(errorMessage(err),{err}),process.exit(1)}emit(buildStatusReport({node,config,channel,latest,source,drift:null,prettierignore:statusPrettierignore(cwd,config),strict}));return}let repo;try{repo=await fetchRepo(await resolveSource(channel))}catch(err){reportFatalPlain(errorMessage(err),{err}),process.exit(1)}let report;try{let index=parseCapabilityIndex(repo.dir),frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`)),diff=diffInstalledCapabilities({repoDir:repo.dir,projectRoot:cwd,capabilities:(config.capabilities??[]).filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`)),layout:configLayout(config)}),upstreamLayout=detectLayout(repo.dir);report=buildStatusReport({node,config,channel,latest:readSkillsVersion(repo.dir),source:repo.source,drift:{diff,hooks:diffHookWiring(repo.dir,cwd),unknown:index.unknown,orphans:statusOrphans(repo.dir,cwd,config,frozen),absentUpstream:absentInstallSurfaces({repoDir:repo.dir,layout:upstreamLayout}),upstreamLayout},prettierignore:statusPrettierignore(cwd,config),strict})}catch(err){reportFatalPlain(errorMessage(err),{err})}finally{repo.cleanup()}report===void 0&&process.exit(1),emit(report)}async function runArchetypeStatus(config,opts,cwd){let{strict,drift}=opts;note7(nodeFloorLines(nodeFloorStatus(process.versions.node)).join(`
|
|
63
64
|
`),"NODE");let proxyNotice=detectProxyNotice(process.env);proxyNotice&&log12.warn(proxyNoticeMessage(proxyNotice));let channel=channelOf(config);if(!drift){let s2=spinner5();s2.start("Checking for updates");let latest,source;try{({latest,source}=await latestWithoutClone(channel)),s2.stop(`Latest skills v${latest}`)}catch(err){s2.stop("Failed to check for updates"),reportFatal(errorMessage(err),{err}),process.exit(1)}let outdated=printArchetypeVersion(config,latest,source,channel);printModels(config),printPrettierignore(cwd,config),strict&&strictFails({outdated})&&process.exit(1),outro8(color_default.dim("Read-only \u2014 nothing changed (drift check skipped)."));return}let s=spinner5();s.start(`Comparing against ${REPO}`);let repo;try{repo=await fetchRepo(await resolveSource(channel)),s.stop(`Compared against ${sourceLabel(repo.source)}`)}catch(err){s.stop(`Failed to reach ${REPO}`),reportFatal(errorMessage(err),{err}),process.exit(1)}let exitCode=0;try{let outdated=printArchetypeVersion(config,readSkillsVersion(repo.dir),repo.source,channel);printModels(config),printPrettierignore(cwd,config);let index=parseCapabilityIndex(repo.dir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&log12.warn(unknownWarning);let frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`)),result=diffInstalledCapabilities({repoDir:repo.dir,projectRoot:cwd,capabilities:(config.capabilities??[]).filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`)),layout:configLayout(config)}),upstreamLayout=detectLayout(repo.dir),absentUpstream=absentInstallSurfaces({repoDir:repo.dir,layout:upstreamLayout});printLayoutNote(configLayout(config),upstreamLayout),printDriftSection(result,absentUpstream,sourceLabel(repo.source));let orphanLines=orphanNoteLines(statusOrphans(repo.dir,cwd,config,frozen)??[]);orphanLines&¬e7(orphanLines.join(`
|
|
64
65
|
`),"ORPHANED");let hooks=diffHookWiring(repo.dir,cwd),hookLines=hookWiringLines(hooks);hookLines&¬e7(hookLines.join(`
|
package/package.json
CHANGED