@pharn-dev/pharn 0.18.2 → 0.18.4

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/README.md CHANGED
@@ -266,8 +266,13 @@ the spec, iterates build -> regress -> verify until green, an iteration cap, or
266
266
  a terminal failure, commits a green result to a new local branch (never pushed
267
267
  or merged), and leaves the merge/fix/abandon decision to you after the run.
268
268
  From pharn-oss 7.7.0, a full `/pharn-loop` (not `--quick`) also runs
269
- `/pharn-triage` after the grill: it gives every grill finding one disposition,
270
- and any verdict but proceed stops the run for you. You can run `/pharn-triage`
269
+ `/pharn-triage` after the grill: it gives every grill finding one disposition.
270
+ Since 7.8.0 a `replan` verdict sends the run back to `/pharn-plan` for at most
271
+ two re-plan rounds, and since 7.9.0 a verdict that still escalates goes to
272
+ `/pharn-supervise`, a fresh agent that decides `stop` or `proceed-at-risk` (the
273
+ escalated findings are then named as known risk in the green commit and the run
274
+ report); since 7.10.0 it may instead amend the SPEC once per run (`amend-spec`).
275
+ That decision is one model's judgment, not a check. You can run `/pharn-triage`
271
276
  yourself after a full `/pharn-grill`.
272
277
 
273
278
  `/pharn-spec` fills PHARN's default SPEC template, or your own if you put one at
package/dist/index.js CHANGED
@@ -16,7 +16,7 @@ Replace it with a real directory and re-run.`);let stat=lstatSync10(safeJoin(cwd
16
16
  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}\`.
17
17
  `)}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(`
18
18
  `).map(escapeUnsafe).join(`
19
- `)}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&&notice.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","triage","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(`
19
+ `)}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&&notice.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","triage","supervise","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(`
20
20
  `));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(`
21
21
  `))}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.
22
22
  Run: git init && git add -A && git commit -m 'init'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pharn-dev/pharn",
3
- "version": "0.18.2",
3
+ "version": "0.18.4",
4
4
  "description": "Install and update PHARN in any git project. PHARN gets features shipped right with Claude Code, with spec, plan and checks kept in Git.",
5
5
  "keywords": [
6
6
  "claude-code",