@pharn-dev/pharn 0.10.0 → 0.11.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.
Files changed (3) hide show
  1. package/README.md +10 -10
  2. package/dist/index.js +6 -5
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -261,16 +261,16 @@ Two commands sit outside the pipeline:
261
261
 
262
262
  ## CLI commands
263
263
 
264
- | Command | Description |
265
- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
266
- | `pharn init` | Detect archetypes and install matching capabilities. This is also the default when no command is given. |
267
- | `pharn add [capability]` | Add one capability manually, for example `a11y` or `lens:n-plus-one`. With no argument, opens an interactive picker. |
268
- | `pharn remove [capability]` | Remove one installed capability. With no argument, opens an interactive picker. |
269
- | `pharn update` | Re-fetch and apply the latest PHARN content using drift-safe per-file decisions. `--force` overwrites files you changed; `--yes`/`-y` skips the confirmation prompt; `--dry-run` prints what it would do and writes nothing (add `--json` for the plan as one machine-readable object). |
270
- | `pharn list` | Show installed archetypes and capabilities. Use `--json` for machine-readable output. |
271
- | `pharn status` | Read-only version and drift report. Use `--strict` to make drift fail CI, `--no-drift` to skip byte comparison, or `--json` for one machine-readable report. |
272
- | `pharn --help` | Show command help. |
273
- | `pharn --version` | Show the installed CLI version. |
264
+ | Command | Description |
265
+ | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
266
+ | `pharn init` | Detect archetypes and install matching capabilities. This is also the default when no command is given. |
267
+ | `pharn add [capability]` | Add one capability manually, for example `a11y` or `lens:n-plus-one`. With no argument, opens an interactive picker. |
268
+ | `pharn remove [capability]` | Remove one installed capability. With no argument, opens an interactive picker. |
269
+ | `pharn update` | Re-fetch and apply the latest PHARN content using drift-safe per-file decisions. `--force` overwrites files you changed; `--yes`/`-y` skips the confirmation prompt; `--dry-run` prints what it would do and writes nothing (add `--json` for the plan as one machine-readable object, and `--compact` to leave the unchanged files out of it). |
270
+ | `pharn list` | Show installed archetypes and capabilities. Use `--json` for machine-readable output. |
271
+ | `pharn status` | Read-only version and drift report. Use `--strict` to make drift fail CI, `--no-drift` to skip byte comparison, or `--json` for one machine-readable report. |
272
+ | `pharn --help` | Show command help. |
273
+ | `pharn --version` | Show the installed CLI version. |
274
274
 
275
275
  `init` also accepts `--archetype`, a deprecated no-op kept for one release —
276
276
  archetype detection is now the default.
package/dist/index.js CHANGED
@@ -20,10 +20,10 @@ ${list}${tail}${editsLine}`);let result=await confirm2({message:"Continue and ov
20
20
  ${valid.join(`
