@pharn-dev/pharn 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -16
- package/dist/add-RYPFFPXB.js +3 -0
- package/dist/{chunk-LVAJFL6J.js → chunk-256AIEPX.js} +1 -1
- package/dist/{chunk-KZCUUHJT.js → chunk-26RZI2K7.js} +1 -1
- package/dist/chunk-2UADMP7W.js +1 -0
- package/dist/{chunk-LF4PFADC.js → chunk-5YCL3WDS.js} +1 -1
- package/dist/chunk-7UE7LQQP.js +1 -0
- package/dist/chunk-KAXAEUPE.js +2 -0
- package/dist/{chunk-BCURDSJC.js → chunk-NE4LZ2VE.js} +1 -1
- package/dist/{chunk-ZQWLF3HH.js → chunk-ONK3I3FO.js} +1 -1
- package/dist/chunk-PL5ALKBN.js +6 -0
- package/dist/{chunk-DFMTJQO7.js → chunk-QZ4LYI42.js} +1 -1
- package/dist/{chunk-B4EM6WAR.js → chunk-TUHBDIL2.js} +1 -1
- package/dist/chunk-W3TXAEBT.js +1 -0
- package/dist/{chunk-6LOUFC5E.js → chunk-YG2GHTWC.js} +1 -1
- package/dist/chunk-ZL3KBIIS.js +2 -0
- package/dist/index.js +2 -2
- package/dist/init-3EJWD45N.js +29 -0
- package/dist/{list-DZPSZHUH.js → list-JME23KNT.js} +1 -1
- package/dist/remove-B5F6HDFM.js +1 -0
- package/dist/status-LSU7LRGO.js +7 -0
- package/dist/uninstall-YZ67TV5B.js +4 -0
- package/dist/update-DUPETT53.js +13 -0
- package/package.json +1 -1
- package/dist/add-7RVWOQW6.js +0 -3
- package/dist/chunk-62AJFPPH.js +0 -3
- package/dist/chunk-7LD2OYB4.js +0 -2
- package/dist/chunk-FUQURK5N.js +0 -6
- package/dist/chunk-KKY6HERY.js +0 -1
- package/dist/chunk-NVSBRL4G.js +0 -2
- package/dist/chunk-PDDT7V7X.js +0 -1
- package/dist/chunk-SQLIXTIY.js +0 -1
- package/dist/init-VXZACXMC.js +0 -32
- package/dist/remove-5VT6T7R5.js +0 -1
- package/dist/status-2HLMKYJM.js +0 -9
- package/dist/uninstall-WCWOJPEM.js +0 -4
- package/dist/update-YTKILGYA.js +0 -15
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import{archetypesFromSignals,classifyEntry,evidenceFor,isBaseDir,isNextConfigName,mergeSignals,packageFacts,recordedArchetypes}from"./chunk-IC45C3NS.js";import{installPrepared,manifestSources,prepareInstall,scanDest,upstreamSettingsCopyable}from"./chunk-ZL3KBIIS.js";import{CapabilityRemovalError,absentSurfaceLines,planCapabilityRemovals,readUpstreamModels,removalBackups,removalBackupsNow,resolveCapabilities,runNodePrereq}from"./chunk-2UADMP7W.js";import{minCliGate}from"./chunk-QZ4LYI42.js";import{deleteCapabilityDir}from"./chunk-YG2GHTWC.js";import{BACKUP_DIR,ProjectLockedError,applyGitignore,backupAction,backupDirIgnored,createBackup,gitignoreLines,gitignoreReport,interactiveAllowed,planGitignore,printBackupNotice,replacedConfigBackup,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{applyPrettierignore,cap,checkModelsBlock,modelsLabelLines,planPrettierignore,prettierignoreLines,prettierignoreReport,resolvedStageLines,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,freshSettingsHookLines,preservedSettingsHookLines,upstreamSettingsSummary}from"./chunk-7UE7LQQP.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import"./chunk-26RZI2K7.js";import{DEFAULT_INIT_REF,ReleaseResolveError,channelOf,resolveSource,sourceLabel}from"./chunk-256AIEPX.js";import{MODELS_RECORD_KEY,PHARN_CONFIG_FILE,UpstreamManifestError,absentInstallSurfaces,buildRecords,carriedSettingsRecord,collectExpectedInstallPaths,conflictingWriteTargets,detectLayout,layoutPaths,modelsRecordHash,readRecords,readSkillsVersion,recordsBaseline,recordsUnderCapabilities,warnIfOlderCli,writeRecords}from"./chunk-PL5ALKBN.js";import{CLAUDE_AGENTS_DIR,CLAUDE_SETTINGS_FILE,FIRST_FEATURE_COMMAND,PHARN_VERSION,REPO_URL}from"./chunk-W3TXAEBT.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{assertConfigFingerprintUnchanged,color_default,configFingerprint,configPath,readJsonBounded,readPharnConfig,row,userOwnedConfigEntries,writePharnConfig}from"./chunk-5YCL3WDS.js";import{VERSION_RE,isPlainObject,safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";import{intro,log as log3,note as note3,outro as outro2,spinner as spinner2}from"@clack/prompts";var LOGO=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D"];function showBanner(){console.log();for(let line of LOGO)console.log(` ${color_default.cyan(color_default.bold(line))}`);console.log(),console.log(` ${color_default.dim(`Ship features right with Claude Code \xB7 v${PHARN_VERSION}`)}`),console.log()}import{closeSync,constants,fstatSync,lstatSync,openSync,readSync,readdirSync}from"node:fs";import{join,resolve}from"node:path";var SKIP_DIRS=new Set(["node_modules",".git","dist","build",".next","out","coverage",".turbo",".vercel",".nuxt",".svelte-kit",".astro",".cache",".parcel-cache","storybook-static","__pycache__",".yarn"]),ECOSYSTEM_DIRS=new Map([["target",{siblings:["Cargo.toml","pom.xml","build.sbt"]}],["vendor",{siblings:["go.mod","composer.json","Gemfile"]}],["venv",{inside:"pyvenv.cfg"}],[".venv",{inside:"pyvenv.cfg"}]]);function isEcosystemTree(dir,name,siblingFiles){let marker=ECOSYSTEM_DIRS.get(name.toLowerCase());return marker===void 0?!1:"siblings"in marker?marker.siblings.some(file=>siblingFiles.has(file)):lstatSync(join(dir,name,marker.inside),{throwIfNoEntry:!1})?.isFile()===!0}var WALK_LIMITS=Object.freeze({maxDepth:24,maxEntries:5e4}),NO_PACKAGE_JSON={jsProject:!1,nextDependency:!1},NO_SIGNALS={ssr:!1,backend:!1,clientUi:!1},SIGNAL_KEYS=["ssr","backend","clientUi"];function scanFileTree(root,facts=NO_PACKAGE_JSON,limits=WALK_LIMITS){let acc={ssr:!1,backend:!1,clientUi:!1},evidence={},pkg=facts.packageSignals??NO_SIGNALS,budget=limits.maxEntries,truncated=!1,settled=()=>(pkg.ssr||acc.ssr)&&(pkg.backend||acc.backend),readEntries=dir=>{try{return readdirSync(dir,{withFileTypes:!0})}catch{return[]}},walk=(dir,depth,segments,names,inherited)=>{if(budget<=0&&truncated||settled())return;let entries=readEntries(dir).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0),siblingFiles=new Set(entries.filter(e=>e.isFile()).map(e=>e.name)),ctx=isBaseDir(segments)?{jsProject:facts.jsProject,baseDepth:segments.length,nextBase:segments.length===0&&facts.nextDependency||[...siblingFiles].some(isNextConfigName)}:inherited;for(let entry of entries){if(settled())return;let name=entry.name;if(entry.isSymbolicLink())continue;let isDir=entry.isDirectory();if(isDir&&SKIP_DIRS.has(name.toLowerCase())||isDir&&isEcosystemTree(dir,name,siblingFiles)||!isDir&&name.toLowerCase().startsWith(".env")||!isDir&&!entry.isFile())continue;if(depth>limits.maxDepth||budget<=0){truncated=!0;return}budget-=1;let sig=classifyEntry(name,isDir,segments,ctx);for(let key2 of SIGNAL_KEYS)sig[key2]&&evidence[key2]===void 0&&(evidence[key2]=[...names,name].join("/")+(isDir?"/":""));acc=mergeSignals(acc,sig),isDir&&walk(join(dir,name),depth+1,[...segments,name.toLowerCase()],[...names,name],ctx)}};return walk(root,0,[],[],{jsProject:facts.jsProject,baseDepth:0,nextBase:!1}),{signals:acc,evidence,truncated:truncated&&!settled()}}var MAX_PACKAGE_JSON_BYTES=4*1024*1024,PKG_OPEN_FLAGS=constants.O_RDONLY|(constants.O_NONBLOCK??0);function readPackageJsonText(pkgPath){let fd;try{fd=openSync(pkgPath,PKG_OPEN_FLAGS)}catch{return null}try{if(!fstatSync(fd).isFile())return null;let buf=Buffer.alloc(MAX_PACKAGE_JSON_BYTES+1),total=0;for(;total<buf.length;){let n=readSync(fd,buf,total,buf.length-total,null);if(n===0)break;total+=n}return total>MAX_PACKAGE_JSON_BYTES?null:buf.subarray(0,total).toString("utf8").replace(/^\uFEFF/,"")}catch{return null}finally{closeSync(fd)}}function readPackageFacts(cwd){let empty=packageFacts({}),text=readPackageJsonText(resolve(cwd,"package.json"));if(text===null)return{pkg:empty,packageJsonFound:!1};try{let parsed=JSON.parse(text);return typeof parsed!="object"||parsed===null||Array.isArray(parsed)?{pkg:empty,packageJsonFound:!1}:{pkg:packageFacts(parsed),packageJsonFound:!0}}catch{return{pkg:empty,packageJsonFound:!1}}}function detectArchetypesFromProject(cwd){let{pkg,packageJsonFound}=readPackageFacts(cwd),tree=scanFileTree(cwd,{jsProject:packageJsonFound,nextDependency:pkg.nextDependency,packageSignals:pkg.signals}),archetypes=archetypesFromSignals(mergeSignals(pkg.signals,tree.signals));return{archetypes,evidence:evidenceFor(archetypes,pkg.evidence,tree.evidence,pkg.devEvidence),truncated:tree.truncated}}import{existsSync as existsSync2}from"node:fs";import{existsSync}from"node:fs";var MAX_LISTED=10,DRIFT_MARKERS={modified:"(edited)",unrecorded:"(no pharn record)",unverifiable:"(differs from upstream)"},DRIFT_LABEL_ORDER=["modified","unrecorded","unverifiable"],CONFIG_MARKER="(will be rewritten \u2014 backed up first)";function planWriteTargets(params){let{repoDir,projectRoot,capabilities,manifest,records}=params,removals=params.removals??[],conflicts=conflictingWriteTargets({repoDir,projectRoot,capabilities,expected:manifest});if(conflicts.length===0)return{conflicts,labels:new Map,configBackedUp:!1,removals};let labels=params.labels??scanDest({repoDir,projectRoot,rels:conflicts.filter(p=>manifest.has(p)),sources:manifestSources(repoDir,manifest),records}).labels,configBackedUp=conflicts.includes(PHARN_CONFIG_FILE)&&replacedConfigBackup(projectRoot).length>0,rank=p=>{let label=labels.get(p);return label!==void 0?DRIFT_LABEL_ORDER.indexOf(label):configBackedUp&&p===PHARN_CONFIG_FILE?DRIFT_LABEL_ORDER.length:DRIFT_LABEL_ORDER.length+1};return{conflicts:[...conflicts].sort((a,b)=>rank(a)-rank(b)),labels,configBackedUp,removals}}function removalLines(removals){return removals.filter(r=>r.present).map(r=>{let n=r.backups.length;return n===0?` \u2022 ${r.dir}/ (${r.cap.role}:${r.cap.name})`:` \u2022 ${r.dir}/ (${r.cap.role}:${r.cap.name} \u2014 ${n} file(s) backed up to ${BACKUP_DIR}/ first)`})}function targetLines(plan,max){let{conflicts:paths,labels,configBackedUp}=plan,shown=max===void 0?paths:paths.slice(0,max),lines=shown.map(p=>{let label=labels.get(p);return label!==void 0?` \u2022 ${p} ${DRIFT_MARKERS[label]}`:configBackedUp&&p===PHARN_CONFIG_FILE?` \u2022 ${p} ${CONFIG_MARKER}`:` \u2022 ${p}`}),more=paths.length-shown.length;return more>0&&lines.push(` \u2026and ${more} more`),lines}var OverwriteRefusedError=class extends Error{constructor(message){super(message),this.name="OverwriteRefusedError"}},YES_WAYS_FORWARD=["--yes never overwrites. Run `pharn init` in a terminal to review and confirm the overwrite,","`pharn init --dry-run` to see the whole plan, or `pharn update` to refresh an existing install."];function existingConfigRefusal(projectRoot){return existsSync(safeJoin(projectRoot,PHARN_CONFIG_FILE))?[`pharn init --yes installs only into a project where none of its files exists yet, and ${PHARN_CONFIG_FILE} already exists.`,...YES_WAYS_FORWARD].join(`
|
|
2
|
+
`):null}function refuseExistingTargets(plan){if(plan.conflicts.length===0)return;let n=plan.conflicts.length;throw new OverwriteRefusedError([`pharn init --yes installs only into a project where none of its files exists yet, and ${n} of them already exist:`,...targetLines(plan,MAX_LISTED),...YES_WAYS_FORWARD].join(`
|
|
3
|
+
`))}function capabilityKey(cap2){return`${cap2.role}:${cap2.name}`}var UNREADABLE_REASON_MAX=200;function readPreviousConfig(cwd){let fingerprint=configFingerprint(cwd);try{let config=readPharnConfig(cwd),unreadable=config===null&&fingerprint!=="absent"?describeUnreadConfig(cwd):null;return{fingerprint,config,unreadable}}catch(err){let reason=escapeUnsafe(firstSentence(errorMessage(err)));return{fingerprint,config:null,unreadable:terminalSafe(reason,{max:UNREADABLE_REASON_MAX})}}}function firstSentence(text){let quoted=!1;for(let i=0;i<text.length;i++){let ch=text[i];if(ch==="\\")i++;else if(ch==='"')quoted=!quoted;else if(ch==="."&&!quoted&&(i+1===text.length||/\s/.test(text[i+1])))return text.slice(0,i)}return text}function describeUnreadConfig(cwd){let read=readJsonBounded(configPath(cwd));if(read.kind==="unusable")return`it ${read.reason}`;if(read.kind!=="ok")return"it changed while init was reading it";let raw=read.value;return isPlainObject(raw)?typeof raw.skillsVersion!="string"?'it has no "skillsVersion" string':'it has neither a "capabilities" key nor a "modules" array':"it is not a JSON object"}function previousConfigLines(previous){return previous.unreadable===null?[]:[` the previous pharn.config.json could not be read (${previous.unreadable}); nothing is carried over, so manual capabilities will be dropped`]}function carryOver(previous,index,resolved){let inIndex=new Set(index.capabilities.map(capabilityKey)),frozen=new Set(index.unknown.map(capabilityKey)),selected=new Set(resolved.selected.map(capabilityKey)),manualKeys=new Set,kept=[],extra=[],gone=[],dropped=[],seen=new Set;for(let cap2 of previous?.capabilities??[]){let k=capabilityKey(cap2);if(!seen.has(k)){if(seen.add(k),frozen.has(k)){kept.push({...cap2});continue}if(cap2.source!=="manual"){selected.has(k)||dropped.push({cap:cap2,reason:cap2.source==="auto"||inIndex.has(k)?"dropped-unselected":"dropped-gone"});continue}if(!inIndex.has(k)){gone.push(cap2),dropped.push({cap:cap2,reason:"dropped-gone"});continue}manualKeys.add(k),selected.has(k)||extra.push(cap2)}}return{manualKeys,kept,extra,gone,dropped,previousStamp:previous?{skillsVersion:previous.skillsVersion,commit:previous.commit}:null}}function planInitRemovals(cwd,carry,records){let drops=carry.dropped??[];return drops.length===0?[]:planCapabilityRemovals({cwd,paths:layoutPaths("pharn"),drops,records,command:"init"})}function resolveInitSelection(params){let{cwd,archetypes,index}=params,resolved=resolveCapabilities(archetypes,index),previous=readPreviousConfig(cwd),carry=carryOver(previous.config,index,resolved),extraKeys=new Set(carry.extra.map(capabilityKey)),selection=carry.extra.length?{selected:[...resolved.selected,...carry.extra.map(c=>({name:c.name,role:c.role,matched:"manual"}))],skipped:resolved.skipped.filter(s=>!extraKeys.has(capabilityKey(s)))}:resolved;return{previous,carry,selection}}function reinstallBaseline(cwd,carry){return carry.previousStamp===null?null:recordsBaseline(readRecords(cwd)).records}function initRecordedPaths(params){let{cwd,manifest,carry,capabilities,layout,baseline}=params,kept=carry.kept.length===0||baseline===null?{}:recordsUnderCapabilities(baseline,layoutPaths(layout),carry.kept),orphans=findOrphans({projectRoot:cwd,records:baseline,expected:manifest,capabilities:[...capabilities,...carry.kept],frozen:carry.kept}).records;return[...Object.keys(kept),...Object.keys(orphans),...manifest.keys()]}function readCarriedEntries(cwd){let read=readJsonBounded(configPath(cwd));return read.kind!=="ok"?{}:isPlainObject(read.value)?userOwnedConfigEntries(read.value):{}}function previousChannelLines(params){let{previous,channel,explicit,source}=params;if(previous===null||explicit)return[];if(channel!=="latest"||channelOf(previous)!=="main")return[];let lines=[" previously followed: main (the pharn-oss tip) \u2014 pass --ref main to keep it"],installed=previous.skillsVersion;return source.kind==="release"&&typeof installed=="string"&&versionStatus({installed,latest:source.version}).ahead&&lines.push(` installed v${terminalSafe(installed,{max:40})} is newer than release ${source.tag} \u2014 this re-install goes back to it`),lines}function buildInitPlan(params){let{repoDir,cwd,sha,source,channel,archetypes,index,chosen}=params,origin=params.origin??{kind:"detected",evidence:[],truncated:!1},{selection,carry}=chosen,layout=detectLayout(repoDir),manifest=collectExpectedInstallPaths({repoDir,capabilities:selection.selected}),prepared=prepareInstall(repoDir,cwd,selection.selected,manifest),baseline=reinstallBaseline(cwd,carry),removals=planInitRemovals(cwd,carry,baseline),scan=scanDest({repoDir,projectRoot:cwd,rels:[...manifest.keys()],sources:manifestSources(repoDir,manifest),records:baseline}),writeTargets=planWriteTargets({repoDir,projectRoot:cwd,capabilities:selection.selected,manifest,records:baseline,removals,labels:scan.labels}),{conflicts,labels,configBackedUp}=writeTargets,existing=new Set(conflicts),targets=[...new Set([...manifest.keys(),PHARN_CONFIG_FILE])].sort().map(rel=>({rel,action:existing.has(rel)?"overwrite":"create",label:labels.get(rel)??(configBackedUp&&rel===PHARN_CONFIG_FILE?"rewritten":null)})),backups=[...new Set([...[...labels.keys()].sort(),...configBackedUp?[PHARN_CONFIG_FILE]:[],...removalBackups(removals)])],settingsPreserved=existsSync2(safeJoin(cwd,CLAUDE_SETTINGS_FILE)),upstreamModels=readUpstreamModels(repoDir);return{report:{archetypes,archetypeOrigin:origin,previousArchetypes:recordedArchetypes(chosen.previous.config?.archetypes),channelLines:previousChannelLines({previous:chosen.previous.config,channel,explicit:params.refExplicit??!1,source}),previousConfigLines:previousConfigLines(chosen.previous),channel,source,commit:sha,skillsVersion:readSkillsVersion(repoDir),layout,selection,carry:{manual:[...carry.manualKeys].sort(),extra:carry.extra,kept:[...carry.kept],gone:carry.gone},unknownCapabilities:index.unknown,targets,conflicts,configBackedUp,removals,backups,counts:{create:targets.length-existing.size,overwrite:existing.size,backup:backups.length},settingsPreserved,hookWiring:settingsPreserved?diffHookWiring(repoDir,cwd):null,freshSettings:!settingsPreserved&&upstreamSettingsCopyable(repoDir)?upstreamSettingsSummary(repoDir):null,models:upstreamModels.kind==="ok"?{outcome:"copy",reasons:[]}:upstreamModels.kind==="absent"?{outcome:"none",reasons:[]}:{outcome:"rejected",reasons:upstreamModels.reasons},absentUpstream:absentInstallSurfaces({repoDir}),carriedConfigKeys:Object.keys(readCarriedEntries(cwd)),gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,initRecordedPaths({cwd,manifest,carry,capabilities:selection.selected,layout,baseline}))},apply:{prepared,drifted:scan.drifted,seen:scan.seen,baseline,removals,targets:writeTargets,fingerprint:chosen.previous.fingerprint}}}var INIT_SCHEMA_VERSION=1,MAX_REASON=300,MAX_UNKNOWN_FIELD=200,MAX_EVIDENCE=200,key=c=>`${c.role}:${c.name}`;function buildInitReport(p){return{schemaVersion:INIT_SCHEMA_VERSION,command:"init",dryRun:!0,status:"planned",channel:p.channel,source:{kind:p.source.kind,tag:p.source.kind==="release"?p.source.tag:null},commit:p.commit,skillsVersion:p.skillsVersion,layout:p.layout,archetypes:[...p.archetypes],archetypeSource:p.archetypeOrigin.kind,detectedArchetypes:p.archetypeOrigin.kind==="flag"?[...p.archetypeOrigin.detected]:null,archetypeEvidence:p.archetypeOrigin.evidence.map(e=>({archetype:e.archetype,source:e.source,value:e.source==="dependency"||e.source==="devDependency"?e.name:e.source==="path"?cap(e.path,MAX_EVIDENCE):null})),...p.archetypeOrigin.truncated?{detectionTruncated:!0}:{},capabilities:{selected:p.selection.selected.map(c=>({role:c.role,name:c.name,matched:Array.isArray(c.matched)?[...c.matched]:c.matched})),skipped:p.selection.skipped.map(c=>({role:c.role,name:c.name,reason:cap(c.reason,MAX_REASON)})),carried:{manual:[...p.carry.manual],kept:p.carry.kept.map(key),dropped:p.carry.gone.map(key)},...p.removals.length>0?{removals:p.removals.map(r=>({role:r.cap.role,name:r.cap.name,reason:r.reason,dir:r.dir,present:r.present,backups:[...r.backups]}))}:{}},unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),targets:p.targets.map(t=>({rel:t.rel,action:t.action,label:t.label})),backups:[...p.backups],counts:{create:p.counts.create,overwrite:p.counts.overwrite,backup:p.counts.backup},yesWouldProceed:p.counts.overwrite===0,settings:{preserved:p.settingsPreserved},hooks:p.hookWiring===null?null:{status:p.hookWiring.status,missing:p.hookWiring.missing,localOnly:p.hookWiring.localOnly??[],file:p.hookWiring.file??null,reason:p.hookWiring.reason??null,...p.hookWiring.replace?.length?{replace:p.hookWiring.replace}:{}},...p.freshSettings===null?{}:{settingsHooks:p.freshSettings.status==="ok"?{status:"ok",hooks:p.freshSettings.hooks.map(e=>({event:e.event,matcher:e.matcher,command:e.command,args:[...e.args]})),otherKeys:p.freshSettings.otherKeys.map(k=>cap(k,MAX_UNKNOWN_FIELD)),skipped:p.freshSettings.skipped}:{status:"unreadable",reason:cap(p.freshSettings.reason,MAX_REASON)}},...p.absentUpstream.length>0?{absentUpstream:p.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))}:{},models:{outcome:p.models.outcome,reasons:p.models.reasons.map(r=>cap(r,MAX_REASON))},config:{carriedKeys:p.carriedConfigKeys.map(k=>cap(k,MAX_UNKNOWN_FIELD))},...gitignoreKey(p.gitignore),...prettierignoreKey(p.prettierignore)}}function prettierignoreKey(plan){let report=prettierignoreReport(plan);return report===null?{}:{prettierignore:report}}function gitignoreKey(plan){let report=gitignoreReport(plan);return report===null?{}:{gitignore:report}}import{existsSync as existsSync3}from"node:fs";import{dirname,join as join2,resolve as resolve2}from"node:path";function runGitPrereq(opts={}){let cwd=process.cwd();if(!existsSync3(resolve2(cwd,".git"))){let root=findAncestorGitRoot(cwd);fail(root===null?`git not found.
|
|
4
|
+
Run: git init && git add -A && git commit -m 'init'
|
|
5
|
+
Then re-run: npx @pharn-dev/pharn init`:`${escapeUnsafe(cwd)} is inside the git repository at ${escapeUnsafe(root)}, not at its root.
|
|
6
|
+
Run \`pharn init\` from the repository root (${escapeUnsafe(root)}).`,opts.json??!1)}}function findAncestorGitRoot(start){let dir=resolve2(start);for(;;){let parent=dirname(dir);if(parent===dir)return null;if(dir=parent,existsSync3(join2(dir,".git")))return dir}}function fail(message,json){throw CliError.error(message,{json})}import{confirm,isCancel,log}from"@clack/prompts";function recordedSkillsVersion(cwd){let read=readJsonBounded(safeJoin(cwd,PHARN_CONFIG_FILE));if(read.kind!=="ok")return null;let parsed=read.value;if(typeof parsed!="object"||parsed===null)return null;let version=parsed.skillsVersion;return typeof version=="string"&&VERSION_RE.test(version)?version:null}function labelLine(label,n){let one=n===1;switch(label){case"modified":return`${n} of them changed since pharn wrote ${one?"it":"them"} (your edits).`;case"unrecorded":return`${n} of them ${one?"differs":"differ"} from upstream, and pharn has no record of ${one?"it":"them"}.`;case"unverifiable":return`${n} of them ${one?"differs":"differ"} from upstream \u2014 pharn has no record to tell your edits from upstream changes.`}}async function confirmWriteTargets(repoDir,cwd,selection,context={}){let{conflicts,labels,configBackedUp,removals}=context.targets??planWriteTargets({repoDir,projectRoot:cwd,capabilities:selection.selected,manifest:context.manifest??collectExpectedInstallPaths({repoDir,capabilities:selection.selected}),records:context.records??null,removals:context.removals}),deletes=removalLines(removals);if(conflicts.length===0&&deletes.length===0)return"proceed";let deleteBackups=removals.filter(r=>r.present).reduce((n,r)=>n+r.backups.length,0),deleteBlock=deletes.length>0?`${conflicts.length>0?`
|
|
7
|
+
`:""}These capability directories are no longer selected and will be DELETED (pharn runs every capability directory on disk):
|
|
8
|
+
${deletes.join(`
|
|
9
|
+
`)}${deleteBackups>0?`
|
|
10
|
+
${deleteBackups} file(s) in them pharn did not write will be copied to ${BACKUP_DIR}/ first.`:""}`:"";if(conflicts.length===0){log.warn(`PHARN installs into your existing project. ${deleteBlock}`);let result2=await confirm({message:"Continue and delete them?",initialValue:!1});return isCancel(result2)?"cancel":result2===!0?"proceed":"decline"}let list=targetLines({conflicts,labels,configBackedUp},MAX_LISTED).join(`
|
|
11
|
+
`),counts=DRIFT_LABEL_ORDER.map(label=>[label,[...labels.values()].filter(l=>l===label).length]).filter(([,n])=>n>0),editsLine=labels.size>0?`
|
|
12
|
+
${counts.map(([label,n])=>labelLine(label,n)).join(`
|
|
13
|
+
`)}
|
|
14
|
+
${labels.size===1?"It":`All ${labels.size}`} will be copied to ${BACKUP_DIR}/ before being overwritten.`:"",configLine=configBackedUp?`
|
|
15
|
+
${PHARN_CONFIG_FILE} will be rewritten (models reset to its default); it will be copied to ${BACKUP_DIR}/ first.`:"",version=conflicts.includes(PHARN_CONFIG_FILE)?recordedSkillsVersion(cwd):null,intro2=version===null?"PHARN installs into your existing project.":`PHARN installs into your existing project (currently at skills v${version}).`;log.warn(`${intro2} These paths already exist and may be overwritten:
|
|
16
|
+
${list}${editsLine}${configLine}${deleteBlock?`
|
|
17
|
+
${deleteBlock}`:""}`);let result=await confirm({message:deletes.length>0?"Continue, overwrite and delete?":"Continue and overwrite?",initialValue:!1});return isCancel(result)?"cancel":result===!0?"proceed":"decline"}import{isCancel as isCancel2,note,select}from"@clack/prompts";var MAX_EVIDENCE_CHARS=120;function describeEvidence(evidence){switch(evidence.source){case"dependency":return`${evidence.name} (package.json)`;case"devDependency":return`${evidence.name} (package.json devDependencies)`;case"path":return terminalSafe(evidence.path,{max:MAX_EVIDENCE_CHARS});case"none":return"no framework signal found"}}var sameSet=(a,b)=>a.length===b.length&&a.every(x=>b.includes(x)),TRUNCATED_LINE=` detection stopped early: it examines at most ${WALK_LIMITS.maxEntries.toLocaleString("en-US")} entries, ${WALK_LIMITS.maxDepth} directories deep, so these archetypes may be incomplete \u2014 pass --archetype <list> if they are wrong`;function archetypeOriginLines(archetypes,origin,previous=null){let lines=[];if(origin.kind==="flag")lines.push(row("Archetypes (--archetype)",archetypes.join(", ")),` detection found ${origin.detected.join(", ")} (not used)`);else{lines.push(row("Detected archetypes",archetypes.join(", ")));for(let e of origin.evidence)lines.push(` ${e.archetype.padEnd(8)}\u2190 ${describeEvidence(e)}`);origin.truncated&&lines.push(TRUNCATED_LINE)}return previous!==null&&!sameSet(previous,archetypes)&&lines.push(` previously recorded: ${previous.join(", ")} \u2014 pass --archetype ${previous.join(",")} to keep them`),lines}function describeMatched(matched){return matched==="universal"?"universal":matched==="manual"?"added by hand":matched.join(", ")}function archetypeSummaryLines(archetypes,selection,origin={kind:"detected",evidence:[],truncated:!1},previous=null,rerunLines=[]){let lines=["\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"," PHARN Install Summary (archetype)","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","",...archetypeOriginLines(archetypes,origin,previous),...rerunLines,"",` CAPABILITIES SELECTED (${selection.selected.length})`,...selection.selected.length>0?selection.selected.map(c=>row(`${c.name} (${c.role})`,describeMatched(c.matched))):[" (none)"]];return selection.skipped.length>0&&lines.push("",` CAPABILITIES SKIPPED (${selection.skipped.length})`,...selection.skipped.map(c=>row(`${c.name} (${c.role})`,c.reason))),lines.push(""," Installs PHARN product commands + write-gating hooks into .claude/"," (an existing .claude/settings.json is preserved, not overwritten).","","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),lines}async function runArchetypeSummary(archetypes,selection,origin={kind:"detected",evidence:[],truncated:!1},previous=null,rerunLines=[]){note(archetypeSummaryLines(archetypes,selection,origin,previous,rerunLines).join(`
|
|
18
|
+
`));let action=await select({message:"Ready to install?",initialValue:"install",options:[{value:"install",label:"Yes, install"},{value:"cancel",label:"Cancel"}]});return isCancel2(action)?"cancel":action==="install"?"install":"cancel"}import{log as log2,note as note2,outro,spinner}from"@clack/prompts";async function runInstallArchetype(repoDir,cwd,archetypes,selection,commit,carry,plan){let startedAt=Date.now(),{prepared,baseline,removals}=plan;assertConfigFingerprintUnchanged(cwd,plan.fingerprint,"init");let deletes=removals.filter(r=>r.present),overwriteBackups=[...plan.drifted,...replacedConfigBackup(cwd)],toBackUp=[...new Set([...overwriteBackups,...removalBackupsNow({cwd,removals,records:baseline,command:"init"})])];if(toBackUp.length>0){let backupDir=createBackup(cwd,toBackUp),action=backupAction(overwriteBackups.length>0,deletes.length>0);printBackupNotice({dir:backupDir,saved:toBackUp.length,action,gitignored:backupDirIgnored(cwd,planGitignore(cwd))})}if(deletes.length>0){let paths=layoutPaths("pharn");for(let removal of deletes)deleteCapabilityDir(cwd,paths,removal.cap);log2.info(`Deleted ${deletes.length} capability director${deletes.length===1?"y":"ies"} no longer installed: ${deletes.map(r=>`${r.dir}/`).join(", ")}.`)}let s=spinner();s.start("Installing capabilities");let capabilities,settingsPreserved,settingsWritten,skillsVersion,layout,docsWritten;try{let result=installPrepared(repoDir,cwd,selection,prepared,plan.seen);capabilities=result.capabilities,settingsPreserved=result.settingsPreserved,settingsWritten=result.settingsWritten,layout=result.layout,docsWritten=result.docs,skillsVersion=readSkillsVersion(repoDir)}catch(err){throw s.stop("Failed to install capabilities"),err}if(s.stop("Capabilities installed"),settingsPreserved){log2.info(`Existing ${CLAUDE_SETTINGS_FILE} preserved \u2014 pharn never overwrites it.`);let hookLines=preservedSettingsHookLines(diffHookWiring(repoDir,cwd));hookLines&¬e2(hookLines.join(`
|
|
19
|
+
`),"HOOKS")}else settingsWritten&¬e2(freshSettingsHookLines(upstreamSettingsSummary(repoDir)).join(`
|
|
20
|
+
`),"HOOKS");let upstreamModels=readUpstreamModels(repoDir);upstreamModels.kind==="invalid"&&log2.warn(["pharn-oss's models block was not written; this pharn rejects it:",...upstreamModels.reasons.map(reason=>` ${terminalSafe(reason,{max:300})}`),"If pharn-oss changed its models format, upgrade pharn","(npm i -g @pharn-dev/pharn@latest) and run `pharn update`."].join(`
|
|
21
|
+
`));let models=upstreamModels.kind==="ok"?upstreamModels.block:void 0,absent=absentInstallSurfaces({repoDir}),absentLines=absentSurfaceLines(absent);absentLines&&log2.warn(absentLines.join(`
|
|
22
|
+
`));let agentsWritten=[...prepared.manifest.keys()].some(rel=>rel.startsWith(`${CLAUDE_AGENTS_DIR}/`)),claudeWritten=[...["commands","hooks"].filter(surface=>!absent.some(a=>a.surface===surface)),...agentsWritten?["agents"]:[]],frozenCapabilities=[...new Set(carry.kept.map(c=>`${c.role}:${c.name}`))].sort(),config={pharnVersion:PHARN_VERSION,skillsVersion,repo:REPO_URL.replace(/^github\.com\//,""),commit,...carry.ref==="latest"?{ref:"latest"}:{},installedAt:new Date().toISOString(),models,archetypes,capabilities:[...capabilities.map(c=>({...c,source:carry.manualKeys.has(`${c.role}:${c.name}`)?"manual":"auto"})),...carry.kept.map(c=>({...c}))],layout,...frozenCapabilities.length>0?{frozenCapabilities}:{}},files={...keptRecords(baseline,carry,layout),...findOrphans({projectRoot:cwd,records:baseline,expected:prepared.manifest,capabilities:[...capabilities,...carry.kept],frozen:carry.kept}).records,...settingsWritten?buildRecords(cwd,[CLAUDE_SETTINGS_FILE]):carriedSettingsRecord(cwd,baseline),...buildRecords(cwd,prepared.manifest.keys()),...models!==void 0?{[MODELS_RECORD_KEY]:modelsRecordHash(models)}:{}};await writeRecords(cwd,{skillsVersion,commit,files}),await writePharnConfig(cwd,{...config,...readCarriedEntries(cwd)});let gitignore=await applyGitignore(cwd),gitignoreReport2=gitignoreLines(gitignore);gitignoreReport2?.warn&&log2.warn(gitignoreReport2.text);let prettierignore=await applyPrettierignore(cwd,Object.keys(files)),prettierignoreReport2=prettierignoreLines(prettierignore);prettierignoreReport2?.warn&&log2.warn(prettierignoreReport2.text);let elapsed=((Date.now()-startedAt)/1e3).toFixed(1),check=color_default.green("\u2714"),grillers=capabilities.filter(c=>c.role==="griller").length,lenses=capabilities.filter(c=>c.role==="lens").length,modelsCheck=checkModelsBlock(models),modelsSection=modelsCheck.kind==="valid"?["",color_default.bold("Declared model per stage")+` ${color_default.dim("(pharn.config.json \u2192 models, from pharn-oss)")}`,...resolvedStageLines(modelsCheck.stages).map(line=>` ${line}`),...modelsLabelLines(layoutPaths(layout).floor).map(line=>` ${color_default.dim(line)}`)]:[],docsLine=docsWritten.length?`${check} ${docsWritten.length} trusted doc${docsWritten.length===1?"":"s"} written \u2192 ${color_default.dim(docsWritten.join(", "))}`:`${color_default.yellow("!")} no trusted docs written ${color_default.dim("(the fetched repo shipped none at their expected paths)")}`;outro([`${check} ${capabilities.length} capabilit${capabilities.length===1?"y":"ies"} installed \u2192 ${color_default.dim(`(${grillers} griller${grillers===1?"":"s"}, ${lenses} lens${lenses===1?"":"es"})`)}`,claudeWritten.length?`${check} PHARN ${claudeWritten.join(" + ")} written \u2192 ${color_default.dim(".claude/")}`:`${color_default.yellow("!")} no PHARN commands or hooks written ${color_default.dim("(the fetched repo shipped none)")}`,docsLine,`${check} pharn.config.json written ${color_default.dim(`(skills v${skillsVersion}, archetypes: ${archetypes.join(", ")})`)}`,...gitignore.action==="create"||gitignore.action==="append"?[`${check} .gitignore ${gitignore.action==="create"?"created":"updated"} \u2192 ${color_default.dim(gitignore.entries.join(", "))}`]:[],...prettierignore.action==="create"||prettierignore.action==="append"?[`${check} .prettierignore ${prettierignore.action==="create"?"created":"updated"} \u2192 ${color_default.dim(`${prettierignore.entries.length} path${prettierignore.entries.length===1?"":"s"} pharn installs or rewrites`)}`]:[],`${color_default.dim(`Done in ${elapsed}s`)}`,...modelsSection,"",color_default.bold("Next steps"),` ${color_default.cyan("1.")} ${color_default.bold("claude")} ${color_default.dim("open Claude Code")}`,` ${color_default.cyan("2.")} ${color_default.bold(FIRST_FEATURE_COMMAND)} ${color_default.dim("capture your first feature's intent")}`].join(`
|
|
23
|
+
`))}function keptRecords(baseline,carry,layout){return carry.kept.length===0||baseline===null?{}:recordsUnderCapabilities(baseline,layoutPaths(layout),carry.kept)}async function runInit(opts={}){let yes=opts.yes??!1,json=opts.json??!1,dryRun=(opts.dryRun??!1)||json;if(runNodePrereq("init",{json}),runGitPrereq({json}),!dryRun&&!yes&&!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("pharn init is interactive \u2014 run it in an interactive terminal. To install without prompts, pass --yes: it installs only into a project where none of its files exists yet, and never overwrites. To see what init would do, pass --dry-run.");if(yes&&!dryRun){let refusal=existingConfigRefusal(process.cwd());if(refusal!==null)throw CliError.refusal(refusal)}json||(showBanner(),intro(dryRun?"pharn init --dry-run":"init wizard"));let run=()=>runInitArchetype({channel:opts.ref??DEFAULT_INIT_REF,refExplicit:opts.ref!==void 0,override:opts.archetypes,yes,dryRun,json});if(dryRun){await run();return}try{await withProjectLock(process.cwd(),"init",run)}catch(err){throw err instanceof ProjectLockedError?CliError.refusal(err.message):err}}function silentSpinner(){return{start:()=>{},stop:()=>{}}}async function runInitArchetype(mode){let{channel,refExplicit,override,yes,dryRun,json}=mode,warn=json?message=>logErrorPlain(message):message=>log3.warn(message),cwd=process.cwd(),detection=detectArchetypesFromProject(cwd),archetypes=override??detection.archetypes,origin=override?{kind:"flag",detected:detection.archetypes,evidence:detection.evidence,truncated:detection.truncated}:{kind:"detected",evidence:detection.evidence,truncated:detection.truncated},proxyNotice=detectProxyNotice(process.env);proxyNotice&&warn(proxyNoticeMessage(proxyNotice));let s=json?silentSpinner():spinner2();s.start(`Fetching PHARN from ${REPO_URL}`);let repo;try{repo=await fetchRepo(await resolveSource(channel))}catch(err){throw s.stop("Failed to fetch PHARN"),CliError.failure(err,{json,message:err instanceof ReleaseResolveError||err instanceof UpstreamManifestError?err.message:`Could not reach ${REPO_URL}: ${errorMessage(err)}`})}if(s.stop(`PHARN fetched from ${sourceLabel(repo.source)}`),dryRun){await runInitDryRun(repo,cwd,archetypes,origin,{channel,refExplicit,json});return}try{let gate=minCliGate(repo.dir,PHARN_VERSION);if(gate.warning&&log3.warn(gate.warning),gate.refusal)throw CliError.refusal(gate.refusal);{let index=parseCapabilityIndex(repo.dir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&log3.warn(unknownWarning);let chosen=resolveInitSelection({cwd,archetypes,index}),{previous,carry,selection}=chosen;warnIfOlderCli(previous.config),reportCarry(carry);let recorded=recordedArchetypes(previous.config?.archetypes),rerunLines=[...previousConfigLines(previous),...previousChannelLines({previous:previous.config,channel,explicit:refExplicit,source:repo.source})],action;if(yes?(note3(archetypeSummaryLines(archetypes,selection,origin,recorded,rerunLines).join(`
|
|
24
|
+
`)),action="install"):action=await runArchetypeSummary(archetypes,selection,origin,recorded,rerunLines),action!=="install")throw CliError.cancel();let planned=buildInitPlan({repoDir:repo.dir,cwd,sha:repo.sha,source:repo.source,channel,archetypes,origin,index,chosen,refExplicit}),targets=planned.apply.targets;if(yes)refuseExistingTargets(targets);else if(await confirmWriteTargets(repo.dir,cwd,selection,{targets})!=="proceed")throw CliError.cancel();await runInstallArchetype(repo.dir,cwd,archetypes,selection,repo.sha,channel==="latest"?{...carry,ref:"latest"}:carry,planned.apply)}}catch(err){throw err instanceof OverwriteRefusedError||err instanceof CapabilityRemovalError?CliError.refusal(err.message):CliError.failure(err)}finally{repo.cleanup()}}function reportCarry(carry){carry.extra.length&&log3.info(`Keeping ${carry.extra.length} capabilit${carry.extra.length===1?"y":"ies"} you added by hand: ${carry.extra.map(capabilityKey).join(", ")}.`),carry.kept.length&&log3.info(`Keeping ${carry.kept.length} capabilit${carry.kept.length===1?"y":"ies"} as installed \u2014 upstream still ships ${carry.kept.length===1?"it":"them"} but this pharn cannot read ${carry.kept.length===1?"it":"them"} (see above): ${carry.kept.map(capabilityKey).join(", ")}. Files and config entries are left as they are; \`pharn update\` re-checks them.`),carry.gone.length&&log3.warn(`Not keeping ${carry.gone.length} capabilit${carry.gone.length===1?"y":"ies"} you added by hand that upstream no longer ships: ${carry.gone.map(capabilityKey).join(", ")}. ${carry.gone.length===1?"It is":"They are"} dropped from pharn.config.json, and ${carry.gone.length===1?"its directory is":"their directories are"} deleted (files pharn did not write are backed up first).`);let goneKeys=new Set(carry.gone.map(capabilityKey)),unselected=carry.dropped.filter(d=>!goneKeys.has(capabilityKey(d.cap)));unselected.length&&log3.warn(`Not keeping ${unselected.length} capabilit${unselected.length===1?"y":"ies"} your archetypes no longer select${unselected.some(d=>d.reason==="dropped-gone")?" (or upstream no longer ships)":""}: ${unselected.map(d=>capabilityKey(d.cap)).join(", ")}. ${unselected.length===1?"It is":"They are"} dropped from pharn.config.json, and ${unselected.length===1?"its directory is":"their directories are"} deleted (files pharn did not write are backed up first).`)}async function runInitDryRun(repo,cwd,archetypes,origin,mode){let{channel,refExplicit,json}=mode,warn=json?message=>logErrorPlain(message):message=>log3.warn(message),plan,carry;try{let gate=minCliGate(repo.dir,PHARN_VERSION);if(gate.warning&&warn(gate.warning),gate.refusal)throw CliError.refusal(gate.refusal,{json});let index=parseCapabilityIndex(repo.dir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&warn(unknownWarning);let chosen=resolveInitSelection({cwd,archetypes,index});warnIfOlderCli(chosen.previous.config,{json}),carry=chosen.carry,plan=buildInitPlan({repoDir:repo.dir,cwd,sha:repo.sha,source:repo.source,channel,archetypes,origin,index,chosen,refExplicit}).report}catch(err){throw err instanceof CapabilityRemovalError?CliError.refusal(err.message,{json}):CliError.failure(err,{json})}finally{repo.cleanup()}if(json){console.log(serializeJsonReport(buildInitReport(plan)));return}reportCarry(carry),reportInitDryRun(plan)}function reportInitDryRun(r){note3(archetypeSummaryLines(r.archetypes,r.selection,r.archetypeOrigin,r.previousArchetypes,[...r.previousConfigLines,...r.channelLines]).join(`
|
|
25
|
+
`));let labels=new Map(r.targets.flatMap(t=>t.label===null||t.label==="rewritten"?[]:[[t.rel,t.label]])),lines=[];r.counts.overwrite>0?(lines.push(` WOULD OVERWRITE ${r.counts.overwrite} existing file(s)`),lines.push(...targetLines({conflicts:r.conflicts,labels,configBackedUp:r.configBackedUp}))):lines.push(" Nothing in your project would be overwritten."),lines.push("",` WOULD CREATE ${r.counts.create} file(s)`);let deletes=removalLines(r.removals);deletes.length>0&&lines.push("",` WOULD DELETE ${deletes.length} capability director${deletes.length===1?"y":"ies"} dropped from your config`,...deletes),r.counts.backup>0&&lines.push("",` WOULD BACK UP ${r.counts.backup} file(s) to ${BACKUP_DIR}/<timestamp>/ first \u2014 the marked ones above${deletes.length>0?" and the deleted directories\u2019 files pharn did not write":""}`),lines.push("",` Would write pharn.config.json (skills v${r.skillsVersion}, ${r.layout} layout, archetypes: ${r.archetypes.join(", ")})`),r.configBackedUp&&lines.push(` The existing pharn.config.json would be rewritten (models reset to its default); it would be copied to ${BACKUP_DIR}/ first.`),r.carriedConfigKeys.length>0&&lines.push(` Would keep your own pharn.config.json keys: ${r.carriedConfigKeys.map(k=>terminalSafe(k,{max:200})).join(", ")}`),r.settingsPreserved?lines.push(` Would preserve the existing ${CLAUDE_SETTINGS_FILE} \u2014 pharn never overwrites it.`):r.freshSettings!==null&&lines.push(` Would write ${CLAUDE_SETTINGS_FILE} from upstream; see HOOKS.`);let gitignore=gitignoreLines(r.gitignore,{preview:!0});gitignore!==null&&!gitignore.warn&&lines.push(` ${gitignore.text}`);let prettierignore=prettierignoreLines(r.prettierignore,{preview:!0});prettierignore!==null&&!prettierignore.warn&&lines.push(` ${prettierignore.text}`),lines.push("",r.counts.overwrite===0?" `pharn init --yes` would install (nothing would be overwritten).":` \`pharn init --yes\` would refuse: ${r.counts.overwrite} existing file(s) would be overwritten.`),note3(lines.join(`
|
|
26
|
+
`),"PLAN"),gitignore?.warn&&log3.warn(gitignore.text),prettierignore?.warn&&log3.warn(prettierignore.text);let hookLines=r.hookWiring!==null?preservedSettingsHookLines(r.hookWiring):r.freshSettings!==null?freshSettingsHookLines(r.freshSettings):null;hookLines&¬e3(hookLines.join(`
|
|
27
|
+
`),"HOOKS");let absentLines=absentSurfaceLines(r.absentUpstream,{preview:!0});absentLines&&log3.warn(absentLines.join(`
|
|
28
|
+
`)),r.models.outcome==="rejected"&&log3.warn(["pharn-oss's models block would not be written; this pharn rejects it:",...r.models.reasons.map(reason=>` ${terminalSafe(reason,{max:300})}`)].join(`
|
|
29
|
+
`)),outro2(`Dry run \u2014 would create ${r.counts.create} \xB7 overwrite ${r.counts.overwrite}${deletes.length>0?` \xB7 delete ${deletes.length} director${deletes.length===1?"y":"ies"}`:""} \xB7 back up ${r.counts.backup}. Nothing was changed. Run \`pharn init\` to apply.`)}export{runInit};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{renderCapabilityLines}from"./chunk-
|
|
1
|
+
import{renderCapabilityLines}from"./chunk-NE4LZ2VE.js";import{color_default,loadArchetypeConfig}from"./chunk-5YCL3WDS.js";import"./chunk-L3QGAX2K.js";import"./chunk-A77BLCF4.js";import{intro,note,outro}from"@clack/prompts";async function runList(opts={}){let json=opts.json??!1,cwd=process.cwd();json||intro("pharn list");let config=loadArchetypeConfig(cwd,{json}),inventory=buildArchetypeInventory(config);if(json){console.log(JSON.stringify(inventory,null,2));return}renderArchetypeHuman(inventory)}function buildArchetypeInventory(config){return{mode:"archetype",skillsVersion:config.skillsVersion,archetypes:config.archetypes??[],capabilities:(config.capabilities??[]).map(c=>({name:c.name,role:c.role,...c.source!==void 0?{source:c.source}:{}}))}}function renderArchetypeHuman(inv){let lines=renderCapabilityLines(inv);note(lines.join(`
|
|
2
2
|
`),"INSTALLED (archetype)"),outro(color_default.dim("Read-only \u2014 nothing changed."))}export{runList};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{parseCapabilityArg}from"./chunk-QGQRN6AC.js";import{capabilityDir,capabilityRelDir,deleteCapabilityDir,linkedComponent,removalBackupSet}from"./chunk-YG2GHTWC.js";import{ProjectLockedError,backupDirIgnored,buildRemoveSelection,createBackup,interactiveAllowed,printBackupNotice,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{layoutPaths,readRecords,recordsBaseline,warnIfOlderCli,writeRecords}from"./chunk-PL5ALKBN.js";import"./chunk-W3TXAEBT.js";import"./chunk-C5RBIXPQ.js";import{assertConfigFingerprintUnchanged,color_default,configFingerprint,loadArchetypeConfig,writePharnConfig}from"./chunk-5YCL3WDS.js";import"./chunk-L3QGAX2K.js";import{CliError,errorMessage}from"./chunk-A77BLCF4.js";import{confirm,groupMultiselect,intro,isCancel,log,outro}from"@clack/prompts";async function runRemove(arg){intro("pharn remove");let cwd=process.cwd();try{await withProjectLock(cwd,"remove",async()=>{let fingerprint=configFingerprint(cwd),config=loadArchetypeConfig(cwd);warnIfOlderCli(config),await removeCapability(cwd,config,arg,fingerprint)})}catch(err){throw err instanceof ProjectLockedError||err instanceof RemoveBackupError||err instanceof SymlinkedTargetError?CliError.error(err.message):err}}var RemoveBackupError=class extends Error{constructor(message){super(message),this.name="RemoveBackupError"}},SymlinkedTargetError=class extends Error{constructor(message){super(message),this.name="SymlinkedTargetError"}};async function removeCapability(cwd,config,arg,fingerprint){let installed=config.capabilities??[];if(arg===void 0){await runRemovePicker(cwd,config,installed,fingerprint);return}await removeNamed(cwd,config,installed,arg,fingerprint)}function backupBeforeDelete(cwd,paths,targets,records){for(let target of targets)capabilityDir(cwd,paths,target);let label=targets.map(t=>`${t.name} (${t.role})`).join(", ");try{let rels=removalBackupSet(cwd,targets.map(t=>capabilityRelDir(paths,t)),records);if(rels.length===0)return;let backupDir=createBackup(cwd,rels);printBackupNotice({dir:backupDir,saved:rels.length,action:"removing",gitignored:backupDirIgnored(cwd)})}catch(err){throw new RemoveBackupError(`Could not back up the files in ${label} before removing: ${errorMessage(err).replace(/\.$/,"")}. Nothing was removed.`)}}function readRecordsBaseline(cwd){return recordsBaseline(readRecords(cwd)).records}function refuseSymlinkedTargets(cwd,paths,targets){for(let target of targets){let linked=linkedComponent(cwd,paths,target);if(linked!==null)throw new SymlinkedTargetError(`Refusing to remove ${target.name} (${target.role}): ${linked} is a symbolic link, so deleting through it would delete files OUTSIDE the project. Nothing was removed. Delete the directory yourself if that is what you want.`)}}async function pruneCapabilityRecords(cwd,config,paths,targets,records){if(records===null)return;let prefixes=targets.map(t=>`${capabilityRelDir(paths,t)}/`),kept={},dropped=0;for(let[key,hash]of Object.entries(records))prefixes.some(prefix=>key.startsWith(prefix))?dropped++:kept[key]=hash;dropped!==0&&await writeRecords(cwd,{skillsVersion:config.skillsVersion,commit:config.commit,files:kept})}function warnIfAutoSelected(targets){let auto=targets.filter(c=>c.source==="auto");if(auto.length===0)return;let names=auto.map(c=>`${c.name} (${c.role})`).join(", "),one=auto.length===1,pronoun=one?"it":"them";log.warn(`${names} ${one?"is":"are"} selected automatically for your archetypes, so ${one?"it comes":"they come"} back: the next \`pharn update\` reinstalls ${pronoun} and names ${pronoun} in its report.`)}async function removeNamed(cwd,config,installed,address,fingerprint){let parsed=parseCapabilityArg(address);if(parsed.error)throw CliError.error(parsed.error);let matches=installed.filter(c=>c.name===parsed.name&&(parsed.role===void 0||c.role===parsed.role));if(matches.length===0){let valid=installed.map(c=>`${c.role}:${c.name}`).sort(),hint=valid.length?` Installed: ${valid.join(", ")}.`:" No capabilities are installed.";throw CliError.error(`"${address}" is not an installed capability.${hint} Nothing was removed.`)}if(matches.length>1)throw CliError.error(`"${parsed.name}" is ambiguous \u2014 use ${matches.map(m=>`${m.role}:${m.name}`).join(" or ")}.`);let target=matches[0],paths=layoutPaths("pharn");refuseSymlinkedTargets(cwd,paths,[target]),assertConfigFingerprintUnchanged(cwd,fingerprint,"remove");let records=readRecordsBaseline(cwd);backupBeforeDelete(cwd,paths,[target],records);let existed=deleteCapabilityDir(cwd,paths,target);await pruneCapabilityRecords(cwd,config,paths,[target],records),await writePharnConfig(cwd,{...config,capabilities:installed.filter(c=>!(c.name===target.name&&c.role===target.role))});let note=existed?"":color_default.dim(" (its files were already gone)");warnIfAutoSelected([target]),outro(`${color_default.green("\u2714")} Removed ${target.name} (${target.role})${note}`)}async function runRemovePicker(cwd,config,installed,fingerprint){if(installed.length===0){outro("No capabilities are installed.");return}if(!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("Specify a capability to remove (e.g. `pharn remove a11y`), or run `pharn remove` in an interactive terminal to pick from a list.");let{groups}=buildRemoveSelection(installed),picked=await groupMultiselect({message:"Select capabilities to remove",options:groups,required:!1,selectableGroups:!1});if(isCancel(picked))throw CliError.cancel();let values=picked;if(values.length===0){outro("Nothing selected. No capabilities were removed.");return}let targets=[];for(let value of values){let parsed=parseCapabilityArg(value),target=installed.find(c=>c.name===parsed.name&&c.role===parsed.role);target&&targets.push(target)}let paths=layoutPaths("pharn");refuseSymlinkedTargets(cwd,paths,targets);let ok=await confirm({message:`Remove ${targets.length} ${plural(targets.length)}: ${targets.map(t=>`${t.name} (${t.role})`).join(", ")}?`,initialValue:!1});if(isCancel(ok)||ok!==!0)throw CliError.cancel();refuseSymlinkedTargets(cwd,paths,targets),assertConfigFingerprintUnchanged(cwd,fingerprint,"remove");let records=readRecordsBaseline(cwd);backupBeforeDelete(cwd,paths,targets,records);for(let target of targets)deleteCapabilityDir(cwd,paths,target);await pruneCapabilityRecords(cwd,config,paths,targets,records);let removed=new Set(targets.map(t=>`${t.role}:${t.name}`));await writePharnConfig(cwd,{...config,capabilities:installed.filter(c=>!removed.has(`${c.role}:${c.name}`))}),warnIfAutoSelected(targets),outro(`${color_default.green("\u2714")} Removed ${targets.length} ${plural(targets.length)}.`)}function plural(n){return n===1?"capability":"capabilities"}export{runRemove};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{NODE_FLOOR,cap,checkModelsBlock,modelsCheckerCommand,modelsLabelLines,nodeFloorLines,nodeFloorStatus,planPrettierignore,prettierignoreLines,prettierignoreReport,resolveStageRows,resolvedStageLines,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,hookWiringFails,hookWiringLines,orphanNoteLines}from"./chunk-7UE7LQQP.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import{readDiskState}from"./chunk-26RZI2K7.js";import{channelOf,resolveLatestReleaseVersion,resolveSource,sourceDescription,sourceLabel}from"./chunk-256AIEPX.js";import{absentInstallSurfaces,collectExpectedInstallPaths,contentHash,fetchRemoteSkillsVersion,layoutPaths,readRecords,readSkillsVersion,recordsBaseline,warnIfOlderCli}from"./chunk-PL5ALKBN.js";import{REPO}from"./chunk-W3TXAEBT.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{color_default,loadArchetypeConfig,row}from"./chunk-5YCL3WDS.js";import"./chunk-L3QGAX2K.js";import{CliError,terminalSafe}from"./chunk-A77BLCF4.js";import{intro,log,note,outro,spinner}from"@clack/prompts";var STATUS_SCHEMA_VERSION=1,MAX_RED_DETAIL=300,MAX_UNKNOWN_FIELD=200,MAX_RUNNING_NODE=40;function strictFails(input){let{outdated,diff,hooks,absentUpstream}=input;return outdated||absentUpstream!==void 0&&absentUpstream.length>0||diff!==void 0&&(diff.modified.length>0||diff.missing.length>0||diff.unreadable.length>0)||hooks!==void 0&&hookWiringFails(hooks)}function modelsReport(models){if(models===void 0)return null;let check=checkModelsBlock(models);return check.kind==="invalid"?{conversionNeeded:!1,verdict:"invalid",stages:null,reds:check.reds.map(r=>({kind:r.kind,detail:cap(r.detail,MAX_RED_DETAIL)}))}:check.kind==="no-stages"?{conversionNeeded:!1,verdict:"no-stages",stages:null,reds:null}:{conversionNeeded:!1,verdict:"valid",stages:resolveStageRows(check.stages),reds:null}}function buildStatusReport(input){let{node,config,drift}=input,layout={recorded:"pharn",upstream:drift===null?null:"pharn"},{ahead,outdated}=versionStatus({installed:config.skillsVersion,latest:input.latest});return{schemaVersion:STATUS_SCHEMA_VERSION,node:{floor:NODE_FLOOR,running:node.kind==="unparseable"?node.raw===void 0?null:cap(node.raw,MAX_RUNNING_NODE):cap(node.current,MAX_RUNNING_NODE),status:node.kind},version:{installed:config.skillsVersion,latest:input.latest,channel:input.channel,source:{kind:input.source.kind,tag:input.source.kind==="release"?input.source.tag:null},ahead,outdated},archetypes:config.archetypes??[],capabilities:{count:(config.capabilities??[]).length},layout,drift:drift===null?null:{modified:drift.diff.modified,missing:drift.diff.missing,unreadable:drift.diff.unreadable,okCount:drift.diff.okCount,absentUpstream:drift.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))},hooks:drift===null?null:{status:drift.hooks.status,missing:drift.hooks.missing,localOnly:drift.hooks.localOnly??[],file:drift.hooks.file??null,reason:drift.hooks.reason??null,...drift.hooks.replace?.length?{replace:drift.hooks.replace}:{}},models:modelsReport(config.models),unknownCapabilities:drift===null?null:drift.unknown.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),orphans:drift===null||drift.orphans===null?null:drift.orphans.map(o=>({path:o.path,state:o.state,...o.reason!==void 0?{reason:cap(o.reason,MAX_RED_DETAIL)}:{}})),prettierignore:input.prettierignore===null?null:prettierignoreReport(input.prettierignore),strict:{enabled:input.strict,failed:input.strict&&strictFails({outdated,diff:drift?.diff,hooks:drift?.hooks,absentUpstream:drift?.absentUpstream})}}}function serializeStatusReport(report){return serializeJsonReport(report)}function diffInstalledCapabilities(params){let{repoDir,projectRoot,capabilities}=params,expected=collectExpectedInstallPaths({repoDir,capabilities});return compareExpected(expected,projectRoot)}function compareExpected(expected,baseDir){let modified=[],missing=[],unreadable=[],okCount=0;for(let[rel,repoPath]of expected){let state=readDiskState(baseDir,rel);state.kind==="absent"?missing.push(rel):state.kind==="unreadable"?unreadable.push({rel,reason:state.reason}):state.hash===contentHash(repoPath)?okCount+=1:modified.push(rel)}return modified.sort(),missing.sort(),unreadable.sort((a,b)=>+(a.rel>b.rel)-+(a.rel<b.rel)),{modified,missing,unreadable,okCount}}async function runStatus(opts={}){let strict=opts.strict??!1,drift=opts.drift??!0,json=opts.json??!1;json||intro("pharn status");let cwd=process.cwd(),config=loadArchetypeConfig(cwd,{json});warnIfOlderCli(config,{json});let node=nodeFloorStatus(process.versions.node);json||note(nodeFloorLines(node).join(`
|
|
2
|
+
`),"NODE");let proxyNotice=detectProxyNotice(process.env);if(proxyNotice){let message=proxyNoticeMessage(proxyNotice);json?logErrorPlain(message):log.warn(message)}let channel=channelOf(config),s=json?null:spinner(),input;if(drift){s?.start(`Comparing against ${REPO}`);let repo;try{repo=await fetchRepo(await resolveSource(channel)),s?.stop(`Compared against ${sourceLabel(repo.source)}`)}catch(err){throw s?.stop(`Failed to reach ${REPO}`),CliError.failure(err,{json})}try{input=cloneInput(repo,{node,config,channel,strict},cwd)}catch(err){throw CliError.failure(err,{json})}finally{repo.cleanup()}}else{s?.start("Checking for updates");let found;try{found=await latestWithoutClone(channel),s?.stop(`Latest skills v${found.latest}`)}catch(err){throw s?.stop("Failed to check for updates"),CliError.failure(err,{json})}input={node,config,channel,...found,drift:null,prettierignore:statusPrettierignore(cwd),strict}}let report=buildStatusReport(input);if(json){console.log(serializeStatusReport(report)),report.strict.failed&&(process.exitCode=1);return}if(renderStatus(report,input),report.strict.failed)throw CliError.reported();outro(color_default.dim(drift?"Read-only \u2014 nothing changed.":"Read-only \u2014 nothing changed (drift check skipped)."))}function cloneInput(repo,base,cwd){let{config}=base,index=parseCapabilityIndex(repo.dir),frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`));return{...base,latest:readSkillsVersion(repo.dir),source:repo.source,drift:{diff:diffInstalledCapabilities({repoDir:repo.dir,projectRoot:cwd,capabilities:(config.capabilities??[]).filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`))}),absentUpstream:absentInstallSurfaces({repoDir:repo.dir}),hooks:diffHookWiring(repo.dir,cwd),unknown:index.unknown,orphans:statusOrphans(repo.dir,cwd,config,frozen)},prettierignore:statusPrettierignore(cwd)}}function renderStatus(report,input){printArchetypeVersion(report,input.source),printModels(input.config),printPrettierignore(input.prettierignore);let drift=input.drift;if(drift===null||report.drift===null)return;let unknownWarning=unknownCapabilitiesWarning(drift.unknown);unknownWarning&&log.warn(unknownWarning),printDriftSection(report.drift,sourceLabel(input.source));let orphanLines=orphanNoteLines(report.orphans??[]);orphanLines&¬e(orphanLines.join(`
|
|
3
|
+
`),"ORPHANED");let hookLines=hookWiringLines(drift.hooks);hookLines&¬e(hookLines.join(`
|
|
4
|
+
`),"HOOKS")}async function latestWithoutClone(channel){if(channel==="latest"){let release=await resolveLatestReleaseVersion();return{latest:release.version,source:release}}return{latest:await fetchRemoteSkillsVersion(),source:await resolveSource("main")}}function channelRow(channel){return channel==="latest"?row("Channel","latest \u2014 verified releases"):`${row("Channel","main \u2014 the pharn-oss tip")} ${color_default.dim("(`pharn update --ref latest` follows verified releases)")}`}function printArchetypeVersion(report,source){let{ahead,outdated,latest,channel}=report.version,installed=terminalSafe(report.version.installed),aheadNote=source.kind==="release"?`(ahead of the latest verified release v${latest} \u2014 installed from main)`:`(ahead of pharn-oss main (v${latest}) \u2014 main has moved back; \`pharn update --force\` downgrades)`,outdatedNote=source.kind==="release"?`(newer verified release ${source.tag} \u2014 run \`pharn update\`)`:"(update available, run `pharn update`)",currentNote=source.kind==="release"?"(no newer verified release)":"(up to date)",skillsLine=ahead?`${row("Skills version",`v${installed}`)} ${color_default.dim(aheadNote)}`:outdated?`${row("Skills version",`v${installed} \u2192 v${latest}`)} ${color_default.dim(outdatedNote)}`:`${row("Skills version",`v${installed}`)} ${color_default.dim(currentNote)}`;note([skillsLine,channelRow(channel),row("Source",sourceDescription(source)),"",row("Archetypes",report.archetypes.join(", ")||"(none)"),row("Capabilities",String(report.capabilities.count))].join(`
|
|
5
|
+
`),"VERSION")}function printModels(config){if(config.models===void 0)return;let floor=layoutPaths("pharn").floor;note(modelsNoteLines(config.models,floor).join(`
|
|
6
|
+
`),"MODELS")}function modelsNoteLines(block,floor){let check=checkModelsBlock(block);return check.kind==="invalid"?["pharn-oss's rules reject this block:",...check.reds.map(red=>` ${terminalSafe(red.detail,{max:300})}`),color_default.dim("Fix it by hand. The checker installed with PHARN says the same:"),color_default.dim(modelsCheckerCommand(floor,"validate"))]:check.kind==="no-stages"?["Declares no stages: pharn-oss's checker reads that as none declared."]:[...resolvedStageLines(check.stages),"",...modelsLabelLines(floor).map(line=>color_default.dim(line))]}function statusPrettierignore(cwd){let{records}=recordsBaseline(readRecords(cwd));return records===null?null:planPrettierignore(cwd,Object.keys(records))}function printPrettierignore(plan){let lines=plan===null?null:prettierignoreLines(plan,{status:!0});lines!==null&¬e(lines.text,"PRETTIER")}function statusOrphans(repoDir,cwd,config,frozen){let{records}=recordsBaseline(readRecords(cwd));if(records===null)return null;let all=config.capabilities??[],isFrozen=cap2=>frozen.has(`${cap2.role}:${cap2.name}`),expected=collectExpectedInstallPaths({repoDir,capabilities:all.filter(cap2=>!isFrozen(cap2))});return findOrphans({projectRoot:cwd,records,expected,capabilities:all,frozen:all.filter(isFrozen)}).orphans}function printDriftSection(result,ref){let{absentUpstream}=result;if(result.modified.length===0&&result.missing.length===0&&result.unreadable.length===0&&absentUpstream.length===0){note(`No drift \u2014 ${result.okCount} file(s) match ${ref}.`,"DRIFT");return}let lines=[];if(result.modified.length){lines.push(` DIFFERS FROM ${ref} (PHARN-owned)`);for(let p of result.modified)lines.push(` ${p}`);lines.push(color_default.dim(" `pharn update` keeps files you've edited and cleanly"),color_default.dim(" upgrades the rest; `--force` overwrites edits too"),color_default.dim(" (backed up to pharn/.backup/ first)."))}if(result.missing.length){lines.length&&lines.push(""),lines.push(" MISSING (expected but absent)");for(let p of result.missing)lines.push(` ${p}`);lines.push(color_default.dim(" Run `pharn update` to restore them (files you edited are kept)."),color_default.dim(" To add a capability not yet in pharn.config.json, use `pharn add`"),color_default.dim(" (additive-only \u2014 already-listed capabilities are a no-op)."))}if(result.unreadable.length){lines.length&&lines.push(""),lines.push(" UNREADABLE \u2014 not a regular readable file");for(let{rel,reason}of result.unreadable)lines.push(` ${rel} \u2014 ${reason}`);lines.push(color_default.dim(" pharn cannot compare these, and `pharn update` skips them too."),color_default.dim(" Inspect each path by hand \u2014 a directory, a symlink, or an"),color_default.dim(" unreadable file sits where pharn expects a regular file."))}if(absentUpstream.length){lines.length&&lines.push(""),lines.push(` NOT SHIPPED UPSTREAM \u2014 ${ref} has no file here`);for(let{surface,path}of absentUpstream)lines.push(` ${terminalSafe(path)} (${surface})`);lines.push(color_default.dim(" Installed commands, hooks and checkers that use these will"),color_default.dim(" not find them. If pharn-oss moved them, a newer pharn may"),color_default.dim(" know where: npm i -g @pharn-dev/pharn@latest"))}lines.push("",color_default.dim(` ${result.okCount} file(s) match ${ref}.`)),note(lines.join(`
|
|
7
|
+
`),"DRIFT")}export{runStatus};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{BACKUP_DIR,LOCK_DIR,ProjectLockedError,backupDirIgnored,createBackup,interactiveAllowed,printBackupNotice,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{displayHook,hooksReferencing}from"./chunk-7UE7LQQP.js";import"./chunk-26RZI2K7.js";import{MODELS_RECORD_KEY,RECORDS_FILE,contentHash,findSymlinkComponent,isInstallRootPath,readRecords,recordsBaseline,recordsPath,warnIfOlderCli}from"./chunk-PL5ALKBN.js";import{CLAUDE_HOOKS_DIR,CLAUDE_SETTINGS_FILE}from"./chunk-W3TXAEBT.js";import"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,assertConfigFingerprintUnchanged,color_default,configFingerprint,configPath,loadArchetypeConfig}from"./chunk-5YCL3WDS.js";import{safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe}from"./chunk-A77BLCF4.js";import{lstatSync as lstatSync2,readdirSync,rmdirSync,unlinkSync}from"node:fs";import{posix as posix2}from"node:path";import{confirm,intro,isCancel,note,outro}from"@clack/prompts";import{lstatSync}from"node:fs";import{posix}from"node:path";function planUninstall(projectRoot,records){let plan={delete:[],edited:[],unverifiable:[],absent:[],outside:[],unsafe:[]};for(let rel of Object.keys(records).sort()){if(rel===MODELS_RECORD_KEY)continue;if(rel!==CLAUDE_SETTINGS_FILE&&!isInstallRootPath(rel)){plan.outside.push(rel);continue}let verdict=classify(projectRoot,rel,records[rel]);typeof verdict=="object"?plan.unsafe.push(verdict):plan[verdict].push(rel)}return plan}function reclassifyDeletes(projectRoot,records,plan){let subset={};for(let rel of plan.delete)subset[rel]=records[rel];let now=planUninstall(projectRoot,subset),merged=(a,b)=>[...a,...b].sort();return{delete:now.delete,edited:merged(plan.edited,now.edited),unverifiable:merged(plan.unverifiable,now.unverifiable),absent:merged(plan.absent,now.absent),outside:plan.outside,unsafe:[...plan.unsafe,...now.unsafe]}}function classify(projectRoot,rel,recorded){let linked;try{let parent=posix.dirname(rel);linked=parent==="."?null:findSymlinkComponent(projectRoot,parent)}catch{return"absent"}if(linked!==null)return{rel,component:linked};let abs=safeJoin(projectRoot,rel),stat;try{stat=lstatSync(abs,{throwIfNoEntry:!1})}catch(err){return err.code==="ENOTDIR"?"absent":"unverifiable"}if(stat===void 0)return"absent";if(!stat.isFile())return"unverifiable";let hash;try{hash=contentHash(abs)}catch{return"unverifiable"}return hash===recorded?"delete":"edited"}var MAX_LISTED=10,UninstallError=class extends Error{constructor(message){super(message),this.name="UninstallError"}};async function runUninstall(opts={}){intro("pharn uninstall");let cwd=process.cwd(),result;try{result=await withProjectLock(cwd,"uninstall",()=>uninstallProject(cwd,opts))}catch(err){throw err instanceof ProjectLockedError||err instanceof UninstallError?CliError.error(err.message):err}result!==null&&(reportResult(cwd,result,finishPharnDir(cwd)),outro(`${color_default.green("\u2714")} PHARN was uninstalled.`))}async function uninstallProject(cwd,opts){if(lstatSync2(configPath(cwd),{throwIfNoEntry:!1})===void 0)return outro(`PHARN is not installed here (no ${CONFIG_FILENAME}). Nothing was removed.`),null;let fingerprint=configFingerprint(cwd);warnIfOlderCli(loadArchetypeConfig(cwd));let records=usableRecords(cwd);if(typeof records=="string")throw CliError.error(records);let preview=planUninstall(cwd,records);if(preview.unsafe.length>0)throw CliError.error(unsafeMessage(preview));if(note(planLines(preview,settingsRecorded(records)).join(`
|
|
2
|
+
`),"PLAN"),!opts.yes){if(!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("`pharn uninstall` asks for confirmation, and this is not an interactive terminal. Re-run it in a terminal, or pass --yes to uninstall without asking. Nothing was removed.");let ok=await confirm({message:`Uninstall PHARN \u2014 delete ${preview.delete.length} file(s), ${RECORDS_FILE} and ${CONFIG_FILENAME}?`,initialValue:!1});if(isCancel(ok)||ok!==!0)throw CliError.cancel()}return applyUninstall(cwd,records,preview,fingerprint)}function usableRecords(cwd){let read=readRecords(cwd),baseline=recordsBaseline(read);return baseline.records!==null?baseline.records:`Cannot uninstall: ${read.kind==="invalid"?escapeUnsafe(read.message):`there is no ${RECORDS_FILE}`}. ${RECORDS_FILE} is the only proof of which files pharn wrote, so without a usable one nothing was removed. Remove PHARN by hand instead (docs/troubleshooting.md, "Removing PHARN by hand").`}function unsafeMessage(plan){let first=plan.unsafe[0];return`Refusing to uninstall: ${escapeUnsafe(first.component)} is a symbolic link, so deleting ${escapeUnsafe(first.rel)} through it would delete a file OUTSIDE the project. Nothing was removed.`}async function applyUninstall(cwd,records,planned,fingerprint){assertConfigFingerprintUnchanged(cwd,fingerprint,"uninstall");let proof=usableRecords(cwd);if(typeof proof=="string")throw new UninstallError(proof);let plan=reclassifyDeletes(cwd,records,planned);if(plan.unsafe.length>0)throw new UninstallError(unsafeMessage(plan));let backupDir;try{backupDir=createBackup(cwd,[CONFIG_FILENAME])}catch(err){throw new UninstallError(`Could not back up ${CONFIG_FILENAME} before uninstalling: ${errorMessage(err).replace(/\.$/,"")}. Nothing was removed.`)}printBackupNotice({dir:backupDir,saved:CONFIG_FILENAME,gitignored:backupDirIgnored(cwd)});let deleted=[];for(let rel of plan.delete)try{unlinkSync(safeJoin(cwd,rel)),deleted.push(rel)}catch(err){if(err.code==="ENOENT")continue;throw new UninstallError(`Could not delete ${escapeUnsafe(rel)}: ${errorMessage(err).replace(/\.$/,"")}. ${deleted.length} file(s) were deleted before it; ${RECORDS_FILE} and ${CONFIG_FILENAME} were kept, so re-running \`pharn uninstall\` continues from here.`)}let{removedDirs,keptDirs}=removeEmptyDirs(cwd,deleted);return unlinkIfPresent(recordsPath(cwd),RECORDS_FILE),unlinkIfPresent(configPath(cwd),CONFIG_FILENAME),{plan,deleted,removedDirs,keptDirs,backupDir,records}}function unlinkIfPresent(abs,label){try{unlinkSync(abs)}catch(err){if(err.code==="ENOENT")return;throw new UninstallError(`Could not delete ${label}: ${errorMessage(err).replace(/\.$/,"")}. Every file pharn could prove it wrote is already gone; delete ${label} yourself to finish.`)}}function removeEmptyDirs(cwd,deleted){let candidates=new Set;for(let rel of deleted)for(let dir=posix2.dirname(rel);dir!==".";dir=posix2.dirname(dir))candidates.add(dir);let deepestFirst=[...candidates].sort((a,b)=>b.split("/").length-a.split("/").length||a.localeCompare(b)),removedDirs=[],keptDirs=[],blocked=new Set;for(let dir of deepestFirst)if(!blocked.has(dir))try{rmdirSync(safeJoin(cwd,dir)),removedDirs.push(dir)}catch(err){if(err.code==="ENOENT")continue;keptDirs.push(dir);for(let up=posix2.dirname(dir);up!==".";up=posix2.dirname(up))blocked.add(up)}return{removedDirs:removedDirs.sort(),keptDirs:keptDirs.sort()}}function listed(rels){let shown=rels.slice(0,MAX_LISTED).map(r=>` \u2022 ${escapeUnsafe(r)}`),more=rels.length-MAX_LISTED;return more>0?[...shown,` \u2026and ${more} more`]:shown}function settingsRecorded(records){return Object.hasOwn(records,CLAUDE_SETTINGS_FILE)}function untouchedLine(settingsIsRecorded){return`${settingsIsRecorded?"":`${CLAUDE_SETTINGS_FILE}, `}.claude/settings.local.json, every ${BACKUP_DIR}/ directory and the lines pharn added to .gitignore and .prettierignore are left untouched.`}function planLines(plan,settingsIsRecorded){let lines=[`Delete ${plan.delete.length} file(s) pharn installed and nobody changed.`];return plan.edited.length>0&&lines.push(`Keep ${plan.edited.length} file(s) you changed (they stay where they are):`,...listed(plan.edited)),plan.unverifiable.length>0&&lines.push(`Keep ${plan.unverifiable.length} path(s) that cannot be verified (not a regular file, or unreadable):`,...listed(plan.unverifiable)),plan.outside.length>0&&lines.push(`Leave ${plan.outside.length} recorded path(s) outside pharn's install paths (never deleted, whatever their hash):`,...listed(plan.outside)),plan.absent.length>0&&lines.push(`${plan.absent.length} recorded file(s) are already gone.`),lines.push(`Then remove directories left empty, and delete ${RECORDS_FILE} and ${CONFIG_FILENAME} (backed up to ${BACKUP_DIR}/ first).`,`Files pharn has no record of are never deleted. ${untouchedLine(settingsIsRecorded)}`),lines}function finishPharnDir(cwd){let dir=safeJoin(cwd,LOCK_DIR);try{return rmdirSync(dir),null}catch(err){if(err.code==="ENOENT")return null;try{return readdirSync(dir).sort()}catch{return[]}}}function reportResult(cwd,result,pharnLeft){let{plan,deleted,removedDirs,keptDirs,backupDir}=result,lines=[`Deleted ${deleted.length} file(s) and ${removedDirs.length} empty director${removedDirs.length===1?"y":"ies"}, plus ${RECORDS_FILE} and ${CONFIG_FILENAME}.`],kept=[...plan.edited,...plan.unverifiable].sort();if(kept.length>0&&lines.push(`Kept ${kept.length} file(s) pharn could not prove are unchanged \u2014 they are yours now:`,...listed(kept)),keptDirs.length>0&&lines.push(`Left ${keptDirs.length} director${keptDirs.length===1?"y":"ies"} that still hold other files:`,...listed(keptDirs)),lines.push(`${CONFIG_FILENAME} was backed up to ${backupDir}.`,`${untouchedLine(settingsRecorded(result.records))} Delete ${BACKUP_DIR}/ yourself once you no longer need it.`),pharnLeft!==null){let names=pharnLeft.slice(0,MAX_LISTED).map(n=>escapeUnsafe(n)),more=pharnLeft.length-names.length;lines.push(`${LOCK_DIR}/ was left because it still holds files pharn has no record of${names.length>0?` (${names.join(", ")}${more>0?`, \u2026and ${more} more`:""})`:""} \u2014 you may delete it once you no longer need them.`)}note(lines.join(`
|
|
3
|
+
`),"UNINSTALLED");let hookLines=danglingHookLines(cwd,result.records);hookLines.length>0&¬e(hookLines.join(`
|
|
4
|
+
`),"HOOKS")}function danglingHookLines(cwd,records){let gone=Object.keys(records).filter(rel=>rel.startsWith(`${CLAUDE_HOOKS_DIR}/`)&&isInstallRootPath(rel)&&isGone(cwd,rel)),refs=hooksReferencing(cwd,gone);if(refs.length===0)return[];let lines=[];for(let ref of refs){if(ref.kind==="unreadable"){lines.push(` ${ref.file} could not be read (${ref.reason}); check it for hooks that run a removed script.`);continue}lines.push(` ${ref.file} still wires ${ref.entries.length} hook(s) whose script was removed:`,...ref.entries.map(e=>` ${displayHook(e)}`))}return lines.push(""," pharn never edits these files \u2014 remove those entries by hand."," Matching is textual: a hook that reaches a removed script another way is not listed."),lines}function isGone(cwd,rel){try{return lstatSync2(safeJoin(cwd,rel),{throwIfNoEntry:!1})===void 0}catch{return!0}}export{runUninstall};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{CapabilityRemovalError,absentSurfaceLines,planCapabilityRemovals,readUpstreamModels,removalBackupsNow,resolveCapabilities,runNodePrereq}from"./chunk-2UADMP7W.js";import{decideFileAction,minCliGate,planUpdate}from"./chunk-QZ4LYI42.js";import{deleteCapabilityDir}from"./chunk-YG2GHTWC.js";import{BACKUP_DIR,ProjectLockedError,applyGitignore,backupAction,backupDirIgnored,createBackup,gitignoreLines,gitignorePending,gitignoreReport,interactiveAllowed,planGitignore,printBackupNotice,withProjectLock}from"./chunk-ONK3I3FO.js";import"./chunk-NE4LZ2VE.js";import{applyPrettierignore,cap,checkModelsBlock,modelsLabelLines,planPrettierignore,prettierignoreLines,prettierignorePending,prettierignoreReport,serializeJsonReport}from"./chunk-TUHBDIL2.js";import{diffHookWiring,findOrphans,hookWiringLines,orphanNoteLines}from"./chunk-7UE7LQQP.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-KAXAEUPE.js";import{ApplyError,applyWrites,changedSince,readDiskState}from"./chunk-26RZI2K7.js";import{channelOf,resolveSource,sourceDescription}from"./chunk-256AIEPX.js";import{MODELS_RECORD_KEY,RECORDS_FILE,RECORDS_SCHEMA_VERSION,absentInstallSurfaces,buildRecords,capabilitySubtree,carriedSettingsRecord,collectExpectedInstallPaths,contentHash,detectLayout,fetchRemoteSkillsVersion,isInstalledHookFile,isProductCommandFile,layoutPaths,modelsRecordHash,readRecords,readSkillsVersion,recordsBaseline,recordsUnderCapabilities,warnIfOlderCli,writeRecords}from"./chunk-PL5ALKBN.js";import{CLAUDE_COMMANDS_DIR,CLAUDE_HOOKS_DIR,FEATURES_README,PHARN_FEATURES_README,PHARN_VERSION,REPO_URL}from"./chunk-W3TXAEBT.js";import{logErrorPlain,reportFatal}from"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,assertConfigFingerprintUnchanged,color_default,configFingerprint,loadArchetypeConfig,row,writePharnConfig}from"./chunk-5YCL3WDS.js";import"./chunk-L3QGAX2K.js";import{CliError,errorMessage,escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";function key(cap2){return`${cap2.role}:${cap2.name}`}function mergeCapabilities(selection,previous,frozen){let resolved=new Set(selection.selected.map(key)),inIndex=new Set([...selection.selected.map(key),...selection.skipped.map(key)]),previousSource=new Map,seenPrevious=new Set;for(let cap2 of previous){let k=key(cap2);seenPrevious.has(k)||(seenPrevious.add(k),previousSource.set(k,cap2.source))}let capabilities=[],changes=[];for(let sel of selection.selected){let k=key(sel);if(!seenPrevious.has(k)){let cap2={name:sel.name,role:sel.role,source:"auto"};capabilities.push(cap2),changes.push({cap:cap2,reason:"added"});continue}let source=previousSource.get(k)==="manual"?"manual":"auto";capabilities.push({name:sel.name,role:sel.role,source})}for(let cap2 of previous){let k=key(cap2);if(resolved.has(k))continue;if(frozen.has(k)){let kept={...cap2};capabilities.push(kept),changes.push({cap:kept,reason:"kept-frozen"});continue}if(cap2.source==="auto"){changes.push({cap:cap2,reason:"dropped-unselected"});continue}let inferred={...cap2,source:"manual"};if(!inIndex.has(k)){changes.push({cap:inferred,reason:"dropped-gone"});continue}capabilities.push(inferred),cap2.source===void 0&&changes.push({cap:inferred,reason:"kept-manual"})}return{capabilities,changes}}function decideModelsUpdate(input){let{current,upstream,recorded,recordsAvailable,force}=input,none={label:null,backup:!1,problems:[],upstreamReasons:[]};if(upstream.kind!=="ok")return{...none,...keep(current),outcome:upstream.kind==="absent"?"upstream-absent":"upstream-invalid",nextRecord:recorded,upstreamReasons:upstream.kind==="invalid"?upstream.reasons:[]};let latestHash=modelsRecordHash(upstream.block),diskHash=current===void 0?null:modelsRecordHash(current),decision=decideFileAction({diskHash,latestHash,recordedHash:recorded,recordsAvailable,force});return decision.action==="write"?{...none,outcome:decision.forced?"forced":decision.label==="restored"?"restored":"updated",label:decision.forced?decision.label:null,next:upstream.block,nextRecord:latestHash,backup:decision.backup}:decision.action==="noop"?{...none,outcome:"ok",next:current,nextRecord:latestHash}:{...none,...keep(current),outcome:"kept",label:decision.label,nextRecord:recorded}}function keep(current){if(current===void 0)return{next:void 0,problems:[]};let check=checkModelsBlock(current);return{next:current,problems:check.kind==="invalid"?check.reds.map(red=>red.detail):[]}}function isExecutableUnitPath(rel,paths){if(rel.startsWith(`${paths.floor}/`))return!0;let hooksPrefix=`${CLAUDE_HOOKS_DIR}/`;if(rel.startsWith(hooksPrefix))return isInstalledHookFile(rel.slice(hooksPrefix.length));let commandsPrefix=`${CLAUDE_COMMANDS_DIR}/`;return rel.startsWith(commandsPrefix)?isProductCommandFile(rel.slice(commandsPrefix.length)):!1}import{isDeepStrictEqual}from"node:util";function nextRecordStore(apply,extra){let files={...apply.frozenRecords,...apply.orphanRecords,...apply.settingsRecords,...apply.plan.nextRecords,...extra.written,...apply.models.nextRecord!==null?{[MODELS_RECORD_KEY]:apply.models.nextRecord}:{}};for(let rel of extra.unwritten??[]){let previous=apply.records?.[rel];previous!==void 0?files[rel]=previous:delete files[rel]}return{skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,files}}function nextConfig(config,report,apply,channel,stamp){let{pendingSkillsVersion:_previousPending,frozenCapabilities:_previousFrozen,ref:_previousRef,...rest}=config;return{...rest,pharnVersion:stamp.pharnVersion,skillsVersion:apply.nextSkillsVersion,commit:apply.nextCommit,...channel==="latest"?{ref:"latest"}:{},...report.pendingSkillsVersion!==null?{pendingSkillsVersion:report.pendingSkillsVersion}:{},...apply.frozenKeys.length>0?{frozenCapabilities:apply.frozenKeys}:{},capabilities:apply.configCapabilities,layout:report.layout,updatedAt:stamp.updatedAt,models:apply.models.next}}function jsonValue(value){return JSON.parse(JSON.stringify(value))}function loadResolved(config){let{updatedAt:_updatedAt,pharnVersion:_pharnVersion,ref:_ref,commit:_commit,...rest}=config;return jsonValue({...rest,commit:config.commit??null,...channelOf(config)==="latest"?{ref:"latest"}:{}})}function planStateChanges(input){let{config,report,apply,channel,loadedRecords}=input,next=nextConfig(config,report,apply,channel,{pharnVersion:"",updatedAt:""}),store={schemaVersion:RECORDS_SCHEMA_VERSION,...nextRecordStore(apply,{written:{}})};return{config:!isDeepStrictEqual(loadResolved(next),loadResolved(config)),records:loadedRecords.kind!=="ok"||!isDeepStrictEqual(jsonValue(store),jsonValue(loadedRecords.store))}}function changesNoFiles(report){return report.writes.length===0&&!report.removals.some(r=>r.present)&&!gitignorePending(report.gitignore)&&!prettierignorePending(report.prettierignore)}function changesNothing(report,state){return changesNoFiles(report)&&!state.config&&!state.records}var USER_EDIT_SKIPS=new Set(["modified","unrecorded"]),DROP_REASONS=new Set(["dropped-unselected","dropped-gone"]);function isDrop(reason){return DROP_REASONS.has(reason)}function buildUpdatePlan(input){let{repoDir,sha,config,cwd,force,channel,onUnknownWarning}=input,index=parseCapabilityIndex(repoDir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&onUnknownWarning?.(unknownWarning);let frozen=new Set(index.unknown.map(u=>`${u.role}:${u.name}`)),selection=resolveCapabilities(config.archetypes??[],index),merged=mergeCapabilities(selection,config.capabilities??[],frozen),configCapabilities=merged.capabilities,manifestCapabilities=configCapabilities.filter(cap2=>!frozen.has(`${cap2.role}:${cap2.name}`)),installedVersion=readSkillsVersion(repoDir),layout=detectLayout(repoDir),expected=collectExpectedInstallPaths({repoDir,capabilities:manifestCapabilities}),latestHashes=new Map;for(let[rel,source]of expected)latestHashes.set(rel,contentHash(source));let diskStates=new Map;for(let rel of expected.keys())diskStates.set(rel,readDiskState(cwd,rel));let loadedRecords=readRecords(cwd),{records,note:recordsNote}=recordsBaseline(loadedRecords),paths=layoutPaths(layout),plan=planUpdate({latestHashes,diskStates,records,force,unit:rel=>isExecutableUnitPath(rel,paths),holdUnit:installedVersion!==config.skillsVersion}),removals=planCapabilityRemovals({cwd,paths,drops:merged.changes.flatMap(({cap:cap2,reason})=>isDrop(reason)?[{cap:cap2,reason}]:[]),records,command:"update"}),models=decideModelsUpdate({current:config.models,upstream:readUpstreamModels(repoDir),recorded:records?.[MODELS_RECORD_KEY]??null,recordsAvailable:records!==null,force}),backups=models.backup?[...plan.backups,CONFIG_FILENAME]:plan.backups,versionWithheld=plan.counts.skipped>0,nextSkillsVersion=versionWithheld?config.skillsVersion:installedVersion,nextCommit=versionWithheld?config.commit:sha,pendingSkillsVersion=versionWithheld&&installedVersion!==nextSkillsVersion&&plan.skipped.every(g=>USER_EDIT_SKIPS.has(g.label)||g.label==="held")?installedVersion:null,frozenRecords=records===null?{}:recordsUnderCapabilities(records,paths,configCapabilities.filter(cap2=>frozen.has(`${cap2.role}:${cap2.name}`))),orphanScan=findOrphans({projectRoot:cwd,records,expected,capabilities:configCapabilities,frozen:configCapabilities.filter(cap2=>frozen.has(`${cap2.role}:${cap2.name}`))}),orphans=orphanScan.orphans,prettierignorePaths=[...expected.keys(),...Object.keys(frozenRecords),...Object.keys(orphanScan.records)],previouslyFrozen=new Set(config.frozenCapabilities??[]),skippedRels=plan.skipped.flatMap(group=>group.rels),hasSkippedFile=cap2=>{let prefix=`${capabilitySubtree(paths,cap2.role)}/${cap2.name}/`;return skippedRels.some(rel=>rel.startsWith(prefix))},frozenKeys=[...new Set(configCapabilities.filter(cap2=>{let key2=`${cap2.role}:${cap2.name}`;return frozen.has(key2)||previouslyFrozen.has(key2)&&hasSkippedFile(cap2)}).map(cap2=>`${cap2.role}:${cap2.name}`))].sort(),report={currentVersion:config.skillsVersion,installedVersion,recordedVersion:nextSkillsVersion,versionWithheld,pendingSkillsVersion,frozenCapabilities:frozenKeys,capCount:configCapabilities.length,layout,featuresReadmeRelocation:records!==null&&FEATURES_README in records&&expected.has(PHARN_FEATURES_README),capabilityChanges:merged.changes,removals,files:plan.files,writes:plan.writes,backups,skipped:plan.skipped,counts:plan.counts,executableUnit:plan.held,models,modelsFloor:paths.floor,hookWiring:diffHookWiring(repoDir,cwd),absentUpstream:absentInstallSurfaces({repoDir}),recordsNote,unknownWarning,unknownCapabilities:index.unknown,orphans,gitignore:planGitignore(cwd),prettierignore:planPrettierignore(cwd,prettierignorePaths)},apply={expected,records,plan,models,configCapabilities,frozen,frozenRecords,orphanRecords:orphanScan.records,settingsRecords:carriedSettingsRecord(cwd,records),nextSkillsVersion,nextCommit,frozenKeys,removalPaths:paths,prettierignorePaths,seen:new Map(plan.writes.map(rel=>{let disk=diskStates.get(rel);return[rel,disk?.kind==="file"?disk.hash:null]}))},stateChanges=planStateChanges({config,report,apply,channel,loadedRecords});return{report:{...report,stateChanges,changesNothing:changesNothing(report,stateChanges)},apply}}import{log,note,outro}from"@clack/prompts";function defaultChannelNotice(config,ref){return ref!==void 0||channelOf(config)!=="main"?null:"Verified releases are now the default for new installs. This install keeps following pharn-oss main; run `pharn update --ref latest` to switch (recorded on first use)."}function noChangeVerdict(r){return r.counts.skipped===0&&r.recordedVersion===r.installedVersion?"Up to date.":"Nothing to change."}function forcedOverwriteSections(r,verb){let sections=["modified","unrecorded","unverifiable"].map(label=>({heading:`${verb} OVERWRITE (--force) \u2014 ${label}`,rels:r.files.filter(f=>f.action==="write"&&f.forced&&f.label===label).map(f=>f.rel)}));return sections.push({heading:`${verb} OVERWRITE (--force) \u2014 your models block`,rels:r.models.backup?[CONFIG_FILENAME]:[]}),sections.filter(s=>s.rels.length>0)}function reportForcedOverwrites(r){let sections=forcedOverwriteSections(r,"WILL");if(sections.length===0)return;let lines=[];for(let{heading,rels}of sections){lines.push(` ${heading}`);for(let rel of rels)lines.push(` ${rel}`);lines.push("")}lines.push(color_default.dim(` Each is copied to ${BACKUP_DIR}/<timestamp>/ first (${r.backups.length} file(s)).`)),note(lines.join(`
|
|
2
|
+
`),"OVERWRITE")}var FORCEABLE_SKIPS=new Set(["modified","unrecorded","unverifiable","held"]),MAX_UNIT_BLOCKERS=20;function executableUnitLines(hold,preview){return hold===null?null:[...unitBlockerLines(hold,preview),...unitMissingLines(hold.missing??[],preview),""," To upgrade the unit: revert the skipped files, or run",` \`pharn update --force\` (it backs them up to ${BACKUP_DIR}/ first).`]}function unitBlockerLines(hold,preview){let shown=hold.blocking.slice(0,MAX_UNIT_BLOCKERS),more=hold.blocking.length-shown.length;return[" The floor, the hooks and the pharn-* commands run together, so pharn"," writes them all or none. These unit files "+(preview?"would be skipped":"were skipped")+":",...shown.map(b=>` ${b.label.padEnd(12)} ${terminalSafe(b.rel,{max:300})}`),...more>0?[` \u2026 and ${more} more`]:[],"",` So ${hold.held.length} other unit file(s) `+(preview?"would not be written":"were not written")+" either, and the"," unit stays at the version you had: upgrading part of it would mix two"," versions that may not load together."]}function unitMissingLines(missing,preview){if(missing.length===0)return[];let shown=missing.slice(0,MAX_UNIT_BLOCKERS),more=missing.length-shown.length;return[""," Of those, these are not on disk, so they "+(preview?"would stay":"stay")+" missing until the hold ends:",...shown.map(rel=>` ${terminalSafe(rel,{max:300})}`),...more>0?[` \u2026 and ${more} more`]:[]]}function reportExecutableUnit(hold,preview){let lines=executableUnitLines(hold,preview);lines&¬e(lines.join(`
|
|
3
|
+
`),"EXECUTABLE UNIT")}function reportOutcome(outcome,force){let{plan,recordsNote,versionWithheld}=outcome,{counts}=plan;recordsNote&&log.warn(`\u26A0 ${escapeUnsafe(recordsNote)}`),reportCapabilityChanges(outcome.capabilityChanges,outcome.removals,!1),reportModels(outcome.models,outcome.modelsFloor,outcome.backup);let hookLines=outcome.hookWiring?hookWiringLines(outcome.hookWiring):null;hookLines&¬e(hookLines.join(`
|
|
4
|
+
`),"HOOKS"),reportAbsentSurfaces(outcome.absentUpstream??[]),reportExecutableUnit(plan.held,!1);let forceable=reportSkipped(plan.skipped,!1);if(reportOrphans(outcome.orphans),reportLayoutWarnings(outcome.featuresReadmeRelocation,!1),versionWithheld&&log.warn(withheldVersionLine({skipped:counts.skipped,recordedVersion:outcome.recordedVersion,installedVersion:outcome.installedVersion,forceable,preview:!1})),outcome.unchanged){outro(`${noChangeVerdict({counts,recordedVersion:outcome.recordedVersion,installedVersion:outcome.installedVersion})} ${color_default.dim(`(unchanged ${counts.ok} \xB7 skipped ${counts.skipped} \xB7 ${outcome.capCount} capabilit${outcome.capCount===1?"y":"ies"}, skills v${outcome.recordedVersion})`)}`);return}let summary=`updated ${counts.updated} \xB7 restored ${counts.restored} \xB7 unchanged ${counts.ok}`+(force?` \xB7 forced ${counts.forced}`:"")+` \xB7 skipped ${counts.skipped}`;outro(`${color_default.green("\u2714")} ${summary} ${color_default.dim(`(${outcome.capCount} capabilit${outcome.capCount===1?"y":"ies"}, skills v${outcome.recordedVersion})`)}`)}function reportAbsentSurfaces(absent){let lines=absentSurfaceLines(absent);lines&¬e(lines.join(`
|
|
5
|
+
`),"NOT SHIPPED")}function withheldVersionLine(o){let{skipped,recordedVersion,installedVersion,forceable,preview}=o;if(recordedVersion===installedVersion){let action=forceable?`${preview?"run":"re-run"} with --force to overwrite them (backed up to ${BACKUP_DIR}/ first), or keep them as they are`:"resolve them by hand";return`${skipped} file(s) ${preview?"would be":"were"} skipped; your install is already at skills v${installedVersion}, so there is no upgrade to finish \u2014 ${action}.`}return preview?`${skipped} file(s) would be skipped, so your install would stay recorded as skills v${recordedVersion} (upstream is v${installedVersion}) \u2014 resolve them${forceable?", or run with --force,":""} to finish the upgrade.`:`${skipped} file(s) were skipped, so your install is still recorded as skills v${recordedVersion} (upstream is v${installedVersion}) \u2014 resolve them${forceable?", or re-run with --force,":""} to finish the upgrade.`}function reportSkipped(skipped,preview){let forceable=skipped.some(g=>FORCEABLE_SKIPS.has(g.label)),hasUnreadable=skipped.some(g=>!FORCEABLE_SKIPS.has(g.label));if(skipped.length>0){let lines=[];for(let group of skipped){lines.push(` ${skipHeading(group.label)}`);for(let rel of group.rels)lines.push(` ${rel}`);lines.push("")}forceable&&lines.push(color_default.dim(preview?` Run \`pharn update --force\` to overwrite (skipped files would be backed up to ${BACKUP_DIR}/ first).`:` Re-run with --force to overwrite (skipped files are backed up to ${BACKUP_DIR}/ first).`)),hasUnreadable&&lines.push(color_default.dim(" --force cannot clear the UNREADABLE paths above."),color_default.dim(" Inspect each path by hand \u2014 a directory, a symlink, or an"),color_default.dim(" unreadable file sits where pharn expects a regular file.")),note(lines.join(`
|
|
6
|
+
`),"SKIPPED")}return forceable}function reportOrphans(orphans){let lines=orphanNoteLines(orphans);lines&¬e(lines.join(`
|
|
7
|
+
`),"ORPHANED")}function reportLayoutWarnings(featuresReadmeRelocation,preview){featuresReadmeRelocation&&log.warn(preview?"Your install would keep the product-loop boundary contract at pharn/features/README.md. A copy at the project root (features/README.md) would be left behind and no longer managed by pharn \u2014 you would delete it by hand.":"Your install now keeps the product-loop boundary contract at pharn/features/README.md. A copy at the project root (features/README.md) is left behind and is no longer managed by pharn \u2014 delete it by hand.")}function reportDryRun(r,force,channel,config){r.recordsNote&&log.warn(`\u26A0 ${escapeUnsafe(r.recordsNote)}`);let writes=r.files.filter(f=>f.action==="write"),sections=[{heading:"WOULD WRITE \u2014 restored (missing from your project)",rels:writes.filter(f=>f.label==="restored").map(f=>f.rel)},{heading:"WOULD WRITE \u2014 updated (still exactly as pharn wrote them)",rels:writes.filter(f=>f.label==="updated").map(f=>f.rel)},...forcedOverwriteSections(r,"WOULD")],deletes=r.removals.filter(removal=>removal.present);sections.push({heading:"WOULD DELETE \u2014 directories of capabilities dropped from your config",rels:deletes.map(removal=>`${removal.dir}/`)});let backupRels=[...new Set([...r.backups,...r.removals.flatMap(x=>x.backups)])],lines=[];for(let{heading,rels}of sections)if(rels.length!==0){lines.push(` ${heading}`);for(let rel of rels)lines.push(` ${rel}`);lines.push("")}if(backupRels.length>0){lines.push(` WOULD BACK UP ${backupRels.length} file(s) to ${BACKUP_DIR}/<timestamp>/ first`);for(let rel of backupRels)lines.push(` ${rel}`);lines.push("")}let gitignore=gitignoreLines(r.gitignore,{preview:!0});gitignore!==null&&!gitignore.warn&&lines.push(` ${gitignore.text}`,"");let prettierignore=prettierignoreLines(r.prettierignore,{preview:!0});prettierignore!==null&&!prettierignore.warn&&lines.push(` ${prettierignore.text}`,"");let stateFiles=[...r.stateChanges.config?[CONFIG_FILENAME]:[],...r.stateChanges.records?[RECORDS_FILE]:[]];r.changesNothing?lines.push(" Nothing would be written.",""):changesNoFiles(r)&&lines.push(` Would rewrite only ${stateFiles.join(" and ")}.`,""),lines.push(` UNCHANGED ${r.counts.ok} file(s) \xB7 SKIPPED ${r.counts.skipped} file(s)`),channel!==channelOf(config)&&lines.push("",` Would record channel: ${channel}`),note(lines.join(`
|
|
8
|
+
`),"PLAN"),gitignore?.warn&&log.warn(gitignore.text),prettierignore?.warn&&log.warn(prettierignore.text),reportCapabilityChanges(r.capabilityChanges,r.removals,!0),reportModels(r.models,r.modelsFloor,null,!0);let hookLines=hookWiringLines(r.hookWiring);hookLines&¬e(hookLines.join(`
|
|
9
|
+
`),"HOOKS"),reportAbsentSurfaces(r.absentUpstream),reportExecutableUnit(r.executableUnit,!0);let forceable=reportSkipped(r.skipped,!0);if(reportOrphans(r.orphans),reportLayoutWarnings(r.featuresReadmeRelocation,!0),r.versionWithheld?(log.warn(withheldVersionLine({skipped:r.counts.skipped,recordedVersion:r.recordedVersion,installedVersion:r.installedVersion,forceable,preview:!0})),r.pendingSkillsVersion!==null&&log.info(`Would record skills v${r.pendingSkillsVersion} as pending, so \`pharn add\` installs at it.`)):log.info(`Would record skills v${r.recordedVersion}.`),r.frozenCapabilities.length>0&&log.info(`Would keep unread upstream capabilities as they are: ${r.frozenCapabilities.join(", ")}.`),r.changesNothing){outro(`Dry run \u2014 ${noChangeVerdict(r)} Unchanged ${r.counts.ok} \xB7 skipped ${r.counts.skipped}. A real run would ask nothing and write nothing.`);return}outro(`Dry run \u2014 would write ${writes.length}${deletes.length>0?` \xB7 delete ${deletes.length} director${deletes.length===1?"y":"ies"}`:""} \xB7 back up ${backupRels.length} \xB7 unchanged ${r.counts.ok} \xB7 skipped ${r.counts.skipped}. Nothing was changed. Run \`pharn update${force?" --force":""}\` to apply.`)}function reportBackup(backup,opts){let output=opts.aborted?process.stderr:process.stdout;opts.aborted&&log.warn(`The update stopped part-way \u2014 some originals may already have been ${ABORTED_PHRASE[backup.action]}.`,{output}),printBackupNotice({dir:backup.dir,saved:backup.count,action:backup.action,gitignored:backup.gitignored},opts)}var ABORTED_PHRASE={overwriting:"overwritten",removing:"removed","overwriting and removing":"overwritten or removed"},CHANGE_ORDER=[{reason:"added",heading:"ADDED \u2014 newly selected for your archetypes"},{reason:"dropped-unselected",heading:"REMOVED \u2014 no longer selected for your archetypes"},{reason:"dropped-gone",heading:"REMOVED \u2014 no longer exists upstream (was a manual add)"},{reason:"kept-manual",heading:"KEPT \u2014 your manual add, not selected by your archetypes"},{reason:"kept-frozen",heading:"KEPT \u2014 pharn could not read these upstream this run, so they were left exactly as they are"}];function reportCapabilityChanges(changes,removals,preview){if(changes.length===0)return;let removalOf=new Map(removals.map(r=>[`${r.cap.role}:${r.cap.name}`,r])),lines=[];for(let{reason,heading}of CHANGE_ORDER){let inGroup=changes.filter(c=>c.reason===reason);if(inGroup.length!==0){lines.push(` ${heading}`);for(let{cap:cap2}of inGroup){let key2=`${cap2.role}:${cap2.name}`,removal=removalOf.get(key2);lines.push(removal===void 0?` ${key2}`:` ${key2} \u2014 ${removalPhrase(removal,preview)}`)}lines.push("")}}removals.length>0&&(lines.push(color_default.dim(preview?" Removed capabilities\u2019 directories would be deleted, so PHARN would no longer run them.":" Removed capabilities\u2019 directories are deleted, so PHARN no longer runs them.")),removals.some(r=>r.backups.length>0)&&lines.push(color_default.dim(preview?` Files in them pharn did not write would be copied to ${BACKUP_DIR}/ first.`:` Files in them pharn did not write were copied to ${BACKUP_DIR}/ first.`))),note(lines.join(`
|
|
10
|
+
`),"CAPABILITIES")}function removalPhrase(removal,preview){if(!removal.present)return"already gone";let n=removal.backups.length,deleted=preview?"directory would be deleted":"directory deleted";return n===0?deleted:preview?`${deleted} (${n} file(s) would be backed up first)`:`${deleted} (${n} file(s) backed up first)`}function reportModels(models,floor,backup,preview=!1){let lines=modelsReportLines(models,backup,preview);lines.length!==0&&(models.next!==void 0&&lines.push("",...modelsLabelLines(floor).map(line=>color_default.dim(line))),note(lines.join(`
|
|
11
|
+
`),"MODELS"))}function modelsReportLines(models,backup,preview){let quoted=text=>` ${terminalSafe(text,{max:300})}`,lines=[];switch(models.outcome){case"ok":return[];case"restored":lines.push(preview?"Your config has no models block \u2014 would write pharn-oss's.":"Your config had no models block \u2014 wrote pharn-oss's.");break;case"updated":lines.push(preview?"Would move your models block to pharn-oss's current one: you have":"Moved your models block to pharn-oss's current one: you had","not changed it since pharn wrote it.");break;case"forced":lines.push(preview?"Would replace your models block with pharn-oss's (--force).":"Replaced your models block with pharn-oss's (--force).",preview?`Your current ${CONFIG_FILENAME} would be copied to ${BACKUP_DIR}/<timestamp>/ first.`:`Your previous ${CONFIG_FILENAME} is in ${backup?.dir??`${BACKUP_DIR}/`}.`);break;case"kept":lines.push(keptModelsHeading(models.label));break;case"upstream-invalid":lines.push("pharn-oss's models block was not applied; this pharn rejects it:",...models.upstreamReasons.map(quoted),"If pharn-oss changed its models format, upgrade pharn","(npm i -g @pharn-dev/pharn@latest) and run `pharn update` again.");break;case"upstream-absent":if(models.problems.length===0)return[];lines.push("pharn-oss ships no models block, so yours is kept.");break}return models.outcome==="kept"&&models.problems.length>0?(lines.push("","pharn-oss's rules reject your models block:",...models.problems.map(quoted),"","Replace it by hand, or delete the `models` key from",`${CONFIG_FILENAME} so the next \`pharn update\` restores pharn-oss's.`,color_default.dim("--force also replaces it, after backing up the config,"),color_default.dim("but it overwrites every file you edited, too.")),lines):(models.problems.length>0&&lines.push("","pharn-oss's rules still reject your models block \u2014 left as is,","fix it by hand:",...models.problems.map(quoted)),models.outcome==="kept"&&lines.push("",color_default.dim("--force replaces it with pharn-oss's, after copying"),color_default.dim(`${CONFIG_FILENAME} to ${BACKUP_DIR}/.`)),lines)}function keptModelsHeading(label){switch(label){case"modified":return"Kept your models block \u2014 you changed it since pharn wrote it.";case"unrecorded":return"Kept your models block \u2014 pharn has no record of writing it.";default:return`Kept your models block \u2014 no usable ${RECORDS_FILE} to check it.`}}function skipHeading(label){switch(label){case"modified":return"MODIFIED \u2014 you changed these since pharn wrote them";case"unrecorded":return"UNRECORDED \u2014 pharn has no record of writing these";case"unverifiable":return`UNVERIFIABLE \u2014 no usable ${RECORDS_FILE} to compare against`;case"held":return"HELD \u2014 not written, so the executable unit stays at one version";default:return"UNREADABLE \u2014 not a regular readable file"}}import{confirm,intro,isCancel,log as log2,note as note2,outro as outro2,spinner}from"@clack/prompts";var UPDATE_SCHEMA_VERSION=1,MAX_REASON=300,MAX_UNKNOWN_FIELD=200,capAll=(values,max)=>values.map(v=>cap(v,max));function planReport(p,compact){let kept=compact?p.files.filter(f=>f.action!=="noop"):p.files;return{layout:p.layout,abandonedLayout:null,featuresReadmeRelocation:p.featuresReadmeRelocation,rootMigration:null,capabilities:{count:p.capCount,changes:p.capabilityChanges.map(c=>({role:c.cap.role,name:c.cap.name,source:c.cap.source??null,reason:c.reason})),...p.removals.length>0?{removals:p.removals.map(r=>({role:r.cap.role,name:r.cap.name,reason:r.reason,dir:r.dir,present:r.present,backups:[...r.backups]}))}:{}},files:kept.map(f=>({rel:f.rel,action:f.action,label:f.label,backup:f.backup,forced:f.forced})),...compact?{filesOmitted:{action:"noop",count:p.files.length-kept.length}}:{},writes:[...p.writes],backups:[...new Set(p.backups)],skipped:p.skipped.map(g=>({label:g.label,rels:[...g.rels]})),counts:{updated:p.counts.updated,restored:p.counts.restored,ok:p.counts.ok,forced:p.counts.forced,skipped:p.counts.skipped},...p.executableUnit!==null?{executableUnit:{blocking:p.executableUnit.blocking.map(b=>({rel:b.rel,label:b.label})),held:[...p.executableUnit.held],...(p.executableUnit.missing??[]).length>0?{missing:[...p.executableUnit.missing]}:{}}}:{},models:{outcome:p.models.outcome,label:p.models.label,replacedLegacyDefault:!1,backup:p.models.backup,conversion:null,problems:capAll(p.models.problems,MAX_REASON),upstreamReasons:capAll(p.models.upstreamReasons,MAX_REASON)},hooks:{status:p.hookWiring.status,missing:p.hookWiring.missing,localOnly:p.hookWiring.localOnly??[],file:p.hookWiring.file??null,reason:p.hookWiring.reason??null,...p.hookWiring.replace?.length?{replace:p.hookWiring.replace}:{}},...p.absentUpstream.length>0?{absentUpstream:p.absentUpstream.map(a=>({surface:a.surface,path:cap(a.path,MAX_UNKNOWN_FIELD)}))}:{},frozenCapabilities:[...p.frozenCapabilities],unknownCapabilities:p.unknownCapabilities.map(u=>({role:u.role,name:cap(u.name,MAX_UNKNOWN_FIELD),subtree:cap(u.subtree,MAX_UNKNOWN_FIELD),reason:cap(u.reason,MAX_UNKNOWN_FIELD)})),recordsNote:p.recordsNote===null?null:cap(p.recordsNote,MAX_REASON),...p.orphans.length>0?{orphans:p.orphans.map(o=>({path:o.path,state:o.state,...o.reason!==void 0?{reason:cap(o.reason,MAX_REASON)}:{}}))}:{},...gitignoreKey(p.gitignore),...prettierignoreKey(p.prettierignore)}}function prettierignoreKey(plan){let report=prettierignoreReport(plan);return report===null?{}:{prettierignore:report}}function gitignoreKey(plan){let report=gitignoreReport(plan);return report===null?{}:{gitignore:report}}function buildUpdateReport(input){let{plan}=input,compact=input.compact??!1;return{schemaVersion:UPDATE_SCHEMA_VERSION,command:"update",dryRun:!0,...compact?{compact:!0}:{},status:input.status,force:input.force,channel:input.channel,channelChange:input.channel===input.currentChannel?null:{from:input.currentChannel,to:input.channel},source:{kind:input.source.kind,tag:input.source.kind==="release"?input.source.tag:null},version:{installed:input.installed,latest:plan?plan.installedVersion:input.latest,recorded:plan?plan.recordedVersion:null,withheld:plan?plan.versionWithheld:null,pending:plan?plan.pendingSkillsVersion:null},archetypes:[...input.archetypes],plan:plan?planReport(plan,compact):null}}async function runUpdate(opts={}){let compact=opts.compact??!1,json=(opts.json??!1)||compact,dryRun=(opts.dryRun??!1)||json;json||intro(dryRun?"pharn update --dry-run":"pharn update"),runNodePrereq("update",{json});let cwd=process.cwd(),run=()=>updateProject(cwd,{...opts,dryRun,json,compact});if(dryRun){await run();return}try{await withProjectLock(cwd,"update",run)}catch(err){throw err instanceof ProjectLockedError?CliError.refusal(err.message):err}}async function updateProject(cwd,opts){let{dryRun,json,compact}=opts,fingerprint=configFingerprint(cwd),config=loadArchetypeConfig(cwd,{json});warnIfOlderCli(config,{json});let yes=opts.yes??!1;if(!dryRun&&!yes&&!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("pharn update needs to confirm before it writes. Run it in an interactive terminal, or pass --yes to confirm automatically (e.g. `pharn update --yes`).");let channelNotice=defaultChannelNotice(config,opts.ref);channelNotice!==null&&!json&&log2.info(channelNotice),await runArchetypeUpdate(config,cwd,opts.force??!1,yes,opts.ref??channelOf(config),dryRun,json,compact,fingerprint)}async function runArchetypeUpdate(config,cwd,force,yes,channel,dryRun,json,compact,fingerprint){let proxyNotice=detectProxyNotice(process.env);proxyNotice&&(json?logErrorPlain(proxyNoticeMessage(proxyNotice)):log2.warn(proxyNoticeMessage(proxyNotice)));let s=json?silentSpinner():spinner();s.start("Checking for updates");let latest,source;try{source=await resolveSource(channel),latest=source.kind==="release"?source.version:await fetchRemoteSkillsVersion(),s.stop(`Latest skills v${latest} (${sourceDescription(source)})`)}catch(err){throw s.stop("Failed to check for updates"),CliError.failure(err,{json})}let emitEarlyReturn=status=>{emitJson(buildUpdateReport({status,force,channel,currentChannel:channelOf(config),source,installed:config.skillsVersion,latest,archetypes:config.archetypes??[],plan:null,compact}))},aheadOf=force?null:[config.pendingSkillsVersion,config.skillsVersion].find(held=>held!==void 0&&versionStatus({installed:held,latest}).ahead)??null;if(aheadOf!==null){if(json){emitEarlyReturn(source.kind==="release"?"ahead-of-release":"ahead-of-main");return}let held=aheadOf===config.skillsVersion?`skills v${terminalSafe(config.skillsVersion)}`:`skills v${terminalSafe(config.skillsVersion)}, partly upgraded to v${terminalSafe(aheadOf)}`;outro2(source.kind==="release"?`Your install (${held}) is ahead of the latest verified release (${source.tag}) \u2014 it came from pharn-oss main. Nothing changed. \`pharn update --ref main\` switches back to main; \`pharn update --force\` goes back to ${source.tag}.`:`Your install (${held}) is newer than pharn-oss main (v${latest}) \u2014 main has moved back to an older version. Nothing changed. \`pharn update --force\` downgrades to v${latest}; otherwise wait for main to move forward again.`);return}if(dryRun){await runDryRun(config,cwd,force,channel,source,json,latest,compact);return}let pre=spinner();pre.start(`Planning from ${REPO_URL}`);let repo;try{repo=await fetchRepo(source)}catch(err){throw pre.stop("Update failed"),CliError.failure(err)}let outcome;try{let planned=planFromClone(repo,config,cwd,force,channel,{spin:pre,warn:m=>log2.warn(m),json:!1});if(planned.report.changesNothing)outcome=unchangedOutcome(planned);else{let confirmed=planned.report;printHeader(config,latest,source,force,!1),reportCapabilityChanges(confirmed.capabilityChanges,confirmed.removals,!0),reportExecutableUnit(confirmed.executableUnit,!0),force&&reportForcedOverwrites(confirmed);let deletes=confirmed.removals.filter(r=>r.present).length;if(!yes){let ok=await confirm({message:confirmMessage(force,deletes),initialValue:deletes===0});if(isCancel(ok)||ok!==!0)throw CliError.cancel()}outcome=await applyConfirmed(planned,{config,cwd,channel,repoDir:repo.dir,fingerprint})}}catch(err){throw err instanceof CapabilityRemovalError?CliError.refusal(err.message):CliError.failure(err)}finally{repo.cleanup()}let gitignore=outcome.gitignore===void 0?null:gitignoreLines(outcome.gitignore);gitignore?.warn?log2.warn(gitignore.text):gitignore!==null&&log2.info(gitignore.text);let prettierignore=outcome.prettierignore===void 0?null:prettierignoreLines(outcome.prettierignore);prettierignore?.warn?log2.warn(prettierignore.text):prettierignore!==null&&log2.info(prettierignore.text),reportOutcome(outcome,force)}function printHeader(config,latest,source,force,preview){note2([config.skillsVersion===latest?row("Skills version",`v${terminalSafe(config.skillsVersion)} (re-applying)`):row("Skills version",`v${terminalSafe(config.skillsVersion)} \u2192 v${latest}`),row("Source",sourceDescription(source)),"",row("Archetypes",(config.archetypes??[]).join(", ")||"(none)"),"",force?color_default.dim(` --force: files you changed will be OVERWRITTEN (each is copied to ${BACKUP_DIR}/ first).`):color_default.dim(" Files you have changed are kept, not overwritten \u2014 they are listed at the end."),color_default.dim(" Re-resolves your archetypes against the latest capabilities and re-copies them."),...preview?[color_default.dim(" Preview only \u2014 nothing will be written.")]:[],color_default.dim(" https://github.com/pharn-dev/pharn-oss/blob/main/CHANGELOG.md")].join(`
|
|
12
|
+
`))}function confirmMessage(force,deletes){let base=force?"Apply this update and overwrite your changes?":"Apply this update?";return deletes===0?base:`${base} It deletes ${deletes} capability director${deletes===1?"y":"ies"}.`}var MAX_CHANGED_SHOWN=10;function changedWhileWaiting(changed){let shown=changed.slice(0,MAX_CHANGED_SHOWN).map(rel=>` ${terminalSafe(rel)}`),more=changed.length-shown.length;return[`${changed.length===1?"A file":`${changed.length} files`} changed while \`pharn update\` was waiting for your answer:`,...shown,...more>0?[` \u2026and ${more} more`]:[],"Nothing was written, and your edit is kept. Run `pharn update` again: it plans the file as changed by you and leaves it alone (or, with --force, backs it up first)."].join(`
|
|
13
|
+
`)}async function applyConfirmed(planned,ctx){let{config,cwd,channel,repoDir,fingerprint}=ctx;assertConfigFingerprintUnchanged(cwd,fingerprint,"update");let changed=changedSince(cwd,planned.apply.seen,planned.report.writes,planned.apply.expected);if(changed.length>0)throw CliError.refusal(changedWhileWaiting(changed));let s=spinner();s.start("Updating");let backup=null;try{let applied=await applyPlannedUpdate(planned,config,cwd,repoDir,channel,written=>{backup=written,s.stop("Backup written"),reportBackup(written,{aborted:!1}),s=spinner(),s.start("Writing files")});return s.stop(applied.plan.writes.length?"Capabilities updated":"Nothing to write"),applied}catch(err){let refused=err instanceof CliError||err instanceof CapabilityRemovalError;throw s.stop(refused?"Update refused":"Update failed"),refused||backup===null?err:(reportFatal(errorMessage(err),{err}),reportBackup(backup,{aborted:!0}),CliError.reported())}}async function applyPlannedUpdate(planned,config,cwd,repoDir,channel,onBackup){let{report,apply}=planned,{expected,records,plan,models}=apply,removalBackups=removalBackupsNow({cwd,removals:report.removals,records,command:"update"}),backupRels=[...new Set([...report.backups,...removalBackups])],deletes=report.removals.some(r=>r.present),backup=backupRels.length>0?{dir:createBackup(cwd,backupRels),count:backupRels.length,action:backupAction(report.backups.length>0,deletes),gitignored:backupDirIgnored(cwd,report.gitignore)}:null;backup&&onBackup(backup);for(let removal of report.removals)removal.present&&deleteCapabilityDir(cwd,apply.removalPaths,removal.cap);let written,unwritten;try{({written,changed:unwritten}=applyWrites({projectRoot:cwd,expected,writes:plan.writes,seen:apply.seen}))}catch(err){throw err instanceof ApplyError&&err.written.length>0&&records!==null&&await writeRecords(cwd,{skillsVersion:config.skillsVersion,commit:config.commit,files:{...records,...buildRecords(cwd,err.written)}}),err}await writeRecords(cwd,nextRecordStore(apply,{written:buildRecords(cwd,written),unwritten})),await writePharnConfig(cwd,nextConfig(config,report,apply,channel,{pharnVersion:PHARN_VERSION,updatedAt:new Date().toISOString()}));let gitignore=await applyGitignore(cwd),prettierignore=await applyPrettierignore(cwd,apply.prettierignorePaths);return{installedVersion:report.installedVersion,recordedVersion:report.recordedVersion,capCount:report.capCount,capabilityChanges:report.capabilityChanges,removals:report.removals,plan,backup,recordsNote:report.recordsNote,versionWithheld:report.versionWithheld,featuresReadmeRelocation:report.featuresReadmeRelocation,hookWiring:report.hookWiring,absentUpstream:report.absentUpstream,models,modelsFloor:report.modelsFloor,orphans:report.orphans,gitignore,prettierignore}}function unchangedOutcome(planned){let{report,apply}=planned;return{installedVersion:report.installedVersion,recordedVersion:report.recordedVersion,capCount:report.capCount,capabilityChanges:report.capabilityChanges,removals:report.removals,plan:apply.plan,backup:null,recordsNote:report.recordsNote,versionWithheld:report.versionWithheld,featuresReadmeRelocation:report.featuresReadmeRelocation,hookWiring:report.hookWiring,absentUpstream:report.absentUpstream,models:apply.models,modelsFloor:report.modelsFloor,orphans:report.orphans,gitignore:report.gitignore,prettierignore:report.prettierignore,unchanged:!0}}function checkMinCli(repoDir,warn=message=>log2.warn(message)){let gate=minCliGate(repoDir,PHARN_VERSION);return gate.warning&&warn(gate.warning),{refusal:gate.refusal??null}}function silentSpinner(){return{start:()=>{},stop:()=>{}}}function emitJson(report){console.log(serializeJsonReport(report))}function planFromClone(repo,config,cwd,force,channel,ui){let{spin,warn,json}=ui,planned;try{let refusal=checkMinCli(repo.dir,warn).refusal;if(refusal)throw CliError.refusal(refusal,{json});planned=buildUpdatePlan({repoDir:repo.dir,sha:repo.sha,config,cwd,force,channel,onUnknownWarning:warn})}catch(err){let removal=err instanceof CapabilityRemovalError;throw spin.stop(removal||err instanceof CliError?"Update refused":"Planning failed"),removal?CliError.refusal(err.message,{json}):CliError.failure(err,{json})}return spin.stop("Plan ready"),planned}async function fetchAndPlan(config,cwd,force,channel,source,ui){ui.spin.start(`Planning from ${REPO_URL}`);let repo;try{repo=await fetchRepo(source)}catch(err){throw ui.spin.stop("Planning failed"),CliError.failure(err,{json:ui.json})}try{return planFromClone(repo,config,cwd,force,channel,ui)}finally{repo.cleanup()}}async function runDryRun(config,cwd,force,channel,source,json,latest,compact){let planned=await fetchAndPlan(config,cwd,force,channel,source,{spin:json?silentSpinner():spinner(),warn:json?message=>logErrorPlain(message):message=>log2.warn(message),json}),{report}=planned;if(json){let empty=report.changesNothing;emitJson(buildUpdateReport({status:empty?"up-to-date":"planned",force,channel,currentChannel:channelOf(config),source,installed:config.skillsVersion,latest,archetypes:config.archetypes??[],plan:empty?null:report,compact}));return}report.changesNothing||printHeader(config,latest,source,force,!0),reportDryRun(report,force,channel,config)}export{runUpdate};
|
package/package.json
CHANGED
package/dist/add-7RVWOQW6.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{installCapabilityDirs,scanDest}from"./chunk-NVSBRL4G.js";import{parseCapabilityArg}from"./chunk-QGQRN6AC.js";import{minCliGate}from"./chunk-DFMTJQO7.js";import{ProjectLockedError,backupDirIgnored,buildAddSelection,createBackup,interactiveAllowed,printBackupNotice,withProjectLock}from"./chunk-ZQWLF3HH.js";import"./chunk-BCURDSJC.js";import{detectProxyNotice,fetchRepo,parseCapabilityIndex,proxyNoticeMessage,unknownCapabilitiesWarning,versionStatus}from"./chunk-62AJFPPH.js";import"./chunk-KZCUUHJT.js";import{channelOf,resolveSource,sourceLabel}from"./chunk-LVAJFL6J.js";import{buildRecords,capabilityCloneFiles,configLayout,detectLayout,layoutPaths,mergeRecords,readRecords,readSkillsVersion,recordsBaseline,warnIfOlderCli,writeRecords}from"./chunk-FUQURK5N.js";import{PHARN_VERSION,REPO_URL}from"./chunk-SQLIXTIY.js";import{logError}from"./chunk-C5RBIXPQ.js";import{assertConfigFingerprintUnchanged,color_default,configFingerprint,loadArchetypeConfig,writePharnConfig}from"./chunk-LF4PFADC.js";import"./chunk-L3QGAX2K.js";import{CliError}from"./chunk-A77BLCF4.js";import{intro,log as log2,outro,spinner}from"@clack/prompts";import{groupMultiselect,isCancel,log}from"@clack/prompts";async function resolveAddPicker(repoDir,sha,config,cwd,addOne,beforeWrite=()=>{}){let index=parseCapabilityIndex(repoDir),unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&log.warn(unknownWarning);let installed=config.capabilities??[],{groups,availableCount}=buildAddSelection(index,installed);if(availableCount===0)return{kind:"all-installed"};installed.length>0&&log.info(`Installed (${installed.length}): ${installed.map(c=>`${c.name} (${c.role})`).join(", ")}`);let picked=await groupMultiselect({message:"Select capabilities to add",options:groups,required:!1,selectableGroups:!1});if(isCancel(picked))return{kind:"cancelled"};let values=picked;if(values.length===0)return{kind:"none"};beforeWrite();let added=[],failed=[],cfg=config;for(let value of values){let parsed=parseCapabilityArg(value),result=await addOne(repoDir,sha,cfg,cwd,parsed,value,index);result.kind==="added"?(log.info(`${color_default.green("\u2714")} Added ${result.name}`),added.push(result.name),cfg={...cfg,...result.stamp,capabilities:[...cfg.capabilities??[],{name:parsed.name,role:parsed.role,source:"manual"}]}):result.kind==="noop"?log.info(`${result.name} is already installed.`):(logError(`\u26A0 ${result.message}`),failed.push(value))}return{kind:"installed",added,failed}}async function runAdd(capabilityArg){intro("pharn add");let cwd=process.cwd();try{await withProjectLock(cwd,"add",()=>{let fingerprint=configFingerprint(cwd),config=loadArchetypeConfig(cwd);return warnIfOlderCli(config),runArchetypeAdd(config,cwd,capabilityArg,fingerprint)})}catch(err){throw addError(err)}}function versionGate(repoDir,config,source){let fetched=readSkillsVersion(repoDir);if(fetched===config.skillsVersion||fetched===config.pendingSkillsVersion)return null;if(versionStatus({installed:config.skillsVersion,latest:fetched}).ahead)return source.kind==="release"?`Your install (skills v${config.skillsVersion}) is ahead of the latest verified ${REPO_URL} release (${source.tag}) \u2014 it came from pharn-oss main, and \`pharn add\` installs only at the version your project is already on. Run \`pharn update --ref main\` to follow main (\`pharn add\` then fetches from it too), or wait for a release at v${config.skillsVersion}.`:`Your install (skills v${config.skillsVersion}) is newer than ${REPO_URL} main (v${fetched}) \u2014 pharn-oss main has moved back to an older version, and \`pharn add\` installs only at the version your project is already on. Wait for main to reach v${config.skillsVersion} again, or run \`pharn update --force\` to downgrade to v${fetched} first (it backs up the files you edited to pharn/.backup/), then re-run \`pharn add\`.`;let partly=config.pendingSkillsVersion===void 0?"":` (partly at v${config.pendingSkillsVersion})`;return`Skills version mismatch: pharn.config.json records v${config.skillsVersion}${partly}, but the fetched ${REPO_URL} is at v${fetched}. \`pharn add\` installs only at the version your project is already on. Run \`pharn update\` to move it to v${fetched}; if update cannot finish (\`pharn update --dry-run\` shows which files block it), revert those files or run \`pharn update --force\` (it backs them up to pharn/.backup/ first), then re-run \`pharn add\`.`}function addStamp(config,version,sha){return version===config.skillsVersion?{skillsVersion:version,commit:sha}:{skillsVersion:config.skillsVersion,commit:config.commit}}function layoutGate(repoDir,config){let clone=detectLayout(repoDir),recorded=configLayout(config);return clone===recorded?null:`Install layout mismatch: pharn.config.json records the \`${recorded}\` layout, but the fetched ${REPO_URL} uses the \`${clone}\` layout. \`pharn add\` installs only at the layout your project is already recorded at \u2014 adding here would put files where \`pharn remove\` and \`pharn status\` will never look for them. Run \`pharn update --force\` first, then re-run \`pharn add\`.`}async function runArchetypeAdd(config,cwd,arg,fingerprint){if(arg===void 0){await runAddPicker(config,cwd,fingerprint);return}let parsed=parseCapabilityArg(arg);if(parsed.error)throw CliError.error(parsed.error);let proxyNotice=detectProxyNotice(process.env);proxyNotice&&log2.warn(proxyNoticeMessage(proxyNotice));let s=spinner();s.start(`Fetching capabilities from ${REPO_URL}`);let repo;try{repo=await fetchRepo(await resolveSource(channelOf(config))),s.stop(`Capabilities fetched from ${sourceLabel(repo.source)}`)}catch(err){throw s.stop("Failed to fetch capabilities"),err}let result;try{let gate=minCliGate(repo.dir,PHARN_VERSION);gate.warning&&log2.warn(gate.warning);let refusal=gate.refusal??versionGate(repo.dir,config,repo.source)??layoutGate(repo.dir,config);if(refusal)throw CliError.refusal(refusal);assertConfigFingerprintUnchanged(cwd,fingerprint,"add"),result=await resolveArchetypeAdd(repo.dir,repo.sha,config,cwd,parsed,arg)}finally{repo.cleanup()}if(result.kind==="error")throw CliError.refusal(result.message);if(result.kind==="noop"){outro(`${result.name} is already installed.`);return}outro(`${color_default.green("\u2714")} Added ${result.name} ${color_default.dim(`(skills v${result.version})`)}`)}async function runAddPicker(config,cwd,fingerprint){if(!interactiveAllowed({stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY}))throw CliError.error("Specify a capability (e.g. `pharn add a11y` or `pharn add lens:n-plus-one`), or run `pharn add` in an interactive terminal to pick from a list.");let proxyNotice=detectProxyNotice(process.env);proxyNotice&&log2.warn(proxyNoticeMessage(proxyNotice));let s=spinner();s.start(`Fetching capabilities from ${REPO_URL}`);let repo;try{repo=await fetchRepo(await resolveSource(channelOf(config))),s.stop(`Capabilities fetched from ${sourceLabel(repo.source)}`)}catch(err){throw s.stop("Failed to fetch capabilities"),err}let outcome;try{let gate=minCliGate(repo.dir,PHARN_VERSION);gate.warning&&log2.warn(gate.warning);let refusal=gate.refusal??versionGate(repo.dir,config,repo.source)??layoutGate(repo.dir,config);if(refusal)throw CliError.refusal(refusal);outcome=await resolveAddPicker(repo.dir,repo.sha,config,cwd,resolveArchetypeAdd,()=>assertConfigFingerprintUnchanged(cwd,fingerprint,"add"))}finally{repo.cleanup()}if(outcome.kind==="all-installed"){outro("All available capabilities are already installed.");return}if(outcome.kind==="cancelled")throw CliError.cancel();if(outcome.kind==="none"){outro("Nothing selected. No capabilities were added.");return}let n=outcome.added.length;if(outcome.failed.length===0){outro(`${color_default.green("\u2714")} Added ${n} ${plural(n)}.`);return}let failures=`${outcome.failed.length} failed: ${outcome.failed.join(", ")}.`;throw outro(n===0?`No capabilities were added; ${failures}`:`Added ${n} ${plural(n)}; ${failures}`),CliError.reported()}function plural(n){return n===1?"capability":"capabilities"}function addError(err){return err instanceof ProjectLockedError?CliError.refusal(err.message):CliError.failure(err)}async function resolveArchetypeAdd(repoDir,sha,config,cwd,parsed,arg,parsedIndex){let index=parsedIndex;if(index===void 0){index=parseCapabilityIndex(repoDir);let unknownWarning=unknownCapabilitiesWarning(index.unknown);unknownWarning&&log2.warn(unknownWarning)}let matches=index.capabilities.filter(c=>c.name===parsed.name&&(parsed.role===void 0||c.role===parsed.role));if(matches.length===0){let valid=index.capabilities.map(c=>`${c.role}:${c.name}`).sort();return{kind:"error",message:`Unknown capability "${arg}". Valid capabilities:
|
|
2
|
-
${valid.join(`
|
|
3
|
-
`)}`}}if(matches.length>1)return{kind:"error",message:`"${parsed.name}" is ambiguous \u2014 use ${matches.map(m=>`${m.role}:${m.name}`).join(" or ")}.`};let cap=matches[0],existing=config.capabilities??[];if(existing.some(c=>c.name===cap.name&&c.role===cap.role))return{kind:"noop",name:cap.name};let paths=layoutPaths(detectLayout(repoDir)),cloneRels=capabilityCloneFiles(repoDir,paths,cap),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 ${cap.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 ${cap.name}\`.`}}if(scan.drifted.length>0){let backupDir=createBackup(cwd,scan.drifted);printBackupNotice({dir:backupDir,saved:scan.drifted.length,action:"overwriting",gitignored:backupDirIgnored(cwd)})}let caps=[{name:cap.name,role:cap.role}];installCapabilityDirs(repoDir,cwd,caps,scan.seen);let version=readSkillsVersion(repoDir),stamp=addStamp(config,version,sha),capabilities=[...existing,{name:cap.name,role:cap.role,source:"manual"}];return await mergeCapabilityRecords(cwd,config,cloneRels,stamp.skillsVersion,stamp.commit),await writePharnConfig(cwd,{...config,...stamp,capabilities}),{kind:"added",name:cap.name,version,stamp}}async function mergeCapabilityRecords(cwd,config,cloneRels,skillsVersion,commit){let{records}=recordsBaseline(readRecords(cwd));if(records===null)return;let added=buildRecords(cwd,cloneRels);await writeRecords(cwd,{skillsVersion,commit,files:mergeRecords(records,added)})}export{runAdd};
|
package/dist/chunk-62AJFPPH.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{MAX_SHA_BYTES}from"./chunk-LVAJFL6J.js";import{detectLayout,layoutPaths,manifestCapabilityIndex,onFatalSignal,readSkillsVersion,readUpstreamManifest,verifyUpstreamManifest}from"./chunk-FUQURK5N.js";import{REPO,REPO_BRANCH,SKILLS_VERSION_FILE,fetchCapped}from"./chunk-SQLIXTIY.js";import{CAPABILITY_NAME_RE,COMMIT_RE,ManifestValidationError,assertAppliesToken,assertRole,assertSafeString,safeJoin}from"./chunk-L3QGAX2K.js";import{escapeUnsafe,hasUnsafeChars,terminalSafe}from"./chunk-A77BLCF4.js";import{closeSync,existsSync,fstatSync,openSync,readFileSync,readdirSync}from"node:fs";function parseCapabilityIndex(repoDir){let manifest=readUpstreamManifest(repoDir);if(manifest)return manifestCapabilityIndex(manifest);let capabilities=[],unknown=[],paths=layoutPaths(detectLayout(repoDir)),subtrees=[{dir:paths.grillers,role:"griller"},{dir:paths.lenses,role:"lens"}];for(let subtree of subtrees){let subtreeDir=safeJoin(repoDir,subtree.dir);if(!existsSync(subtreeDir))throw new ManifestValidationError(`Capability subtree "${subtree.dir}" is missing in the fetched repo.`);let names=readdirSync(subtreeDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort((a,b)=>a<b?-1:a>b?1:0);for(let name of names)try{assertSafeString(name,`capability "${name}"`,CAPABILITY_NAME_RE);let capFile=safeJoin(subtreeDir,`${name}/${name}.md`),frontmatter=extractFrontmatter(readCapabilityMarkdown(capFile,name,subtree.dir),name),role=assertRole(readRole(frontmatter,name),name);if(role!==subtree.role)throw new ManifestValidationError(`Capability "${name}" declares role "${role}" but lives under ${subtree.dir} (expected "${subtree.role}").`);let applies=readApplies(frontmatter,name);capabilities.push({name,role,applies})}catch(err){if(!(err instanceof ManifestValidationError))throw err;unknown.push({name,role:subtree.role,subtree:subtree.dir,reason:err.message})}}return{capabilities,unknown}}function readCapabilityMarkdown(capFile,name,subtreeDir){let fd;try{fd=openSync(capFile,"r")}catch(err){let code=err.code;throw code==="ENOENT"?new ManifestValidationError(`Capability "${name}" in ${subtreeDir} is missing its markdown ${name}/${name}.md.`):code==="EISDIR"?new ManifestValidationError(`Capability "${name}" in ${subtreeDir}: ${name}/${name}.md is not a regular file.`):err}try{if(!fstatSync(fd).isFile())throw new ManifestValidationError(`Capability "${name}" in ${subtreeDir}: ${name}/${name}.md is not a regular file.`);return readFileSync(fd,"utf8")}finally{closeSync(fd)}}var BOM_RE=/^\uFEFF/,DISPLACED_LEAD_RE=/^[\s\p{Cf}]+(?=---)/u;function extractFrontmatter(content,name){let text=content.replace(BOM_RE,""),displaced=!1;if(!text.startsWith("---")){let lead=DISPLACED_LEAD_RE.exec(text);lead&&(text=text.slice(lead[0].length),displaced=!0)}let end=text.startsWith("---")?text.indexOf(`
|
|
2
|
-
---`,3):-1;if(end===-1)throw new ManifestValidationError(`Capability "${name}" is missing a "---"-fenced frontmatter block.`);if(displaced)throw new ManifestValidationError(`Capability "${name}": the frontmatter fence is not at the start of the file (whitespace or an invisible character precedes the opening ---).`);return text.slice(3,end).trim()}var FIELD_LINE_RE=/^([A-Za-z0-9_]+):\s*(.*)$/;function unquote(value){return value.replace(/^["']|["']$/g,"")}function readField(frontmatter,field){let value;for(let line of frontmatter.split(/\r?\n/)){let m=FIELD_LINE_RE.exec(line);if(!m||m[1]!==field)continue;let val=m[2].trim();value=val.startsWith("[")&&val.endsWith("]")?val.slice(1,-1).split(",").map(s=>unquote(s.trim())).filter(Boolean):unquote(val)}return value===""?void 0:value}function missingField(field,name){return new ManifestValidationError(`Capability "${name}" is missing the "${field}" frontmatter field.`)}function readRole(frontmatter,name){let role=readField(frontmatter,"role");if(role===void 0)throw missingField("role",name);if(Array.isArray(role))throw new ManifestValidationError(`Capability "${name}" has a malformed "role" value ${JSON.stringify(role)} (expected one role, not an array).`);return role}function readApplies(frontmatter,name){let raw=readField(frontmatter,"applies");if(raw===void 0)throw missingField("applies",name);let tokens=Array.isArray(raw)?raw:[raw];if(tokens.length===0)throw new ManifestValidationError(`Capability "${name}" has an empty "applies" array \u2014 every capability must declare its applicability.`);let validated=tokens.map(t=>assertAppliesToken(t,`capability "${name}"`));return validated.includes("universal")?"universal":validated}var MAX_FIELD=200,MAX_LISTED=10;function safe(value){return terminalSafe(value,{max:MAX_FIELD})}function unknownCapabilitiesWarning(unknown){if(unknown.length===0)return null;let listed=unknown.slice(0,MAX_LISTED),lines=[`${unknown.length} upstream ${unknown.length===1?"capability":"capabilities"} could not be read and ${unknown.length===1?"was":"were"} SKIPPED \u2014 not installed:`];for(let u of listed)lines.push(` ${u.role}:${safe(u.name)} (${safe(u.subtree)}) \u2014 ${safe(u.reason)}`);return unknown.length>listed.length&&lines.push(` \u2026and ${unknown.length-listed.length} more.`),lines.push("This usually means pharn-oss changed something your pharn version does not understand yet. Upgrade with `npm install -g @pharn-dev/pharn@latest`."),lines.join(`
|
|
3
|
-
`)}import{mkdtempSync,rmSync}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{gunzipSync}from"node:zlib";import{mkdirSync,writeFileSync}from"node:fs";import{dirname}from"node:path";var BLOCK=512,OFF_NAME=0,LEN_NAME=100,OFF_SIZE=124,LEN_SIZE=12,OFF_CHKSUM=148,LEN_CHKSUM=8,OFF_TYPEFLAG=156,OFF_MAGIC=257,OFF_PREFIX=345,LEN_PREFIX=155,TarExtractError=class extends Error{constructor(message){super(message),this.name="TarExtractError"}};function readString(block,offset,length){let raw=block.subarray(offset,offset+length),end=raw.indexOf(0);return raw.subarray(0,end===-1?raw.length:end).toString("latin1")}function describeBytes(bytes,max=200){let out="";for(let byte of bytes.subarray(0,max))out+=byte>=32&&byte<=126&&byte!==92?String.fromCharCode(byte):`\\x${byte.toString(16).padStart(2,"0")}`;return bytes.length>max?`${out}\u2026`:out}var PATH_DECODER=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});function readPathField(block,offset,length){let raw=block.subarray(offset,offset+length),end=raw.indexOf(0),bytes=raw.subarray(0,end===-1?raw.length:end);try{return PATH_DECODER.decode(bytes)}catch{throw new TarExtractError(`tar entry path is not valid UTF-8: "${describeBytes(bytes)}"`)}}function readOctal(block,offset,length){let text=readString(block,offset,length).replace(/^ +| +$/g,"");if(text==="")return 0;if(!/^[0-7]+$/.test(text))throw new TarExtractError(`tar header has a non-octal numeric field: "${describeBytes(Buffer.from(text,"latin1"),32)}"`);return parseInt(text,8)}function assertDisplayablePath(fullPath){if(hasUnsafeChars(fullPath))throw new TarExtractError(`tar entry path contains a control or format character: "${escapeUnsafe(fullPath.length>200?`${fullPath.slice(0,200)}\u2026`:fullPath)}"`)}function describeTypeflag(typeflag){return typeflag==="x"?"'x' (a pax extended header, whose records would override the next entry's path and size)":hasUnsafeChars(typeflag)?`0x${typeflag.charCodeAt(0).toString(16).padStart(2,"0")}`:`'${typeflag}'`}function assertZeroTail(tar,from){for(let i=from;i<tar.length;i+=1)if(tar[i]!==0)throw new TarExtractError("tar archive has data after its end-of-archive marker.")}function isZeroBlock(block){for(let byte of block)if(byte!==0)return!1;return!0}function checksumOk(block){let stored=readOctal(block,OFF_CHKSUM,LEN_CHKSUM),unsigned=0,signed=0;for(let i=0;i<BLOCK;i+=1){let byte=i>=OFF_CHKSUM&&i<OFF_CHKSUM+LEN_CHKSUM?32:block[i];unsigned+=byte,signed+=byte>127?byte-256:byte}return stored===unsigned||stored===signed}function resolveEntryPath(fullPath,isDirectory,expectedRoot){if(fullPath==="")throw new TarExtractError("tar entry has an empty path.");if(fullPath.startsWith("/"))throw new TarExtractError(`tar entry has an absolute path: ${fullPath}`);if(/[\\:]/.test(fullPath))throw new TarExtractError(`tar entry path contains a backslash or colon, which pharn does not accept: ${fullPath}`);let segments=fullPath.replace(/\/+$/,"").split("/");for(let segment of segments)if(segment==="..")throw new TarExtractError(`tar entry escapes the archive root: ${fullPath}`);let root=segments[0];if(root===""||root===".")throw new TarExtractError(`tar entry has no leading component: ${fullPath}`);if(expectedRoot!==null&&root!==expectedRoot)throw new TarExtractError(`tar archive has more than one root component: ${expectedRoot} and ${root}`);let rest=segments.slice(1);if(rest.some(segment=>segment===""||segment==="."))throw new TarExtractError(`tar entry has an empty or "." path segment: ${fullPath}`);if(rest.length===0){if(isDirectory)return{rel:null,root};throw new TarExtractError(`tar entry has no path below the archive root: ${fullPath}`)}return{rel:rest.join("/"),root}}function extractTarGz(archive,destDir,limits){let tar;try{tar=gunzipSync(archive,{maxOutputLength:limits.maxTotalBytes})}catch(err){throw new TarExtractError(`could not decompress the fetched archive: ${err.message}`)}extractTar(tar,destDir,limits)}function extractTar(tar,destDir,limits){let offset=0,entries=0,expectedRoot=null;for(;offset+BLOCK<=tar.length;){let header=tar.subarray(offset,offset+BLOCK);if(isZeroBlock(header)){assertZeroTail(tar,offset+BLOCK);return}if(!checksumOk(header))throw new TarExtractError("tar header failed its checksum \u2014 the archive is corrupt or truncated.");if(header.toString("latin1",OFF_MAGIC,OFF_MAGIC+5)!=="ustar")throw new TarExtractError('tar header is not a ustar header (missing "ustar" magic).');let size=readOctal(header,OFF_SIZE,LEN_SIZE),dataStart=offset+BLOCK,dataEnd=dataStart+size;if(dataEnd>tar.length)throw new TarExtractError("tar entry runs past the end of the archive \u2014 truncated.");let next=dataStart+Math.ceil(size/BLOCK)*BLOCK,typeflag=String.fromCharCode(header[OFF_TYPEFLAG]);if(typeflag==="g"){if(entries+=1,entries>limits.maxEntries)throw new TarExtractError(`tar archive has more than ${limits.maxEntries} entries.`);offset=next;continue}let name=readPathField(header,OFF_NAME,LEN_NAME),prefix=readPathField(header,OFF_PREFIX,LEN_PREFIX),fullPath=prefix===""?name:`${prefix}/${name}`;assertDisplayablePath(fullPath);let isFile=typeflag==="0"||typeflag==="\0",isDirectory=typeflag==="5";if(!isFile&&!isDirectory)throw new TarExtractError(`tar entry has an unsupported type ${describeTypeflag(typeflag)}: ${fullPath}`);let{rel,root}=resolveEntryPath(fullPath,isDirectory,expectedRoot);if(expectedRoot=root,rel!==null){if(entries+=1,entries>limits.maxEntries)throw new TarExtractError(`tar archive has more than ${limits.maxEntries} entries.`);let target=safeJoin(destDir,rel);isDirectory?mkdirSync(target,{recursive:!0}):(mkdirSync(dirname(target),{recursive:!0}),writeFileSync(target,tar.subarray(dataStart,dataEnd)))}offset=next}throw new TarExtractError("tar archive has no end-of-archive marker \u2014 truncated.")}var API="https://api.github.com",CODELOAD="https://codeload.github.com",FETCH_TIMEOUT_MS=8e3,CLONE_TIMEOUT_MS=6e4,MAX_ARCHIVE_BYTES=32*1024*1024,MAX_EXTRACTED_BYTES=128*1024*1024,MAX_ENTRIES=2e4,liveClones=new Set,handlersInstalled=!1;function rmQuiet(dir){try{rmSync(dir,{recursive:!0,force:!0})}catch{}}function installCleanupHandlers(){handlersInstalled||(handlersInstalled=!0,process.on("exit",()=>{for(let dir of liveClones)rmQuiet(dir)}),onFatalSignal(()=>{for(let dir of liveClones)rmQuiet(dir);liveClones.clear()}))}async function fetchRepo(source){return source.kind==="release"?fetchAt(source,source.sha):fetchAt(source,await fetchCommitSha())}async function fetchAt(source,rawSha){let sha=rawSha===null?null:assertSafeString(rawSha,"commit SHA",COMMIT_RE),ref=sha??`refs/heads/${REPO_BRANCH}`;installCleanupHandlers();let dir=mkdtempSync(join(tmpdir(),"pharn-"));liveClones.add(dir);try{let archive=await downloadArchive(ref);if(extractTarGz(archive,dir,{maxEntries:MAX_ENTRIES,maxTotalBytes:MAX_EXTRACTED_BYTES}),source.kind==="release"){let found=readSkillsVersion(dir);if(found!==source.version)throw new ManifestValidationError(`Release ${source.tag} (${source.sha}) ships ${SKILLS_VERSION_FILE} ${found}, not ${source.version}; refusing to install a release whose content does not match its tag.`)}let manifest=readUpstreamManifest(dir);manifest&&verifyUpstreamManifest(dir,manifest)}catch(err){throw liveClones.delete(dir),rmSync(dir,{recursive:!0,force:!0}),err}return{dir,sha,source,cleanup:()=>{liveClones.delete(dir),rmSync(dir,{recursive:!0,force:!0})}}}async function downloadArchive(ref){let url=`${CODELOAD}/${REPO}/tar.gz/${ref}`,got;try{got=await fetchCapped(url,{maxBytes:MAX_ARCHIVE_BYTES,ms:CLONE_TIMEOUT_MS})}catch(err){let capped=err;throw capped.kind==="unreachable"?capped.cause:new Error(capped.kind==="timeout"?`Timed out downloading ${url} after ${CLONE_TIMEOUT_MS/1e3}s.`:`Refusing ${url}: archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`,{cause:err})}if(!got.ok)throw new Error(`Failed to download ${url}: HTTP ${got.status}`);if(got.body.byteLength===0)throw new Error(`Failed to download ${url}: empty response body`);return got.body}async function fetchCommitSha(){let url=`${API}/repos/${REPO}/commits/refs/heads/${REPO_BRANCH}`;try{let got=await fetchCapped(url,{accept:"application/vnd.github.sha",maxBytes:MAX_SHA_BYTES,ms:FETCH_TIMEOUT_MS});if(!got.ok)return null;let text=got.body.toString("utf8").trim();return/^\S+$/.test(text)?text:null}catch{return null}}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(key=>!READ_SPELLINGS.has(key)&&READ_SPELLINGS.has(key.toLowerCase())&&isSet(env[key])).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 shown=`${notice.name} is set (${redactProxyUrl(notice.value)})`;if(notice.envProxy==="on")return`${shown} 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`${shown}, but pharn will not use it: Node reads only https_proxy, HTTPS_PROXY, http_proxy and HTTP_PROXY, spelled exactly so. ${direct}`;let base=`${shown}, 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.`}var CORE_RE=/^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/;function core(version){let match=CORE_RE.exec(version);return match?[Number(match[1]),Number(match[2]),Number(match[3])]:null}function compareVersionCore(a,b){let left=core(a),right=core(b);if(left===null||right===null)return null;for(let i=0;i<3;i++){let l=left[i],r=right[i];if(l!==r)return l>r?1:-1}return 0}function versionStatus(input){let ahead=compareVersionCore(input.installed,input.latest)===1,outdated=!ahead&&input.installed!==input.latest;return{ahead,outdated}}export{parseCapabilityIndex,unknownCapabilitiesWarning,compareVersionCore,fetchRepo,detectProxyNotice,proxyNoticeMessage,versionStatus};
|
package/dist/chunk-7LD2OYB4.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{planUninstall}from"./chunk-PDDT7V7X.js";import{capabilityDir,capabilityRelDir,linkedComponent,removalBackupSet}from"./chunk-6LOUFC5E.js";import{checkModelsBlock,nodeFloorRefusal,nodeFloorStatus}from"./chunk-B4EM6WAR.js";import{contentHash,findSymlinkComponent,readUpstreamManifest,resolveTrustedDocs}from"./chunk-FUQURK5N.js";import{PHARN_ROOT_FALLBACK_DOCS}from"./chunk-SQLIXTIY.js";import{readBoundedFile,readJsonBounded}from"./chunk-LF4PFADC.js";import{isPlainObject,safeJoin}from"./chunk-L3QGAX2K.js";import{CliError,errorMessage,terminalSafe}from"./chunk-A77BLCF4.js";import{lstatSync,readdirSync,unlinkSync}from"node:fs";var ROOT_MIGRATION_FROM_MAJOR=7,USER_DATA_PATHS=[{from:"memory-bank",to:"pharn/memory-bank",dir:!0},{from:"pharn.spec-template.md",to:"pharn/spec-template.md",dir:!1}],GITIGNORE_REPLACEMENTS=[{old:".pharn",hint:"pharn/.run/"}],SCRATCH_DIR=".pharn",SCRATCH_KEEP="ci.yml";function versionMajor(version){let m=/^(\d+)\./.exec(version);return m===null?null:Number(m[1])}function planRootMigration(input){let{projectRoot,repoDir,layout,skillsVersion,records}=input;if(layout!=="pharn"||input.installedLayout!=="pharn")return null;let docs=planRootDocs(projectRoot,repoDir,records),major=versionMajor(skillsVersion),sevenApplies=major!==null&&major>=ROOT_MIGRATION_FROM_MAJOR;return!sevenApplies&&docs.length===0?null:{docs,userData:sevenApplies?userDataHints(projectRoot):[],scratchNotice:sevenApplies&&scratchNotice(projectRoot),gitignoreHints:sevenApplies?gitignoreHints(projectRoot):[]}}function planRootDocs(projectRoot,repoDir,records){let shipped=new Set(resolveTrustedDocs(repoDir,"pharn")),steps=[];for(let[pharnRel,rootRel]of Object.entries(PHARN_ROOT_FALLBACK_DOCS))shipped.has(pharnRel)&&steps.push({rel:rootRel,action:classifyRootDoc(projectRoot,rootRel,records)});return steps}function classifyRootDoc(projectRoot,rel,records){let recorded=records!==null&&Object.hasOwn(records,rel)?records[rel]:void 0;if(recorded===void 0){let stat;try{stat=lstatSync(safeJoin(projectRoot,rel),{throwIfNoEntry:!1})}catch{return"unverifiable"}return stat===void 0?"absent":"unverifiable"}let plan=planUninstall(projectRoot,{[rel]:recorded});return plan.delete.length>0?"delete":plan.edited.length>0?"keep-edited":plan.absent.length>0?"absent":"unverifiable"}function userDataHints(projectRoot){let present=rel=>{try{return lstatSync(safeJoin(projectRoot,rel),{throwIfNoEntry:!1})!==void 0}catch{return null}},hints=[];for(let{from,to,dir}of USER_DATA_PATHS){if(present(from)!==!0)continue;let shown=rel=>dir?`${rel}/`:rel;hints.push({from:shown(from),to:shown(to),destination:present(to)===!1?"free":"exists"})}return hints}function scratchNotice(projectRoot){try{let stat=lstatSync(safeJoin(projectRoot,SCRATCH_DIR),{throwIfNoEntry:!1});return stat===void 0||!stat.isDirectory()?!1:readdirSync(safeJoin(projectRoot,SCRATCH_DIR)).some(name=>name!==SCRATCH_KEEP)}catch{return!1}}function gitignoreHints(projectRoot){let read=readBoundedFile(safeJoin(projectRoot,".gitignore"));if(read.kind!=="ok")return[];let lines=new Set(read.bytes.toString("utf8").split(`
|
|
2
|
-
`).map(line=>line.trim().replace(/^\//,"").replace(/(\/\*\*|\/\*|\/|\*)$/,"")));return GITIGNORE_REPLACEMENTS.filter(({old})=>lines.has(old)).map(({hint})=>hint)}function rootDocsChangedSincePlan(projectRoot,docs,records){return docs.filter(d=>d.action==="delete"&&classifyRootDoc(projectRoot,d.rel,records)!=="delete").map(d=>d.rel)}function deleteRootDocs(projectRoot,repoDir,docs,records){let deleted=[],kept=[],changed=new Set(rootDocsChangedSincePlan(projectRoot,docs,records));for(let{rel,action}of docs){if(action!=="delete")continue;let pharnRel=pharnCounterpart(rel);if(changed.has(rel)||pharnRel===null||!landed(projectRoot,repoDir,pharnRel)){kept.push(rel);continue}try{unlinkSync(safeJoin(projectRoot,rel)),deleted.push(rel)}catch{kept.push(rel)}}return{deleted,kept}}function pharnCounterpart(rootRel){for(let[pharnRel,rel]of Object.entries(PHARN_ROOT_FALLBACK_DOCS))if(rel===rootRel)return pharnRel;return null}function landed(projectRoot,repoDir,rel){try{if(findSymlinkComponent(projectRoot,rel)!==null)return!1;let stat=lstatSync(safeJoin(projectRoot,rel),{throwIfNoEntry:!1});return stat===void 0||!stat.isFile()?!1:contentHash(safeJoin(projectRoot,rel))===contentHash(safeJoin(repoDir,rel))}catch{return!1}}function rootMigrationNoteLines(m,result){let lines=[],preview=result===null;for(let{rel,action}of m.docs){let now=`pharn/${rel}`;action==="delete"?preview?lines.push(` WOULD DELETE ${rel} \u2014 pharn now keeps it at ${now}, and this copy is still exactly as pharn wrote it.`):result.deleted.includes(rel)?lines.push(` deleted ${rel} \u2014 pharn now keeps it at ${now}.`):lines.push(` kept ${rel} \u2014 ${now} did not land as upstream ships it, so the root copy stays.`):action==="keep-edited"?lines.push(` kept ${rel} \u2014 you edited it. pharn now ships ${now}; this copy is no longer managed (listed under ORPHANED).`):action==="unverifiable"&&lines.push(` kept ${rel} \u2014 pharn cannot prove it wrote these bytes. pharn now ships ${now}; delete this one yourself if it is pharn's old copy.`)}for(let{from,to,destination}of m.userData){let bare=rel=>rel.replace(/\/$/,"");destination==="free"?lines.push(` ${from} is at the project root; PHARN 7 reads ${to}. pharn does not move it. If it is PHARN's, move it: git mv ${bare(from)} ${bare(to)} (or mv, if git does not track it).`):lines.push(` ${from} is at the project root, and ${to} already exists (or cannot be checked); PHARN 7 reads ${to}. pharn does not move or merge them. If the root copy is PHARN's, merge it into ${to} by hand, then delete ${from}.`)}return m.scratchNotice&&lines.push(` ${SCRATCH_DIR}/ \u2014 runtime scratch now lives in pharn/.run/. The old ${SCRATCH_DIR}/ contents other than ${SCRATCH_KEEP} can be deleted.`),m.gitignoreHints.length>0&&lines.push(` .gitignore names pharn's old paths. Replace them with: ${m.gitignoreHints.join(", ")} (pharn only appends its own entries; it never rewrites yours).`),lines.length>0?lines:null}import{existsSync}from"node:fs";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,reason}of drops){let key=`${cap.role}:${cap.name}`;if(seen.has(key))continue;seen.add(key);let label=`${cap.name} (${cap.role})`,abs=capabilityDir(cwd,paths,cap),dir=capabilityRelDir(paths,cap),linked=linkedComponent(cwd,paths,cap);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=existsSync(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,reason,dir,present,backups})}return removals}function removalBackups(removals){return[...new Set(removals.flatMap(r=>r.backups))]}function removalBackupsNow(params){let{cwd,removals,records,command}=params,present=removals.filter(r=>r.present),now;try{now=removalBackupSet(cwd,present.map(r=>r.dir),records)}catch(err){throw new CapabilityRemovalError(`Could not check the files in ${present.map(r=>`${r.dir}/`).join(", ")} before \`pharn ${command}\` deletes them: ${errorMessage(err).replace(/\.$/,"")}. Nothing was changed.`)}return[...new Set([...removalBackups(removals),...now])]}function runNodePrereq(command,opts={}){let refusal=nodeFloorRefusal(nodeFloorStatus(process.versions.node),command);if(refusal!==null)throw CliError.error(refusal,opts)}var MAX_PATH=200;function absentSurfaceLines(absent,opts={}){return absent.length===0?null:[`pharn-oss ships nothing at these paths, so pharn ${opts.preview===!0?"would not install":"did not install"} them:`,...absent.map(({surface,path})=>` ${terminalSafe(path,{max:MAX_PATH})} (${surface})`),"Installed commands, hooks and checkers that use them will not find them.","If pharn-oss moved them, a newer pharn may know where:"," npm i -g @pharn-dev/pharn@latest"]}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(", ")}]; archetypes [${archetypes.join(", ")}]`})}return{selected,skipped}}var UPSTREAM_CONFIG_FILE="pharn.config.json",MAX_UPSTREAM_CONFIG_BYTES=1024*1024;function readUpstreamModels(repoDir){let manifest=readUpstreamManifest(repoDir);if(manifest)return checkUpstreamBlock(manifest.modelsDefaults);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;return isPlainObject(config)?checkUpstreamBlock(config.models):{kind:"invalid",reasons:[`pharn-oss's ${UPSTREAM_CONFIG_FILE} is valid JSON but is not an object`]}}function checkUpstreamBlock(block){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}}export{planRootMigration,rootDocsChangedSincePlan,deleteRootDocs,rootMigrationNoteLines,CapabilityRemovalError,planCapabilityRemovals,removalBackups,removalBackupsNow,resolveCapabilities,readUpstreamModels,runNodePrereq,absentSurfaceLines};
|
package/dist/chunk-FUQURK5N.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{CLAUDE_AGENTS_DIR,CLAUDE_COMMANDS_DIR,CLAUDE_HOOKS_DIR,CLAUDE_SETTINGS_FILE,CONTRACTS_DIR,CORE_DIR,DEV_COMMAND_PREFIX,FEATURES_README,FLAT_LICENSE_DEST,FLOOR_DIR,FLOOR_TEST_FIXTURES_DIRS,FetchCappedError,GRILLERS_DIR,LENSES_DIR,MIN_CLI_FILE,PHARN_CONTRACTS_DIR,PHARN_CORE_DIR,PHARN_FEATURES_README,PHARN_FLOOR_DIR,PHARN_GRILLERS_DIR,PHARN_LENSES_DIR,PHARN_LICENSE_DEST,PHARN_ROOT_FALLBACK_DOCS,PHARN_TRUSTED_DOCS,PHARN_VERSION,PRODUCT_COMMAND_PREFIX,REPO,REPO_BRANCH,SKILLS_VERSION_FILE,TRUSTED_DOCS,UPSTREAM_LICENSE,fetchCapped}from"./chunk-SQLIXTIY.js";import{logErrorPlain}from"./chunk-C5RBIXPQ.js";import{CONFIG_FILENAME,color_default,readBoundedFile,readJsonBounded,writeFileAtomic,writeJsonAtomic}from"./chunk-LF4PFADC.js";import{CAPABILITY_NAME_RE,COPY_FILENAME_RE,ManifestValidationError,VERSION_RE,assertAppliesToken,assertRole,assertSafeString,isPlainObject,safeJoin,toPosix}from"./chunk-L3QGAX2K.js";import{escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";import{existsSync}from"node:fs";function detectLayout(rootDir){return existsSync(safeJoin(rootDir,PHARN_CONTRACTS_DIR))?"pharn":"flat"}function layoutPaths(layout){return layout==="pharn"?{layout,grillers:PHARN_GRILLERS_DIR,lenses:PHARN_LENSES_DIR,contracts:PHARN_CONTRACTS_DIR,core:PHARN_CORE_DIR,floor:PHARN_FLOOR_DIR,docs:PHARN_TRUSTED_DOCS,featuresReadme:PHARN_FEATURES_README,license:{from:UPSTREAM_LICENSE,to:PHARN_LICENSE_DEST}}:{layout,grillers:GRILLERS_DIR,lenses:LENSES_DIR,contracts:CONTRACTS_DIR,core:CORE_DIR,floor:FLOOR_DIR,docs:TRUSTED_DOCS,featuresReadme:FEATURES_README,license:{from:UPSTREAM_LICENSE,to:FLAT_LICENSE_DEST}}}function capabilitySubtree(paths,role){return role==="griller"?paths.grillers:paths.lenses}function configLayout(config){return config.layout==="pharn"?"pharn":"flat"}function flatDeprecationLines(layout){return layout!=="flat"?null:["This install is at the flat layout (PHARN files at the project","root). The flat layout is deprecated and is removed in pharn v0.22.0.",color_default.dim("`pharn update` moves the install to the pharn/ layout; then"),color_default.dim("delete the old top-level copies it leaves behind by hand.")]}function resolveFeaturesReadme(repoDir,layout){if(layout==="pharn"){let preferred=safeJoin(repoDir,PHARN_FEATURES_README);if(!existsSync(preferred))return FEATURES_README}return layoutPaths(layout).featuresReadme}function resolveTrustedDocs(repoDir,layout){let docs=layoutPaths(layout).docs;return layout!=="pharn"?docs:docs.map(doc=>{let fallback=PHARN_ROOT_FALLBACK_DOCS[doc];return fallback===void 0||existsSync(safeJoin(repoDir,doc))?doc:fallback})}import{createHash as createHash2}from"node:crypto";import{lstatSync}from"node:fs";import{resolve}from"node:path";import{createHash}from"node:crypto";import{readFileSync}from"node:fs";var BINARY_SNIFF_BYTES=8e3,CR=13,LF=10;function isBinaryContent(buf){return buf.subarray(0,BINARY_SNIFF_BYTES).includes(0)}function contentHashBytes(buf){let hash=createHash("sha256"),cr=buf.indexOf(CR);if(cr===-1||isBinaryContent(buf))return hash.update(buf).digest("hex");let start=0;for(;cr!==-1;)buf[cr+1]===LF&&(hash.update(buf.subarray(start,cr)),start=cr+1),cr=buf.indexOf(CR,cr+1);return hash.update(buf.subarray(start)).digest("hex")}function contentHash(path){return contentHashBytes(readFileSync(path))}function sha256File(path){return createHash("sha256").update(readFileSync(path)).digest("hex")}function matchesRawSha256(path,expected){return sha256File(path)===expected}var RECORDS_FILE="pharn.records.json",MODELS_RECORD_KEY="pharn.config.json#/models";function modelsRecordHash(block){return createHash2("sha256").update(JSON.stringify(block)).digest("hex")}var RECORDS_SCHEMA_VERSION=1,SHA256_RE=/^[0-9a-f]{64}$/;function isInvalidRecordKey(key){let normalized=toPosix(key);return normalized===""||normalized.startsWith("/")||DRIVE_ABSOLUTE_RE.test(normalized)?!0:normalized.split("/").some(segment=>segment===".."||segment===".")}var DRIVE_ABSOLUTE_RE=/^[A-Za-z]:\//;function recordsPath(cwd){return resolve(cwd,RECORDS_FILE)}function readRecords(cwd){let read=readJsonBounded(recordsPath(cwd));if(read.kind==="absent")return{kind:"absent"};if(read.kind==="unusable")return{kind:"invalid",message:`${RECORDS_FILE} ${read.reason}`};if(read.kind==="invalid-json")return{kind:"invalid",message:`${RECORDS_FILE} is not valid JSON`};let raw=read.value;if(!isPlainObject(raw))return{kind:"invalid",message:`${RECORDS_FILE} is not a JSON object`};if(raw.schemaVersion!==RECORDS_SCHEMA_VERSION)return{kind:"invalid",message:`${RECORDS_FILE} has unknown schemaVersion ${JSON.stringify(raw.schemaVersion)} (expected ${RECORDS_SCHEMA_VERSION})`};if(typeof raw.skillsVersion!="string")return{kind:"invalid",message:`${RECORDS_FILE} has an invalid skillsVersion stamp`};let commit=raw.commit===void 0?null:raw.commit;if(commit!==null&&typeof commit!="string")return{kind:"invalid",message:`${RECORDS_FILE} has an invalid commit stamp`};if(!isPlainObject(raw.files))return{kind:"invalid",message:`${RECORDS_FILE} has no \`files\` object`};let files={};for(let[key,value]of Object.entries(raw.files)){if(isInvalidRecordKey(key))return{kind:"invalid",message:`${RECORDS_FILE} has an invalid file path key ${JSON.stringify(key)}`};if(typeof value!="string"||!SHA256_RE.test(value))return{kind:"invalid",message:`${RECORDS_FILE} has an invalid hash for ${JSON.stringify(key)}`};files[key]=value}return{kind:"ok",store:{schemaVersion:RECORDS_SCHEMA_VERSION,skillsVersion:raw.skillsVersion,commit,files}}}function recordsBaseline(read){return read.kind==="absent"?{records:null,note:null}:read.kind==="invalid"?{records:null,note:read.message}:{records:read.store.files,note:null}}async function writeRecords(cwd,params){let store={schemaVersion:RECORDS_SCHEMA_VERSION,skillsVersion:params.skillsVersion,commit:params.commit,files:sortRecords(params.files)};await writeJsonAtomic(recordsPath(cwd),store)}function sortRecords(files){let out={};for(let key of Object.keys(files).sort())out[key]=files[key];return out}function carriedSettingsRecord(projectRoot,records){let recorded=records?.[CLAUDE_SETTINGS_FILE];if(recorded===void 0)return{};try{return lstatSync(safeJoin(projectRoot,CLAUDE_SETTINGS_FILE),{throwIfNoEntry:!1})===void 0?{}:{[CLAUDE_SETTINGS_FILE]:recorded}}catch{return{}}}function buildRecords(projectRoot,rels){let files={};for(let rel of rels){let dest=safeJoin(projectRoot,rel),stat;try{stat=lstatSync(dest,{throwIfNoEntry:!1})}catch{continue}stat?.isFile()&&(files[rel]=contentHash(dest))}return files}function mergeRecords(prev,next){return{...prev,...next}}function recordsUnderCapabilities(records,paths,capabilities){let prefixes=capabilities.map(cap=>`${capabilitySubtree(paths,cap.role)}/${cap.name}/`);if(prefixes.length===0)return{};let out={};for(let[rel,hash]of Object.entries(records))prefixes.some(prefix=>rel.startsWith(prefix))&&(out[rel]=hash);return out}function isProductCommandFile(name){return!name.includes("/")&&name.endsWith(".md")&&name.startsWith(PRODUCT_COMMAND_PREFIX)&&!name.startsWith(DEV_COMMAND_PREFIX)}function isProductAgentFile(name){return isProductCommandFile(name)}function isInstalledHookFile(name){return!name.includes("/")&&/\.(cjs|mjs)$/.test(name)&&!/\.test\.(cjs|mjs)$/.test(name)}var BOTH_LAYOUTS=[layoutPaths("flat"),layoutPaths("pharn")],SURFACE_DIRS=BOTH_LAYOUTS.flatMap(p=>[p.contracts,p.core,p.floor]),SURFACE_FILES=new Set(BOTH_LAYOUTS.flatMap(p=>[...p.docs,p.license.to,p.featuresReadme])),CAPABILITY_SUBTREES=BOTH_LAYOUTS.flatMap(p=>[{subtree:p.grillers,role:"griller"},{subtree:p.lenses,role:"lens"}]);function directChild(rel,dir){if(!rel.startsWith(`${dir}/`))return null;let name=rel.slice(dir.length+1);return name!==""&&!name.includes("/")?name:null}function capabilityOf(rel){for(let{subtree,role}of CAPABILITY_SUBTREES){if(!rel.startsWith(`${subtree}/`))continue;let rest=rel.slice(subtree.length+1),slash=rest.indexOf("/");return slash<=0||slash===rest.length-1?null:`${role}:${rest.slice(0,slash)}`}return null}function isInstallRootPath(rel){return rel===MODELS_RECORD_KEY?!1:isLegacyInstallPath(rel)||isPharnOwnedPath(rel)}function isLegacyInstallPath(rel){if(SURFACE_FILES.has(rel)||SURFACE_DIRS.some(dir=>rel.startsWith(`${dir}/`))||capabilityOf(rel)!==null)return!0;let command=directChild(rel,CLAUDE_COMMANDS_DIR);if(command!==null)return isProductCommandFile(command);let agent=directChild(rel,CLAUDE_AGENTS_DIR);if(agent!==null)return isProductAgentFile(agent);let hook=directChild(rel,CLAUDE_HOOKS_DIR);return hook!==null?isInstalledHookFile(hook):!1}var PHARN_ROOT="pharn",CLAUDE_ROOT=".claude",OWNED_SEGMENT_RE=/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/,CLAUDE_DIR_RE=/^[a-z0-9]+(-[a-z0-9]+)*$/,isPharnOwnedName=name=>name.startsWith(PRODUCT_COMMAND_PREFIX)&&!name.startsWith(DEV_COMMAND_PREFIX)&&name.length>PRODUCT_COMMAND_PREFIX.length,PHARN=layoutPaths("pharn"),PHARN_FIXED_FILES=new Set([...PHARN.docs,PHARN.license.to,PHARN.featuresReadme]),PHARN_FIXED_DIRS=[PHARN.floor],PHARN_SUBTREES=[PHARN.grillers,PHARN.lenses];function isPharnOwnedPath(rel){let segments=rel.split("/"),[root,entry]=segments;if(root!==PHARN_ROOT&&root!==CLAUDE_ROOT)return!1;let below=segments.slice(1);if(below.length===0||!below.every(s=>OWNED_SEGMENT_RE.test(s)))return!1;if(root===PHARN_ROOT)return PHARN_FIXED_FILES.has(rel)||PHARN_FIXED_DIRS.some(dir2=>rel.startsWith(`${dir2}/`))?!0:PHARN_SUBTREES.some(dir2=>rel.startsWith(`${dir2}/`))?capabilityOf(rel)!==null:segments.length>2&&isPharnOwnedName(entry);if(segments.length<3)return!1;let dir=entry,name=segments[2];if(!CLAUDE_DIR_RE.test(dir))return!1;let isFile=segments.length===3;return isFile&&`${root}/${dir}`===CLAUDE_HOOKS_DIR&&isInstalledHookFile(name)?COPY_FILENAME_RE.test(name):isPharnOwnedName(name)?!isFile||COPY_FILENAME_RE.test(name):!1}import{closeSync,existsSync as existsSync2,openSync,readFileSync as readFileSync2,readSync}from"node:fs";var RAW="https://raw.githubusercontent.com",MAX_MIN_CLI_BYTES=1024,FETCH_TIMEOUT_MS=8e3,MAX_BODY_BYTES=256*1024;function readSkillsVersion(repoDir){let path=safeJoin(repoDir,SKILLS_VERSION_FILE);if(!existsSync2(path))throw new ManifestValidationError(`${SKILLS_VERSION_FILE} is missing in the fetched repo.`);return assertSafeString(readFileSync2(path,"utf8").trim(),SKILLS_VERSION_FILE,VERSION_RE)}function readMinCli(repoDir){let path=safeJoin(repoDir,MIN_CLI_FILE),fd;try{fd=openSync(path,"r")}catch(err){return err.code==="ENOENT"?{version:null,warning:null}:{version:null,warning:unusableMinCli(err)}}let raw;try{let buf=Buffer.alloc(MAX_MIN_CLI_BYTES+1),bytes=readSync(fd,buf,0,buf.length,0);if(bytes>MAX_MIN_CLI_BYTES)return{version:null,warning:`${MIN_CLI_FILE} in the fetched repo is too large to be a version; continuing without a minimum-version constraint.`};raw=buf.subarray(0,bytes).toString("utf8")}catch(err){return{version:null,warning:unusableMinCli(err)}}finally{closeSync(fd)}let value=raw.trim();return VERSION_RE.test(value)?{version:value,warning:null}:{version:null,warning:`${MIN_CLI_FILE} in the fetched repo is not a valid version; continuing without a minimum-version constraint.`}}function unusableMinCli(err){let code=err?.code??(err instanceof Error?err.name:"unknown error");return`${MIN_CLI_FILE} in the fetched repo could not be read (${code}); continuing without a minimum-version constraint.`}async function fetchRemoteSkillsVersion(){let url=`${RAW}/${REPO}/${REPO_BRANCH}/${SKILLS_VERSION_FILE}`,got=await fetchCapped(url,{maxBytes:MAX_BODY_BYTES,ms:FETCH_TIMEOUT_MS}).catch(err=>{throw err instanceof FetchCappedError&&err.kind==="too-large"?new Error(`SKILLS_VERSION too large (over ${MAX_BODY_BYTES} bytes) from ${url}`):err});if(!got.ok)throw new Error(`SKILLS_VERSION fetch failed (${got.status}) from ${url}`);return assertSafeString(got.body.toString("utf8").trim(),SKILLS_VERSION_FILE,VERSION_RE)}import{lstatSync as lstatSync2}from"node:fs";var MANIFEST_FILE="pharn-install.json",MANIFEST_SCHEMA_VERSION=1,MAX_MANIFEST_BYTES=4*1024*1024,MAX_MANIFEST_FILES=2e4,POLICIES=["managed","if-absent"],CAPABILITY_SURFACE="capability",MANIFEST_PATH_RE=/^(?!(?:.*\/)?\.{1,2}(?:\/|$))[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,SURFACE_RE=/^[a-z][a-z0-9-]*$/,SHA256_RE2=/^[0-9a-f]{64}$/,UpstreamManifestError=class extends ManifestValidationError{constructor(message){super(message),this.name="UpstreamManifestError"}};function refuse(detail){return new UpstreamManifestError(`pharn-oss's ${MANIFEST_FILE} ${escapeUnsafe(detail)}; refusing to install. Nothing was written.`)}var show=v=>JSON.stringify(v)??String(v);function readUpstreamManifest(repoDir){let read=readJsonBounded(safeJoin(repoDir,MANIFEST_FILE),MAX_MANIFEST_BYTES);if(read.kind==="absent")return null;if(read.kind==="unusable")throw refuse(read.reason);if(read.kind==="invalid-json")throw refuse("is not valid JSON");let raw=read.value;if(!isPlainObject(raw))throw refuse("is not a JSON object");if(raw.schemaVersion!==MANIFEST_SCHEMA_VERSION)throw new UpstreamManifestError(`pharn-oss's ${MANIFEST_FILE} declares schemaVersion ${escapeUnsafe(show(raw.schemaVersion))}, and this pharn reads only schemaVersion ${MANIFEST_SCHEMA_VERSION}. Upgrade pharn (\`npm install -g @pharn-dev/pharn@latest\`, or run \`npx @pharn-dev/pharn@latest\`) and re-run; with \`--ref main\`, the tip may be ahead of the latest release. Nothing was written.`);let skillsVersion=checkSkillsVersion(repoDir,raw.skillsVersion);checkLayout(repoDir,raw.layout);let capabilities=checkCapabilities(raw.capabilities),files=checkFiles(repoDir,raw.files,capabilities),modelsDefaults=checkModels(raw.models);return checkInstallRoots(raw.installRoots),{skillsVersion,capabilities,files,modelsDefaults}}function checkSkillsVersion(repoDir,value){if(typeof value!="string"||!VERSION_RE.test(value))throw refuse(`has an invalid skillsVersion ${show(value)}`);let tree=readSkillsVersion(repoDir);if(value!==tree)throw refuse(`declares skillsVersion ${value}, but the tree's SKILLS_VERSION is ${tree}`);return value}function checkLayout(repoDir,layout){let pharn=layoutPaths("pharn"),subtrees=isPlainObject(layout)?layout.capabilitySubtrees:null;if(!(isPlainObject(layout)&&layout.name==="pharn"&&layout.marker===PHARN_CONTRACTS_DIR&&isPlainObject(subtrees)&&subtrees.griller===pharn.grillers&&subtrees.lens===pharn.lenses&&Object.keys(subtrees).length===2))throw new UpstreamManifestError(`pharn-oss's ${MANIFEST_FILE} declares a layout this pharn does not know (${escapeUnsafe(show(layout))}). Upgrade pharn (\`npm install -g @pharn-dev/pharn@latest\`) and re-run. Nothing was written.`);if(detectLayout(repoDir)!=="pharn")throw refuse(`declares the pharn layout, but the tree has no ${PHARN_CONTRACTS_DIR}`)}function checkCapabilities(value){if(!Array.isArray(value))throw refuse("has no capabilities array");let pharn=layoutPaths("pharn"),names=new Set;return value.map((entry,i)=>{let at=`capabilities[${i}]`;if(!isPlainObject(entry))throw refuse(`${at} is not an object`);let name=guard(()=>assertSafeString(entry.name,`${at} name`,CAPABILITY_NAME_RE)),role=guard(()=>assertRole(entry.role,`${at} (${name})`));if(names.has(name))throw refuse(`declares capability "${name}" twice`);names.add(name);let dir=`${capabilitySubtree(pharn,role)}/${name}`;if(entry.dir!==dir)throw refuse(`${at} (${name}) has dir ${show(entry.dir)}; a ${role} lives at ${dir}`);return{name,role,applies:checkApplies(entry.applies,at),dir}})}function checkApplies(value,at){if(value==="universal")return value;if(Array.isArray(value)&&value.length>0&&value.every(t=>typeof t=="string"))return[...value];throw refuse(`${at} has a malformed applies ${show(value)}`)}function checkFiles(repoDir,value,capabilities){if(!Array.isArray(value))throw refuse("has no files array");if(value.length>MAX_MANIFEST_FILES)throw refuse(`declares more than ${MAX_MANIFEST_FILES} files`);let byName=new Map(capabilities.map(c=>[c.name,c])),owned=new Set,dests=new Set,files=value.map((entry,i)=>{let at=`files[${i}]`;if(!isPlainObject(entry))throw refuse(`${at} is not an object`);let path=checkPath(repoDir,entry.path,`${at} path`),dest=checkPath(repoDir,entry.dest,`${at} dest`);if(dests.has(dest))throw refuse(`declares the dest ${dest} twice`);if(dests.add(dest),typeof entry.sha256!="string"||!SHA256_RE2.test(entry.sha256))throw refuse(`${at} (${dest}) has a malformed sha256`);let policy=POLICIES.find(p=>p===entry.policy);if(policy===void 0)throw refuse(`${at} (${dest}) has an unknown policy ${show(entry.policy)}`);if(typeof entry.surface!="string"||!SURFACE_RE.test(entry.surface))throw refuse(`${at} (${dest}) has a malformed surface ${show(entry.surface)}`);checkDestBound(dest,path,policy,at);let file={path,dest,surface:entry.surface,policy,sha256:entry.sha256};if(entry.surface===CAPABILITY_SURFACE){let cap=byName.get(entry.capability);if(typeof entry.capability!="string"||cap===void 0)throw refuse(`${at} (${dest}) names no declared capability (${show(entry.capability)})`);if(path!==dest||!dest.startsWith(`${cap.dir}/`))throw refuse(`${at} (${dest}) does not lie inside ${cap.dir}`);owned.add(cap.name),file.capability=cap.name}else{if(entry.capability!==void 0)throw refuse(`${at} (${dest}) names a capability outside the capability surface`);if(capabilityOf(dest)!==null)throw refuse(`${at} (${dest}) lies inside a capability directory but is not a capability file`)}return file});for(let dest of dests)for(let i=dest.indexOf("/");i!==-1;i=dest.indexOf("/",i+1))if(dests.has(dest.slice(0,i)))throw refuse(`declares ${dest.slice(0,i)} as a file and as the directory of ${dest}`);for(let cap of capabilities)if(!owned.has(cap.name))throw refuse(`declares capability "${cap.name}" with no files`);return files}function checkPath(repoDir,value,at){if(typeof value!="string"||!MANIFEST_PATH_RE.test(value))throw refuse(`${at} ${show(value)} is not a safe relative path`);return guard(()=>safeJoin(repoDir,value)),value}function checkDestBound(dest,path,policy,at){if(dest===CLAUDE_SETTINGS_FILE||policy==="if-absent"){if(dest===CLAUDE_SETTINGS_FILE&&path===dest&&policy==="if-absent")return;throw refuse(`${at} (${dest}): only ${CLAUDE_SETTINGS_FILE} may be copied if absent, and only from the same path`)}if(!isPharnOwnedPath(dest))throw refuse(`${at} would write ${dest}, outside the paths pharn installs`)}function checkModels(value){if(!isPlainObject(value))throw refuse("has no models object");if(value.rules!==void 0&&!isPlainObject(value.rules))throw refuse("has a models.rules that is not an object");return value.defaults}function checkInstallRoots(value){if(!(isPlainObject(value)&&["include","exclude","legacy"].every(key=>{let list=value[key];return list===void 0||Array.isArray(list)&&list.every(g=>typeof g=="string")})))throw refuse("has a malformed installRoots")}function guard(fn){try{return fn()}catch(err){throw err instanceof ManifestValidationError?new UpstreamManifestError(`pharn-oss's ${MANIFEST_FILE}: ${err.message}; refusing to install. Nothing was written.`):err}}function verifyUpstreamManifest(repoDir,manifest){for(let file of manifest.files){let abs=safeJoin(repoDir,file.path);if(!lstatSync2(abs,{throwIfNoEntry:!1})?.isFile())throw refuse(`declares ${file.path}, which the tree does not ship as a file`);if(!matchesRawSha256(abs,file.sha256))throw refuse(`declares a sha256 for ${file.path} that its bytes do not match`)}}function manifestCapabilityIndex(m){let pharn=layoutPaths("pharn"),capabilities=[],unknown=[],order=c=>`${c.role==="griller"?0:1}\0${c.name}`,sorted=[...m.capabilities].sort((a,b)=>order(a)<order(b)?-1:order(a)>order(b)?1:0);for(let cap of sorted){if(cap.applies==="universal"){capabilities.push({name:cap.name,role:cap.role,applies:"universal"});continue}try{let tokens=cap.applies.map(t=>assertAppliesToken(t,`capability "${cap.name}"`)),applies=tokens.includes("universal")?"universal":tokens;capabilities.push({name:cap.name,role:cap.role,applies})}catch(err){if(!(err instanceof ManifestValidationError))throw err;unknown.push({name:cap.name,role:cap.role,subtree:capabilitySubtree(pharn,cap.role),reason:err.message})}}return{capabilities,unknown}}function manifestCapabilityFiles(m,cap){return m.files.filter(f=>f.capability===cap.name&&capRole(m,cap.name)===cap.role).map(f=>f.dest).sort()}function capRole(m,name){return m.capabilities.find(c=>c.name===name)?.role}function manifestInstallFiles(repoDir,m,capabilities){let selected=new Set(capabilities.map(c=>`${c.role}:${c.name}`)),expected=new Map;for(let f of m.files)f.policy==="managed"&&(f.capability!==void 0&&!selected.has(`${capRole(m,f.capability)}:${f.capability}`)||expected.set(f.dest,safeJoin(repoDir,f.path)));return expected}function manifestDeclaresSettings(m){return m.files.some(f=>f.dest===CLAUDE_SETTINGS_FILE&&f.policy==="if-absent")}import{existsSync as existsSync3,lstatSync as lstatSync3,readdirSync}from"node:fs";import{join,resolve as resolve2}from"node:path";var PHARN_CONFIG_FILE="pharn.config.json";function*walkFiles(dir,prefix=""){for(let entry of readdirSync(dir,{withFileTypes:!0})){let rel=prefix?`${prefix}/${entry.name}`:entry.name;entry.isDirectory()?yield*walkFiles(resolve2(dir,entry.name),rel):yield rel}}function collectExpectedInstallPaths(params){return collectInstallManifest(params).expected}function absentInstallSurfaces(params){return collectInstallManifest({...params,capabilities:[]}).surfaces.filter(s=>s.files===0).map(({surface,path})=>({surface,path}))}function collectInstallManifest(params){let{repoDir,capabilities,layout}=params,paths=layoutPaths(layout),manifest=layout==="pharn"?readUpstreamManifest(repoDir):null;if(manifest){let expected2=manifestInstallFiles(repoDir,manifest,capabilities);return{expected:expected2,surfaces:accountManifest(expected2,paths)}}let expected=new Map,surfaces=[],add=(rel,repoPath)=>{expected.set(toPosix(rel),repoPath)},account=(surface,path,files)=>{surfaces.push({surface,path,files})},addDir=(relDir,keep,validate)=>{let from=safeJoin(repoDir,relDir);if(!lstatSync3(from,{throwIfNoEntry:!1})?.isDirectory())return 0;let added=0;for(let rel of walkFiles(from))keep&&!keep(rel)||(validate?.(rel),add(join(relDir,rel),resolve2(from,rel)),added+=1);return added},copyNameFloor=dir=>rel=>{let label=`${dir}/${rel}`;assertSafeString(rel,label,COPY_FILENAME_RE)};for(let cap of capabilities){let subtree=capabilitySubtree(paths,cap.role);addDir(`${subtree}/${cap.name}`)}account("commands",CLAUDE_COMMANDS_DIR,addDir(CLAUDE_COMMANDS_DIR,isProductCommandFile,copyNameFloor(CLAUDE_COMMANDS_DIR))),account("hooks",CLAUDE_HOOKS_DIR,addDir(CLAUDE_HOOKS_DIR,isInstalledHookFile,copyNameFloor(CLAUDE_HOOKS_DIR))),addDir(CLAUDE_AGENTS_DIR,isProductAgentFile,copyNameFloor(CLAUDE_AGENTS_DIR));let layoutDocs=paths.docs;resolveTrustedDocs(repoDir,layout).forEach((doc,i)=>{let from=safeJoin(repoDir,doc),shipped=lstatSync3(from,{throwIfNoEntry:!1})?.isFile()===!0;shipped&&add(doc,from),account("trusted-doc",shipped?doc:layoutDocs[i],shipped?1:0)});let licenseShipped=!1,licenseFrom=safeJoin(repoDir,paths.license.from);lstatSync3(licenseFrom,{throwIfNoEntry:!1})?.isFile()&&(add(paths.license.to,licenseFrom),licenseShipped=!0),account("license",paths.license.from,licenseShipped?1:0);let featuresRel=resolveFeaturesReadme(repoDir,layout),featuresShipped=!1,featuresFrom=safeJoin(repoDir,featuresRel);lstatSync3(featuresFrom,{throwIfNoEntry:!1})?.isFile()&&(add(featuresRel,featuresFrom),featuresShipped=!0),account("features-readme",featuresShipped?featuresRel:paths.featuresReadme,featuresShipped?1:0),account("contracts",paths.contracts,addDir(paths.contracts));let coreFiles=addDir(paths.core);layout==="pharn"&&account("core",paths.core,coreFiles);let floorFiles=addDir(paths.floor,rel=>!/\.test\.(mjs|cjs)$/.test(rel)&&!isFloorTestFixturePath(rel));return account("floor",paths.floor,floorFiles),{expected,surfaces}}function accountManifest(expected,paths){let dests=[...expected.keys()],under=dir=>dests.filter(d=>d.startsWith(`${dir}/`)).length,one=dest=>expected.has(dest)?1:0;return[{surface:"commands",path:CLAUDE_COMMANDS_DIR,files:under(CLAUDE_COMMANDS_DIR)},{surface:"hooks",path:CLAUDE_HOOKS_DIR,files:under(CLAUDE_HOOKS_DIR)},...paths.docs.map(doc=>({surface:"trusted-doc",path:doc,files:one(doc)})),{surface:"license",path:paths.license.from,files:one(paths.license.to)},{surface:"features-readme",path:paths.featuresReadme,files:one(paths.featuresReadme)},{surface:"contracts",path:paths.contracts,files:under(paths.contracts)},{surface:"core",path:paths.core,files:under(paths.core)},{surface:"floor",path:paths.floor,files:under(paths.floor)}]}function isFloorTestFixturePath(rel){return FLOOR_TEST_FIXTURES_DIRS.some(dir=>rel===dir||rel.startsWith(`${dir}/`))}function conflictingWriteTargets(params){let{repoDir,projectRoot,capabilities,layout}=params,expected=params.expected??collectExpectedInstallPaths({repoDir,capabilities,layout}),candidates=new Set(expected.keys());candidates.add(PHARN_CONFIG_FILE);let conflicts=[];for(let rel of candidates)existsSync3(safeJoin(projectRoot,rel))&&conflicts.push(rel);return conflicts.sort()}function capabilityCloneFiles(repoDir,paths,capability){let manifest=paths.layout==="pharn"?readUpstreamManifest(repoDir):null;if(manifest)return manifestCapabilityFiles(manifest,capability);let relDir=`${capabilitySubtree(paths,capability.role)}/${capability.name}`,from=safeJoin(repoDir,relDir);return lstatSync3(from,{throwIfNoEntry:!1})?.isDirectory()?[...walkFiles(from)].map(rel=>`${relDir}/${rel}`).sort():[]}import{log}from"@clack/prompts";var VERSION_DISPLAY_MAX=64;function majorMinor(version){if(typeof version!="string"||!VERSION_RE.test(version))return null;let[major,minor]=version.split(".");return[Number(major),Number(minor)]}function olderCliWarning(recorded,running){let theirs=majorMinor(recorded),ours=majorMinor(running);if(theirs===null||ours===null||!(ours[0]<theirs[0]||ours[0]===theirs[0]&&ours[1]<theirs[1]))return null;let shown=terminalSafe(recorded,{max:VERSION_DISPLAY_MAX});return`${CONFIG_FILENAME} was written by pharn ${shown}; this is pharn ${terminalSafe(running,{max:VERSION_DISPLAY_MAX})}. Upgrade pharn (\`npm install -g @pharn-dev/pharn@latest\`, or run \`npx @pharn-dev/pharn@latest\`) so teammates on different versions don't undo each other's changes. Continuing.`}function warnIfOlderCli(config,opts={}){let warning=olderCliWarning(config?.pharnVersion,PHARN_VERSION);warning!==null&&(opts.json?logErrorPlain(warning):log.warn(warning,{output:process.stderr}))}import{lstatSync as lstatSync4}from"node:fs";function parseIgnorePattern(raw){let line=(raw.endsWith("\r")?raw.slice(0,-1):raw).replace(/[ \t]+$/,"");if(line===""||line.startsWith("#"))return null;let p=line,negated=p.startsWith("!");negated&&(p=p.slice(1));let anyDepth=!1,anchored=!1;p.startsWith("**/")?(anyDepth=!0,p=p.slice(3)):p.startsWith("/")&&(anchored=!0,p=p.slice(1));let suffix=/(\/\*\*|\/\*|\/)$/.exec(p)?.[0]??"";p=p.slice(0,p.length-suffix.length);let floating=anyDepth||!anchored&&suffix!=="/*"&&suffix!=="/**"&&!p.includes("/");return{negated,core:p,floating,suffix}}var UTF8_BOM="\xEF\xBB\xBF";function ignoreFileLines(bytes){let text=bytes.toString("latin1");return(text.startsWith(UTF8_BOM)?text.slice(UTF8_BOM.length):text).split(`
|
|
2
|
-
`)}function ignorePatterns(bytes){return ignoreFileLines(bytes).map(parseIgnorePattern).filter(p=>p!==null)}function ignoreAddition(old,entries,comment){if(entries.length===0)return Buffer.alloc(0);let bytes=old??Buffer.alloc(0),text=bytes.toString("latin1"),firstLf=text.indexOf(`
|
|
3
|
-
`),eol=firstLf>0&&text[firstLf-1]==="\r"?`\r
|
|
4
|
-
`:`
|
|
5
|
-
`,hasComment=ignoreFileLines(bytes).some(l=>l.replace(/[ \t\r]+$/,"")===comment),parts=[];text.length>0&&!text.endsWith(`
|
|
6
|
-
`)&&parts.push(eol),hasComment||parts.push(comment+eol);for(let entry of entries)parts.push(entry+eol);return Buffer.from(parts.join(""),"latin1")}function readIgnoreFile(projectRoot,name){let target=safeJoin(projectRoot,name),isLink;try{isLink=lstatSync4(target).isSymbolicLink()}catch(err){return err.code==="ENOENT"?{kind:"absent"}:{kind:"refused",reason:"unreadable"}}if(isLink)return{kind:"refused",reason:"symlink"};let read=readBoundedFile(target);return read.kind==="absent"?{kind:"refused",reason:"unreadable"}:read.kind==="unusable"?{kind:"refused",reason:read.code==="not-a-file"||read.code==="EISDIR"?"not-a-file":"unreadable"}:{kind:"ok",bytes:read.bytes}}async function writeIgnoreFile(projectRoot,name,old,append){try{return await writeFileAtomic(safeJoin(projectRoot,name),Buffer.concat([old??Buffer.alloc(0),append])),null}catch(err){let code=err.code;return typeof code=="string"&&/^[A-Z0-9_]{1,32}$/.test(code)?code:"EUNKNOWN"}}import{lstatSync as lstatSync5}from"node:fs";function findSymlinkComponent(base,rel){let current="";for(let segment of toPosix(rel).split("/"))if(segment&&(current=current?`${current}/${segment}`:segment,lstatSync5(safeJoin(base,current),{throwIfNoEntry:!1})?.isSymbolicLink()))return current;return null}function findSymlinkComponentOr(base,rel,unwalkable){try{return findSymlinkComponent(base,rel)}catch{return unwalkable}}function findTypeCollision(base,rel){let segments=toPosix(rel).split("/").filter(Boolean),current="";for(let[i,segment]of segments.entries()){current=current?`${current}/${segment}`:segment;let stat=lstatSync5(safeJoin(base,current),{throwIfNoEntry:!1});if(stat===void 0)return null;if(i===segments.length-1?!stat.isFile():!stat.isDirectory())return current}return null}var FATAL_SIGNALS=["SIGINT","SIGTERM"],SIGNAL_NUMBER={SIGINT:2,SIGTERM:15},cleanups=new Set,installed=!1;function onFatalSignal(cleanup){install();let entry=()=>cleanup();return cleanups.add(entry),()=>{cleanups.delete(entry)}}function install(){if(!installed){installed=!0;for(let sig of FATAL_SIGNALS)process.on(sig,()=>die(sig))}}function die(sig){let pending=[...cleanups].reverse();cleanups.clear();for(let cleanup of pending)try{cleanup()}catch{}process.removeAllListeners(sig);try{process.kill(process.pid,sig)}catch{process.exit(128+SIGNAL_NUMBER[sig])}}export{ignorePatterns,ignoreAddition,readIgnoreFile,writeIgnoreFile,detectLayout,layoutPaths,capabilitySubtree,configLayout,flatDeprecationLines,resolveFeaturesReadme,resolveTrustedDocs,contentHash,RECORDS_FILE,MODELS_RECORD_KEY,modelsRecordHash,RECORDS_SCHEMA_VERSION,recordsPath,readRecords,recordsBaseline,writeRecords,carriedSettingsRecord,buildRecords,mergeRecords,recordsUnderCapabilities,isProductCommandFile,isInstalledHookFile,SURFACE_DIRS,CAPABILITY_SUBTREES,capabilityOf,isInstallRootPath,readSkillsVersion,readMinCli,fetchRemoteSkillsVersion,UpstreamManifestError,readUpstreamManifest,verifyUpstreamManifest,manifestCapabilityIndex,manifestDeclaresSettings,PHARN_CONFIG_FILE,collectExpectedInstallPaths,absentInstallSurfaces,conflictingWriteTargets,capabilityCloneFiles,findSymlinkComponent,findSymlinkComponentOr,findTypeCollision,warnIfOlderCli,onFatalSignal};
|
package/dist/chunk-KKY6HERY.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{readDiskState}from"./chunk-KZCUUHJT.js";import{capabilityOf,findSymlinkComponent,isInstallRootPath}from"./chunk-FUQURK5N.js";import{CLAUDE_SETTINGS_FILE}from"./chunk-SQLIXTIY.js";import{color_default}from"./chunk-LF4PFADC.js";import{isPlainObject,safeJoin}from"./chunk-L3QGAX2K.js";import{escapeUnsafe,terminalSafe}from"./chunk-A77BLCF4.js";var MAX_ORPHANS_PER_GROUP=20;function findOrphans(params){let{projectRoot,records,expected}=params;if(records===null)return{orphans:[],records:{}};let key=cap=>`${cap.role}:${cap.name}`,owned=new Set(params.capabilities.map(key)),frozen=new Set(params.frozen.map(key)),orphans=[],carried={};for(let[rel,recorded]of Object.entries(records)){if(expected.has(rel)||!isInstallRootPath(rel))continue;let cap=capabilityOf(rel);if(cap!==null&&(frozen.has(cap)||!owned.has(cap)))continue;let disk=readDiskState(projectRoot,rel);disk.kind!=="absent"&&(carried[rel]=recorded,disk.kind==="unreadable"?orphans.push({path:rel,state:"unreadable",reason:disk.reason}):orphans.push({path:rel,state:disk.hash===recorded?"unchanged":"edited"}))}return orphans.sort((a,b)=>+(a.path>b.path)-+(a.path<b.path)),{orphans,records:carried}}var GROUPS=[{state:"unchanged",heading:"UNCHANGED \u2014 unchanged since pharn wrote it"},{state:"edited",heading:"EDITED \u2014 changed since pharn wrote it \u2014 review before deleting"},{state:"unreadable",heading:"UNREADABLE \u2014 not a readable regular file; inspect by hand"}];function orphanNoteLines(orphans){if(orphans.length===0)return null;let lines=[" Upstream no longer ships these files pharn installed. pharn never deletes"," them, and keeps listing each one until it is gone.",""],capped=!1;for(let{state,heading}of GROUPS){let group=orphans.filter(o=>o.state===state);if(group.length!==0){lines.push(` ${heading}`);for(let o of group.slice(0,MAX_ORPHANS_PER_GROUP)){let path=terminalSafe(o.path);lines.push(o.reason!==void 0?` ${path} \u2014 ${terminalSafe(o.reason)}`:` ${path}`)}group.length>MAX_ORPHANS_PER_GROUP&&(capped=!0,lines.push(` \u2026 and ${group.length-MAX_ORPHANS_PER_GROUP} more`)),lines.push("")}}return lines.push(color_default.dim(" Delete the ones you no longer need by hand (e.g. `git rm <path>`).")),capped&&lines.push(color_default.dim(" The full list: `pharn status --json` (`orphans`).")),lines}import{closeSync,constants,fstatSync,openSync,readSync}from"node:fs";import{dirname}from"node:path";var LOCAL_SETTINGS_FILE=".claude/settings.local.json",MAX_SETTINGS_BYTES=256*1024,OPEN_FLAGS=constants.O_RDONLY|(constants.O_NONBLOCK??0);function readSettings(base,rel){let linked;try{linked=findSymlinkComponent(base,dirname(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=openSync(safeJoin(base,rel),OPEN_FLAGS)}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=fstatSync(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=readSync(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{closeSync(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),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),local=readSettings(projectRoot,LOCAL_SETTINGS_FILE);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);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 countSkipped(settings){if(!("hooks"in settings))return 0;if(!isPlainObject(settings.hooks))return 1;let skipped=0;for(let groups of Object.values(settings.hooks)){if(!Array.isArray(groups)){skipped++;continue}for(let group of groups){if(!isPlainObject(group)||!Array.isArray(group.hooks)){skipped++;continue}for(let hook of group.hooks)(!isPlainObject(hook)||typeof hook.command!="string")&&skipped++}}return skipped}function upstreamSettingsSummary(repoDir){let read=readSettings(repoDir,CLAUDE_SETTINGS_FILE);return read.kind==="absent"?{status:"unreadable",reason:"it does not exist"}:read.kind==="unreadable"?{status:"unreadable",reason:read.reason}:isPlainObject(read.value)?{status:"ok",hooks:hookEntries(read.value)??[],otherKeys:Object.keys(read.value).filter(k=>k!=="hooks"&&k!=="_comment").sort(),skipped:countSkipped(read.value)}:{status:"ok",hooks:[],otherKeys:[],skipped:0}}var MAX_KEY=100,MAX_KEYS=20;function displayKey(key){return escapeUnsafe(key.length>MAX_KEY?`${key.slice(0,MAX_KEY)}\u2026`:key)}function freshSettingsHookLines(summary){let review=" Claude Code runs these commands; review `.claude/settings.json`.";if(summary.status==="unreadable")return[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream, but could not list its hooks (${escapeUnsafe(summary.reason)}).`,review];let lines=summary.hooks.length>0?[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream. It wires ${summary.hooks.length} hook(s):`,...summary.hooks.map(e=>` ${displayHook(e)}`)]:[` Wrote ${CLAUDE_SETTINGS_FILE} from upstream. It wires no hooks.`];if(summary.skipped>0&&lines.push(` ${summary.skipped} other hook entr${summary.skipped===1?"y":"ies"} not shown \u2014 review the file.`),summary.otherKeys.length>0){let shown=summary.otherKeys.slice(0,MAX_KEYS).map(displayKey),more=summary.otherKeys.length-shown.length;lines.push(` It also sets: ${shown.join(", ")}${more>0?` and ${more} more`:""}`)}return[...lines,review]}export{findOrphans,orphanNoteLines,diffHookWiring,hooksReferencing,hookWiringFails,displayHook,hookWiringLines,preservedSettingsHookLines,upstreamSettingsSummary,freshSettingsHookLines};
|