21
21
  `)}`}}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);log6.info(`Backed up ${scan.drifted.length} file(s) to ${backupDir} before overwriting.`)}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,installedAt:new Date().toISOString()}),{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{existsSync as existsSync8,rmSync as rmSync3}from"node:fs";import{confirm as confirm3,groupMultiselect as groupMultiselect2,intro as intro3,isCancel as isCancel5,log as log7,outro as outro3}from"@clack/prompts";import pc4 from"picocolors";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}}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 deleteCapabilityDir(cwd,paths,target){let dir=safeChildJoin(safeJoin(cwd,capabilitySubtree(paths,target.role)),target.name),existed=existsSync8(dir);return existed&&rmSync3(dir,{recursive:!0,force:!0}),existed}function refuseSymlinkedTargets(cwd,paths,targets){for(let target of targets){let linked;try{linked=findSymlinkComponent(cwd,capabilityRelDir(paths,target))}catch{linked=null}linked!==null&&(logError(`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.`),process.exit(1))}}function capabilityRelDir(paths,capability){return`${capabilitySubtree(paths,capability.role)}/${capability.name}`}async function pruneCapabilityRecords(cwd,config,paths,targets){let{records}=recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit});if(records===null)return;let prefixes=targets.map(t=>`${capabilityRelDir(paths,t)}/`),kept={},dropped=0;for(let[key2,hash]of Object.entries(records))prefixes.some(prefix=>key2.startsWith(prefix))?dropped++:kept[key2]=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(", ");log7.warn(`${names} ${auto.length===1?"is":"are"} selected automatically for your archetypes, so the next \`pharn update\` will reinstall ${auto.length===1?"it":"them"} (and will name ${auto.length===1?"it":"them"} in its report).`)}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.";log7.warn(`"${address}" is not an installed capability.${hint}`),outro3("Nothing was removed.");return}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 note6=await withProjectLock(cwd,"remove",async()=>{assertConfigUnchanged(cwd,config,"remove");let existed=deleteCapabilityDir(cwd,paths,target);return await pruneCapabilityRecords(cwd,config,paths,[target]),await writePharnConfig(cwd,{...config,capabilities:installed2.filter(c=>!(c.name===target.name&&c.role===target.role)),installedAt:new Date().toISOString()}),existed?"":pc4.dim(" (its files were already gone)")});warnIfAutoSelected([target]),outro3(`${pc4.green("\u2714")} Removed ${target.name} (${target.role})${note6}`)}async function runRemovePicker(cwd,config,installed2){if(installed2.length===0){outro3("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});isCancel5(picked)&&cancelAndExit();let values=picked;if(values.length===0){outro3("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 confirm3({message:`Remove ${targets.length} ${plural2(targets.length)}: ${targets.map(t=>`${t.name} (${t.role})`).join(", ")}?`,initialValue:!1});(isCancel5(ok)||ok!==!0)&&cancelAndExit(),await withProjectLock(cwd,"remove",async()=>{assertConfigUnchanged(cwd,config,"remove");for(let target of targets)deleteCapabilityDir(cwd,paths,target);await pruneCapabilityRecords(cwd,config,paths,targets);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}`)),installedAt:new Date().toISOString()})}),warnIfAutoSelected(targets),outro3(`${pc4.green("\u2714")} Removed ${targets.length} ${plural2(targets.length)}.`)}function plural2(n){return n===1?"capability":"capabilities"}import{closeSync as closeSync6,constants as constants3,fstatSync as fstatSync4,openSync as openSync6,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=openSync6(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{closeSync6(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 wiredKeys(result){return new Set(result.kind==="ok"?(hookEntries(result.value)??[]).map(entryKey):[])}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 inShared=wiredKeys(shared),inLocal=wiredKeys(local),missing=upstreamEntries.filter(e=>!inShared.has(entryKey(e))&&!inLocal.has(entryKey(e))),localOnly=upstreamEntries.filter(e=>!inShared.has(entryKey(e))&&inLocal.has(entryKey(e)));return missing.length?{status:"missing",missing}:localOnly.length?{status:"local-only",missing,localOnly}:{status:"match",missing}}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)}`)]}return[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:`," each line is one hook, as JSON, under its event [matcher]. Matching is"," textual: an equivalent hook you wrote differently is listed too."]}function key(cap2){return`${cap2.role}:${cap2.name}`}function mergeCapabilities(selection,previous,frozen){let resolved=new Set(selection.selected.map(key)),inIndex=new Set([...selection.selected.map(key),...selection.skipped.map(key)]),previousSource=new Map,seenPrevious=new Set;for(let cap2 of previous){let k=key(cap2);seenPrevious.has(k)||(seenPrevious.add(k),previousSource.set(k,cap2.source))}let capabilities=[],changes=[];for(let sel of selection.selected){let k=key(sel);if(!seenPrevious.has(k)){let cap2={name:sel.name,role:sel.role,source:"auto"};capabilities.push(cap2),changes.push({cap:cap2,reason:"added"});continue}let source=previousSource.get(k)==="manual"?"manual":"auto";capabilities.push({name:sel.name,role:sel.role,source})}for(let cap2 of previous){let k=key(cap2);if(resolved.has(k))continue;if(frozen.has(k)){let kept={...cap2};capabilities.push(kept),changes.push({cap:kept,reason:"kept-frozen"});continue}if(cap2.source==="auto"){changes.push({cap:cap2,reason:"dropped-unselected"});continue}let inferred={...cap2,source:"manual"};if(!inIndex.has(k)){changes.push({cap:inferred,reason:"dropped-gone"});continue}capabilities.push(inferred),cap2.source===void 0&&changes.push({cap:inferred,reason:"kept-manual"})}return{capabilities,changes}}import{copyFileSync as copyFileSync2,lstatSync as lstatSync8,mkdirSync as mkdirSync4}from"node:fs";import{dirname as dirname5}from"node:path";var ApplyError=class extends Error{constructor(message,written){super(message);this.written=written;this.name="ApplyError"}written};function readDiskState(projectRoot,rel){let dest=safeJoin(projectRoot,rel),stat;try{let link=findSymlinkComponent(projectRoot,rel);if(link!==null)return{kind:"unreadable",reason:link===toPosix(rel)?"the path is a symlink":`${link} is a symlink`};stat=lstatSync8(dest,{throwIfNoEntry:!1})}catch{return{kind:"unreadable",reason:"the path could not be inspected"}}if(!stat)return{kind:"absent"};if(!stat.isFile())return{kind:"unreadable",reason:"the path is not a regular file"};try{return{kind:"file",hash:sha256File(dest)}}catch{return{kind:"unreadable",reason:"the file could not be read"}}}function applyWrites(params){let{projectRoot,expected,writes}=params,written=[];for(let rel of writes){let from=expected.get(rel);if(from===void 0)throw new ApplyError(`Internal: no source for planned write ${rel}.`,written);try{let to=safeJoin(projectRoot,rel),link=findSymlinkComponent(projectRoot,rel);if(link!==null)throw new ManifestValidationError(`${link} is a symlink; refusing to write through it.`);mkdirSync4(dirname5(to),{recursive:!0}),copyFileSync2(from,to),written.push(rel)}catch(err){throw new ApplyError(`Failed to write ${rel}: ${err instanceof Error?err.message:String(err)}`,written)}}return written}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"]);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,sha256File(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}),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}`))),previouslyFrozen=new Set(config.frozenCapabilities??[]),skippedRels=plan.skipped.flatMap(group=>group.rels),hasSkippedFile=cap2=>{let prefix=`${capabilitySubtree(paths,cap2.role)}/${cap2.name}/`;return skippedRels.some(rel=>rel.startsWith(prefix))},frozenKeys=[...new Set(configCapabilities.filter(cap2=>{let key2=`${cap2.role}:${cap2.name}`;return frozen.has(key2)||previouslyFrozen.has(key2)&&hasSkippedFile(cap2)}).map(cap2=>`${cap2.role}:${cap2.name}`))].sort();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,files:plan.files,writes:plan.writes,backups,skipped:plan.skipped,counts:plan.counts,models,modelsFloor:paths.floor,hookWiring:diffHookWiring(repoDir,cwd),recordsNote,unknownWarning,unknownCapabilities:index.unknown},apply:{expected,records,plan,models,configCapabilities,frozen,frozenRecords,nextSkillsVersion,nextCommit,frozenKeys}}}import{confirm as confirm4,intro as intro4,isCancel as isCancel6,log as log8,note as note3,outro as outro4,spinner as spinner4}from"@clack/prompts";import pc5 from"picocolors";function cap(value,max){return value.length>max?`${value.slice(0,max)}\u2026`:value}function serializeJsonReport(report){return JSON.stringify(report,null,2).split(`
22
22
  `).map(escapeUnsafe).join(`
23
- `)}var UPDATE_SCHEMA_VERSION=1,MAX_REASON=300,MAX_UNKNOWN_FIELD=200,capAll=(values,max)=>values.map(v=>cap(v,max));function planReport(p){return{layout:p.layout,abandonedLayout:p.abandonedLayout,featuresReadmeRelocation:p.featuresReadmeRelocation,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}))},files:p.files.map(f=>({rel:f.rel,action:f.action,label:f.label,backup:f.backup,forced:f.forced})),writes:[...p.writes],backups:[...p.backups],skipped:p.skipped.map(g=>({label:g.label,rels:[...g.rels]})),counts:{updated:p.counts.updated,restored:p.counts.restored,ok:p.counts.ok,forced:p.counts.forced,skipped:p.counts.skipped},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_REASON),leftovers:capAll(p.models.conversion.leftovers,MAX_REASON)},problems:capAll(p.models.problems,MAX_REASON),upstreamReasons:capAll(p.models.upstreamReasons,MAX_REASON)},hooks:{status:p.hookWiring.status,missing:p.hookWiring.missing,localOnly:p.hookWiring.localOnly??[],file:p.hookWiring.file??null,reason:p.hookWiring.reason??null},frozenCapabilities:[...p.frozenCapabilities],unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),recordsNote:p.recordsNote===null?null:cap(p.recordsNote,MAX_REASON)}}function buildUpdateReport(input){let{plan}=input;return{schemaVersion:UPDATE_SCHEMA_VERSION,command:"update",dryRun:!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):null}}async function runUpdate(opts={}){let dryRun=opts.dryRun??!1,json=opts.json??!1;json&&!dryRun&&(reportFatalPlain("--json is only available with --dry-run."),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)),await runArchetypeUpdate(config,cwd,opts.force??!1,yes,opts.ref??channelOf(config),dryRun,json)}async function runArchetypeUpdate(config,cwd,force,yes,channel,dryRun,json){let proxyNotice=detectProxyNotice(process.env);proxyNotice&&(json?logErrorPlain(proxyNoticeMessage(proxyNotice)):log8.warn(proxyNoticeMessage(proxyNotice)));let s=json?silentSpinner():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}))};if(source.kind==="release"&&!force&&compareVersionCore(config.skillsVersion,latest)===1){if(json){emitEarlyReturn("ahead-of-release");return}outro4(`Your install (skills v${config.skillsVersion}) 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}.`);return}let current=config.skillsVersion===latest,recheckFrozen=(config.frozenCapabilities??[]).length>0,convertModels=modelsMigrationPending(config.models,recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit}).records?.[MODELS_RECORD_KEY]??null),switchChannel=channel!==channelOf(config);if(current&&!force&&!recheckFrozen&&!convertModels&&!switchChannel){if(json){emitEarlyReturn("up-to-date");return}outro4(`Already up to date (skills v${config.skillsVersion}).`);return}if(json||note3([current?row("Skills version",`v${config.skillsVersion} (re-applying)`):row("Skills version",`v${config.skillsVersion} \u2192 v${latest}`),row("Source",sourceDescription(source)),"",row("Archetypes",(config.archetypes??[]).join(", ")||"(none)"),"",force?pc5.dim(` --force: files you changed will be OVERWRITTEN (each is copied to ${BACKUP_DIR}/ first).`):pc5.dim(" Files you have changed are kept, not overwritten \u2014 they are listed at the end."),...convertModels?[pc5.dim(" Your models block is in the format pharn wrote before 0.7.0 \u2014 this run converts it.")]:[],pc5.dim(" Re-resolves your archetypes against the latest capabilities and re-copies them."),...dryRun?[pc5.dim(" Preview only \u2014 nothing will be written.")]:[],pc5.dim(" https://github.com/pharn-dev/pharn-oss/blob/main/CHANGELOG.md")].join(`
24
- `)),dryRun){await runDryRun(config,cwd,force,channel,source,json,latest);return}if(!yes){let ok=await confirm4({message:force?"Re-fetch capabilities and overwrite your changes?":"Re-fetch capabilities at the latest version?",initialValue:!0});(isCancel6(ok)||ok!==!0)&&cancelAndExit()}let outcome=null,backupRef={current:null},spinnerRef={current:null},refusalRef={current:null},failure=null;try{outcome=await withProjectLock(cwd,"update",async()=>{assertConfigUnchanged(cwd,config,"update");let s2=spinner4();spinnerRef.current=s2,s2.start(`Updating from ${REPO_URL}`);let repo=await fetchRepo(source);try{let gate=checkMinCli(repo.dir);if(gate.refusal)return s2.stop("Update refused"),refusalRef.current=gate.refusal,null;let planned=buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel,onUnknownWarning:warning=>log8.warn(warning)}),applied=await applyPlannedUpdate(planned,config,cwd,channel,backup=>{backupRef.current=backup,s2.stop("Backup written"),printBackupNotice(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}finally{repo.cleanup()}})}catch(err){err instanceof ProjectLockedError?(spinnerRef.current?.stop("Update refused"),refusalRef.current=err.message):(spinnerRef.current?.stop("Update failed"),failure={err})}let refusal3=refusalRef.current;refusal3&&(reportFatal(refusal3),process.exit(1)),(failure||!outcome)&&(failure?reportFatal(errorMessage(failure.err),failure):reportFatal("Update failed."),backupRef.current&&printBackupNotice(backupRef.current,{aborted:!0}),process.exit(1)),reportOutcome(outcome,force)}async function applyPlannedUpdate(planned,config,cwd,channel,onBackup){let{report,apply}=planned,{expected,records,plan,models,configCapabilities}=apply,backup=report.backups.length>0?{dir:createBackup(cwd,report.backups),count:report.backups.length}:null;backup&&onBackup(backup);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}await writeRecords(cwd,{skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,files:{...apply.frozenRecords,...plan.nextRecords,...buildRecords(cwd,written),...models.nextRecord!==null?{[MODELS_RECORD_KEY]:models.nextRecord}:{}}});let{pendingSkillsVersion:_previousPending,frozenCapabilities:_previousFrozen,ref:_previousRef,...rest}=config;return await writePharnConfig(cwd,{...rest,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,installedAt:new Date().toISOString(),models:models.next}),{installedVersion:report.installedVersion,recordedVersion:report.recordedVersion,capCount:report.capCount,capabilityChanges:report.capabilityChanges,plan,backup,recordsNote:report.recordsNote,versionWithheld:report.versionWithheld,abandonedLayout:report.abandonedLayout,featuresReadmeRelocation:report.featuresReadmeRelocation,hookWiring:report.hookWiring,models,modelsFloor:report.modelsFloor}}var FORCEABLE_SKIPS=new Set(["modified","unrecorded","unverifiable"]);function reportOutcome(outcome,force){let{plan,recordsNote,versionWithheld}=outcome,{counts}=plan;recordsNote&&log8.warn(`\u26A0 ${recordsNote}`),reportCapabilityChanges(outcome.capabilityChanges),reportModels(outcome.models,outcome.modelsFloor,outcome.backup);let hookLines=outcome.hookWiring?hookWiringLines(outcome.hookWiring):null;hookLines&&note3(hookLines.join(`
23
+ `)}var UPDATE_SCHEMA_VERSION=1,MAX_REASON=300,MAX_UNKNOWN_FIELD=200,capAll=(values,max)=>values.map(v=>cap(v,max));function planReport(p,compact){let kept=compact?p.files.filter(f=>f.action!=="noop"):p.files;return{layout:p.layout,abandonedLayout:p.abandonedLayout,featuresReadmeRelocation:p.featuresReadmeRelocation,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}))},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:[...p.backups],skipped:p.skipped.map(g=>({label:g.label,rels:[...g.rels]})),counts:{updated:p.counts.updated,restored:p.counts.restored,ok:p.counts.ok,forced:p.counts.forced,skipped:p.counts.skipped},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_REASON),leftovers:capAll(p.models.conversion.leftovers,MAX_REASON)},problems:capAll(p.models.problems,MAX_REASON),upstreamReasons:capAll(p.models.upstreamReasons,MAX_REASON)},hooks:{status:p.hookWiring.status,missing:p.hookWiring.missing,localOnly:p.hookWiring.localOnly??[],file:p.hookWiring.file??null,reason:p.hookWiring.reason??null},frozenCapabilities:[...p.frozenCapabilities],unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),recordsNote:p.recordsNote===null?null:cap(p.recordsNote,MAX_REASON)}}function buildUpdateReport(input){let{plan}=input,compact=input.compact??!1;return{schemaVersion:UPDATE_SCHEMA_VERSION,command:"update",dryRun:!0,...compact?{compact:!0}:{},status:input.status,force:input.force,channel:input.channel,channelChange:input.channel===input.currentChannel?null:{from:input.currentChannel,to:input.channel},source:{kind:input.source.kind,tag:input.source.kind==="release"?input.source.tag:null},version:{installed:input.installed,latest:plan?plan.installedVersion:input.latest,recorded:plan?plan.recordedVersion:null,withheld:plan?plan.versionWithheld:null,pending:plan?plan.pendingSkillsVersion:null},archetypes:[...input.archetypes],plan:plan?planReport(plan,compact):null}}async function runUpdate(opts={}){let 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)),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)):log8.warn(proxyNoticeMessage(proxyNotice)));let s=json?silentSpinner():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}))};if(source.kind==="release"&&!force&&compareVersionCore(config.skillsVersion,latest)===1){if(json){emitEarlyReturn("ahead-of-release");return}outro4(`Your install (skills v${config.skillsVersion}) 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}.`);return}let current=config.skillsVersion===latest,recheckFrozen=(config.frozenCapabilities??[]).length>0,convertModels=modelsMigrationPending(config.models,recordsBaseline(readRecords(cwd),{skillsVersion:config.skillsVersion,commit:config.commit}).records?.[MODELS_RECORD_KEY]??null),switchChannel=channel!==channelOf(config);if(current&&!force&&!recheckFrozen&&!convertModels&&!switchChannel){if(json){emitEarlyReturn("up-to-date");return}outro4(`Already up to date (skills v${config.skillsVersion}).`);return}if(json||note3([current?row("Skills version",`v${config.skillsVersion} (re-applying)`):row("Skills version",`v${config.skillsVersion} \u2192 v${latest}`),row("Source",sourceDescription(source)),"",row("Archetypes",(config.archetypes??[]).join(", ")||"(none)"),"",force?pc5.dim(` --force: files you changed will be OVERWRITTEN (each is copied to ${BACKUP_DIR}/ first).`):pc5.dim(" Files you have changed are kept, not overwritten \u2014 they are listed at the end."),...convertModels?[pc5.dim(" Your models block is in the format pharn wrote before 0.7.0 \u2014 this run converts it.")]:[],pc5.dim(" Re-resolves your archetypes against the latest capabilities and re-copies them."),...dryRun?[pc5.dim(" Preview only \u2014 nothing will be written.")]:[],pc5.dim(" https://github.com/pharn-dev/pharn-oss/blob/main/CHANGELOG.md")].join(`
24
+ `)),dryRun){await runDryRun(config,cwd,force,channel,source,json,latest,compact);return}if(!yes){let ok=await confirm4({message:force?"Re-fetch capabilities and overwrite your changes?":"Re-fetch capabilities at the latest version?",initialValue:!0});(isCancel6(ok)||ok!==!0)&&cancelAndExit()}let outcome=null,backupRef={current:null},spinnerRef={current:null},refusalRef={current:null},failure=null;try{outcome=await withProjectLock(cwd,"update",async()=>{assertConfigUnchanged(cwd,config,"update");let s2=spinner4();spinnerRef.current=s2,s2.start(`Updating from ${REPO_URL}`);let repo=await fetchRepo(source);try{let gate=checkMinCli(repo.dir);if(gate.refusal)return s2.stop("Update refused"),refusalRef.current=gate.refusal,null;let planned=buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel,onUnknownWarning:warning=>log8.warn(warning)}),applied=await applyPlannedUpdate(planned,config,cwd,channel,backup=>{backupRef.current=backup,s2.stop("Backup written"),printBackupNotice(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}finally{repo.cleanup()}})}catch(err){err instanceof ProjectLockedError?(spinnerRef.current?.stop("Update refused"),refusalRef.current=err.message):(spinnerRef.current?.stop("Update failed"),failure={err})}let refusal3=refusalRef.current;refusal3&&(reportFatal(refusal3),process.exit(1)),(failure||!outcome)&&(failure?reportFatal(errorMessage(failure.err),failure):reportFatal("Update failed."),backupRef.current&&printBackupNotice(backupRef.current,{aborted:!0}),process.exit(1)),reportOutcome(outcome,force)}async function applyPlannedUpdate(planned,config,cwd,channel,onBackup){let{report,apply}=planned,{expected,records,plan,models,configCapabilities}=apply,backup=report.backups.length>0?{dir:createBackup(cwd,report.backups),count:report.backups.length}:null;backup&&onBackup(backup);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}await writeRecords(cwd,{skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,files:{...apply.frozenRecords,...plan.nextRecords,...buildRecords(cwd,written),...models.nextRecord!==null?{[MODELS_RECORD_KEY]:models.nextRecord}:{}}});let{pendingSkillsVersion:_previousPending,frozenCapabilities:_previousFrozen,ref:_previousRef,...rest}=config;return await writePharnConfig(cwd,{...rest,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,installedAt:new Date().toISOString(),models:models.next}),{installedVersion:report.installedVersion,recordedVersion:report.recordedVersion,capCount:report.capCount,capabilityChanges:report.capabilityChanges,plan,backup,recordsNote:report.recordsNote,versionWithheld:report.versionWithheld,abandonedLayout:report.abandonedLayout,featuresReadmeRelocation:report.featuresReadmeRelocation,hookWiring:report.hookWiring,models,modelsFloor:report.modelsFloor}}var FORCEABLE_SKIPS=new Set(["modified","unrecorded","unverifiable"]);function reportOutcome(outcome,force){let{plan,recordsNote,versionWithheld}=outcome,{counts}=plan;recordsNote&&log8.warn(`\u26A0 ${recordsNote}`),reportCapabilityChanges(outcome.capabilityChanges),reportModels(outcome.models,outcome.modelsFloor,outcome.backup);let hookLines=outcome.hookWiring?hookWiringLines(outcome.hookWiring):null;hookLines&&note3(hookLines.join(`
25
25
  `),"HOOKS");let forceable=reportSkipped(plan.skipped,!1);reportLayoutWarnings(outcome.abandonedLayout,outcome.featuresReadmeRelocation,!1),versionWithheld&&log8.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}`;outro4(`${pc5.green("\u2714")} ${summary} ${pc5.dim(`(${outcome.capCount} capabilit${outcome.capCount===1?"y":"ies"}, skills v${outcome.recordedVersion})`)}`)}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(pc5.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(pc5.dim(" --force cannot clear the UNREADABLE paths above."),pc5.dim(" Inspect each path by hand \u2014 a directory, a symlink, or an"),pc5.dim(" unreadable file sits where pharn expects a regular file.")),note3(lines.join(`
26
- `),"SKIPPED")}return forceable}function reportLayoutWarnings(abandonedLayout,featuresReadmeRelocation,preview){abandonedLayout==="flat"?log8.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"&&log8.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&&log8.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 checkMinCli(repoDir,warn=message=>log8.warn(message)){let gate=minCliGate(repoDir,PHARN_VERSION);return gate.warning&&warn(gate.warning),{refusal:gate.refusal??null}}function silentSpinner(){return{start:()=>{},stop:()=>{}}}function emitJson(report){console.log(serializeJsonReport(report))}async function fetchAndPlan(config,cwd,force,channel,source,ui){let{spin,warn}=ui;spin.start(`Planning from ${REPO_URL}`);let outcome;try{let repo=await fetchRepo(source);try{let refusal3=checkMinCli(repo.dir,warn).refusal;if(refusal3)spin.stop("Update refused"),outcome={kind:"refused",refusal:refusal3};else{let planned=buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel,onUnknownWarning:warn});spin.stop("Plan ready"),outcome={kind:"planned",planned}}}finally{repo.cleanup()}}catch(err){spin.stop("Planning failed"),outcome={kind:"failed",failure:{err}}}return outcome}async function runDryRun(config,cwd,force,channel,source,json,latest){let outcome=await fetchAndPlan(config,cwd,force,channel,source,{spin:json?silentSpinner():spinner4(),warn:json?message=>logErrorPlain(message):message=>log8.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}));return}reportDryRun(report,force,channel,config)}function reportDryRun(r,force,channel,config){r.recordsNote&&log8.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)}))],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(r.backups.length>0){lines.push(` WOULD BACK UP ${r.backups.length} file(s) to ${BACKUP_DIR}/<timestamp>/ first`);for(let rel of r.backups)lines.push(` ${rel}`);lines.push("")}writes.length===0&&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}`),note3(lines.join(`
26
+ `),"SKIPPED")}return forceable}function reportLayoutWarnings(abandonedLayout,featuresReadmeRelocation,preview){abandonedLayout==="flat"?log8.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"&&log8.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&&log8.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 checkMinCli(repoDir,warn=message=>log8.warn(message)){let gate=minCliGate(repoDir,PHARN_VERSION);return gate.warning&&warn(gate.warning),{refusal:gate.refusal??null}}function silentSpinner(){return{start:()=>{},stop:()=>{}}}function emitJson(report){console.log(serializeJsonReport(report))}async function fetchAndPlan(config,cwd,force,channel,source,ui){let{spin,warn}=ui;spin.start(`Planning from ${REPO_URL}`);let outcome;try{let repo=await fetchRepo(source);try{let refusal3=checkMinCli(repo.dir,warn).refusal;if(refusal3)spin.stop("Update refused"),outcome={kind:"refused",refusal:refusal3};else{let planned=buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel,onUnknownWarning:warn});spin.stop("Plan ready"),outcome={kind:"planned",planned}}}finally{repo.cleanup()}}catch(err){spin.stop("Planning failed"),outcome={kind:"failed",failure:{err}}}return outcome}async function runDryRun(config,cwd,force,channel,source,json,latest,compact){let outcome=await fetchAndPlan(config,cwd,force,channel,source,{spin:json?silentSpinner():spinner4(),warn:json?message=>logErrorPlain(message):message=>log8.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}reportDryRun(report,force,channel,config)}function reportDryRun(r,force,channel,config){r.recordsNote&&log8.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)}))],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(r.backups.length>0){lines.push(` WOULD BACK UP ${r.backups.length} file(s) to ${BACKUP_DIR}/<timestamp>/ first`);for(let rel of r.backups)lines.push(` ${rel}`);lines.push("")}writes.length===0&&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}`),note3(lines.join(`
27
27
  `),"PLAN"),reportCapabilityChanges(r.capabilityChanges),reportModels(r.models,r.modelsFloor,null,!0);let hookLines=hookWiringLines(r.hookWiring);hookLines&&note3(hookLines.join(`
28
28
  `),"HOOKS");let forceable=reportSkipped(r.skipped,!0);reportLayoutWarnings(r.abandonedLayout,r.featuresReadmeRelocation,!0),r.versionWithheld?(log8.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&&log8.info(`Would record skills v${r.pendingSkillsVersion} as pending, so \`pharn add\` installs at it.`)):log8.info(`Would record skills v${r.recordedVersion}.`),r.frozenCapabilities.length>0&&log8.info(`Would keep unread upstream capabilities as they are: ${r.frozenCapabilities.join(", ")}.`),outro4(`Dry run \u2014 would write ${writes.length} \xB7 back up ${r.backups.length} \xB7 unchanged ${r.counts.ok} \xB7 skipped ${r.counts.skipped}. Nothing was changed. Run \`pharn update${force?" --force":""}\` to apply.`)}function printBackupNotice(backup,opts){let output=opts.aborted?process.stderr:process.stdout;opts.aborted&&log8.warn("The update stopped part-way \u2014 some originals may already have been overwritten.",{output}),log8.info(`Backed up ${backup.count} file(s) to ${backup.dir} before overwriting.`,{output}),opts.aborted||log8.info(`${BACKUP_DIR}/ is not gitignored \u2014 add it to .gitignore or delete it once you are happy.`,{output})}var 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){if(changes.length===0)return;let 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)lines.push(` ${cap2.role}:${cap2.name}`);lines.push("")}}changes.some(c=>c.reason==="dropped-unselected"||c.reason==="dropped-gone")&&lines.push(pc5.dim(" Removed capabilities\u2019 files are left on disk \u2014 pharn update never deletes.")),note3(lines.join(`
29
29
  `),"CAPABILITIES")}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=>pc5.dim(line))),note3(lines.join(`
@@ -58,7 +58,8 @@ Options (each belongs to ONE command; passing it to another is an error):
58
58
  --json list: emit the inventory as JSON
59
59
  status: emit one JSON report on stdout (diagnostics on stderr)
60
60
  update: with --dry-run, emit the plan as one JSON object
61
+ --compact update: with --dry-run --json, omit the unchanged files from the plan's file list
61
62
  -h, --help Show this help text
62
- -v, --version Show the version number`,MAX_POSITIONALS=new Map([["init",1],["update",1],["list",1],["status",1],["add",2],["remove",2],["rm",2]]),ALLOWED_FLAGS=new Map([["init",["archetype","ref"]],["add",[]],["remove",[]],["rm",[]],["update",["force","yes","ref","dry-run","json"]],["list",["json"]],["status",["strict","drift","json"]]]),REQUIRED_WITH=new Map([["update",[{flag:"json",requires:"dry-run"}]]]),GLOBAL_FLAGS=["help","version"],ALIASES={h:"help",v:"version",y:"yes"},STRING_FLAGS=new Set(["ref"]),DECLARED_FLAGS=[...new Set([...GLOBAL_FLAGS,...Array.from(ALLOWED_FLAGS.values()).flat()])],DECLARED_BOOLEANS=DECLARED_FLAGS.filter(f=>!STRING_FLAGS.has(f)),DECLARED_STRINGS=DECLARED_FLAGS.filter(f=>STRING_FLAGS.has(f));function collectFlags(offenders){return arg=>arg.startsWith("-")?(offenders.push(arg),!1):!0}function aliasesFor(declared){return Object.fromEntries(Object.entries(ALIASES).filter(([,canonical])=>declared.includes(canonical)))}function unsupportedFlags(allowed){let offenders=[],declared=[...GLOBAL_FLAGS,...allowed];return minimist(process.argv.slice(2),{boolean:declared.filter(f=>!STRING_FLAGS.has(f)),string:declared.filter(f=>STRING_FLAGS.has(f)),alias:aliasesFor(declared),unknown:collectFlags(offenders)}),offenders}function unmetRequirements(cmd,argv){return(REQUIRED_WITH.get(cmd)??[]).filter(({flag,requires})=>!!argv[flag]&&!argv[requires]).map(({flag,requires})=>`--${flag} (needs --${requires})`)}function refuse(label,offenders){console.error(`${label}: ${[...new Set(offenders)].map(o=>JSON.stringify(o)).join(", ")}
63
- `),console.error(USAGE),process.exit(1)}async function main(){let unknownOptions=[],argv=minimist(process.argv.slice(2),{boolean:DECLARED_BOOLEANS,string:["_",...DECLARED_STRINGS],default:{drift:!0},alias:ALIASES,unknown:collectFlags(unknownOptions)});unknownOptions.length>0&&refuse("Unknown option",unknownOptions);let cmd=argv._[0]??"init",allowedFlags=ALLOWED_FLAGS.get(cmd);if(allowedFlags!==void 0){let unsupported=unsupportedFlags(allowedFlags);unsupported.length>0&&refuse(`Unsupported option for \`${cmd}\``,unsupported)}let unmet=unmetRequirements(cmd,argv);unmet.length>0&&refuse(`Incomplete option for \`${cmd}\``,unmet);let ref=refOption(argv.ref);if(ref===null&&refuse(`Invalid value for --ref (expected ${REF_CHOICES.map(r=>`"${r}"`).join(" or ")})`,[typeof argv.ref=="string"?argv.ref:JSON.stringify(argv.ref)]),argv.version){console.log(PHARN_VERSION);return}if(argv.help){console.log(USAGE);return}let maxPositionals=MAX_POSITIONALS.get(cmd);switch(maxPositionals!==void 0&&argv._.length>maxPositionals&&refuse("Unexpected argument",argv._.slice(maxPositionals)),cmd){case"init":await runInit({ref});return;case"add":await runAdd(argv._[1]);return;case"remove":case"rm":await runRemove(argv._[1]);return;case"update":await runUpdate({force:!!argv.force,yes:!!argv.yes,dryRun:!!argv["dry-run"],json:!!argv.json,ref});return;case"list":await runList({json:!!argv.json});return;case"status":await runStatus({strict:!!argv.strict,drift:argv.drift!==!1,json:!!argv.json});return;default:console.error(`Unknown command: ${cmd}
63
+ -v, --version Show the version number`,MAX_POSITIONALS=new Map([["init",1],["update",1],["list",1],["status",1],["add",2],["remove",2],["rm",2]]),ALLOWED_FLAGS=new Map([["init",["archetype","ref"]],["add",[]],["remove",[]],["rm",[]],["update",["force","yes","ref","dry-run","json","compact"]],["list",["json"]],["status",["strict","drift","json"]]]),REQUIRED_WITH=new Map([["update",[{flag:"json",requires:"dry-run"},{flag:"compact",requires:"json"}]]]),GLOBAL_FLAGS=["help","version"],ALIASES={h:"help",v:"version",y:"yes"},STRING_FLAGS=new Set(["ref"]),DECLARED_FLAGS=[...new Set([...GLOBAL_FLAGS,...Array.from(ALLOWED_FLAGS.values()).flat()])],DECLARED_BOOLEANS=DECLARED_FLAGS.filter(f=>!STRING_FLAGS.has(f)),DECLARED_STRINGS=DECLARED_FLAGS.filter(f=>STRING_FLAGS.has(f));function collectFlags(offenders){return arg=>arg.startsWith("-")?(offenders.push(arg),!1):!0}function aliasesFor(declared){return Object.fromEntries(Object.entries(ALIASES).filter(([,canonical])=>declared.includes(canonical)))}function unsupportedFlags(allowed){let offenders=[],declared=[...GLOBAL_FLAGS,...allowed];return minimist(process.argv.slice(2),{boolean:declared.filter(f=>!STRING_FLAGS.has(f)),string:declared.filter(f=>STRING_FLAGS.has(f)),alias:aliasesFor(declared),unknown:collectFlags(offenders)}),offenders}function unmetRequirements(cmd,argv){return(REQUIRED_WITH.get(cmd)??[]).filter(({flag,requires})=>!!argv[flag]&&!argv[requires]).map(({flag,requires})=>`--${flag} (needs --${requires})`)}function refuse(label,offenders){console.error(`${label}: ${[...new Set(offenders)].map(o=>JSON.stringify(o)).join(", ")}
64
+ `),console.error(USAGE),process.exit(1)}async function main(){let unknownOptions=[],argv=minimist(process.argv.slice(2),{boolean:DECLARED_BOOLEANS,string:["_",...DECLARED_STRINGS],default:{drift:!0},alias:ALIASES,unknown:collectFlags(unknownOptions)});unknownOptions.length>0&&refuse("Unknown option",unknownOptions);let cmd=argv._[0]??"init",allowedFlags=ALLOWED_FLAGS.get(cmd);if(allowedFlags!==void 0){let unsupported=unsupportedFlags(allowedFlags);unsupported.length>0&&refuse(`Unsupported option for \`${cmd}\``,unsupported)}let unmet=unmetRequirements(cmd,argv);unmet.length>0&&refuse(`Incomplete option for \`${cmd}\``,unmet);let ref=refOption(argv.ref);if(ref===null&&refuse(`Invalid value for --ref (expected ${REF_CHOICES.map(r=>`"${r}"`).join(" or ")})`,[typeof argv.ref=="string"?argv.ref:JSON.stringify(argv.ref)]),argv.version){console.log(PHARN_VERSION);return}if(argv.help){console.log(USAGE);return}let maxPositionals=MAX_POSITIONALS.get(cmd);switch(maxPositionals!==void 0&&argv._.length>maxPositionals&&refuse("Unexpected argument",argv._.slice(maxPositionals)),cmd){case"init":await runInit({ref});return;case"add":await runAdd(argv._[1]);return;case"remove":case"rm":await runRemove(argv._[1]);return;case"update":await runUpdate({force:!!argv.force,yes:!!argv.yes,dryRun:!!argv["dry-run"],json:!!argv.json,compact:!!argv.compact,ref});return;case"list":await runList({json:!!argv.json});return;case"status":await runStatus({strict:!!argv.strict,drift:argv.drift!==!1,json:!!argv.json});return;default:console.error(`Unknown command: ${cmd}
64
65
  `),console.error(USAGE),process.exit(1)}}function refOption(value){if(value!==void 0)return REF_CHOICES.find(choice=>choice===value)??null}function isEntryPoint(){if(!process.argv[1])return!1;try{return realpathSync(process.argv[1])===fileURLToPath(import.meta.url)}catch{return!1}}isEntryPoint()&&main().catch(err=>{console.error(err),process.exit(1)});export{main};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pharn-dev/pharn",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Audit-grade AI development methodology for Claude Code — spec, plan, grill, build, regress, verify, ship.",
5
5
  "keywords": [
6
6
  "claude-code",