@punks/cli 6.5.1 → 6.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +6 -6
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -278,7 +278,7 @@ ${colorRail2({environment,headingTone:"accent",rail:reflowRail(guide,environment
|
|
|
278
278
|
`);return outcome.exitCode}if(mode==="json"){let rendered;if(outcome.kind==="expected-failure"){rendered=renderJsonFailure(outcome.failure)}else if(outcome.jsonPayload===undefined){rendered=renderJsonResult(outcome.result)}else{rendered=`${JSON.stringify(outcome.jsonPayload,null,2)}
|
|
279
279
|
`}writeStdout(rendered);return outcome.kind==="expected-failure"||resultFailed(outcome.result)?1:0}if(outcome.kind==="expected-failure"){writeStdout(renderExpectedFailure(outcome.failure,humanEnvironment));return 1}writeStdout(renderOperationResult(outcome.result,humanEnvironment));return resultFailed(outcome.result)?1:0};import{existsSync as existsSync7,readFileSync as readFileSync7}from"node:fs";import path11 from"node:path";import{homedir as homedir2}from"node:os";import{accessSync,constants as constants2,existsSync as existsSync3,readFileSync as readFileSync3}from"node:fs";import{homedir}from"node:os";import path6 from"node:path";var toolCatalog=[{ensureCommands:[["agent-browser","install"]],id:"agent-browser",kind:"npm-global",latestInstallTarget:"agent-browser@latest",packageName:"agent-browser",requiredBins:["node"],skipEnsureCommandsIfAnyCommandExists:[{env:"AGENT_BROWSER_EXECUTABLE_PATH"},"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","google-chrome","google-chrome-stable","chromium","chromium-browser","brave-browser","brave-browser-stable","C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"]},{ensureCommands:[],id:"debug-agent",kind:"npm-global",latestInstallTarget:"debug-agent@latest",packageName:"debug-agent",requiredBins:["node"]},{ensureCommands:[],id:"clawpatch",kind:"npm-global",latestInstallTarget:"clawpatch@latest",packageName:"clawpatch",requiredBins:["node"]},{ensureCommands:[],id:"opensrc",kind:"npm-global",latestInstallTarget:"opensrc@latest",minimumVersion:"0.7.2",packageName:"opensrc@^0.7.2",requiredBins:["node"],versionCommand:["opensrc","--version"]},{ensureCommands:[],id:"portless",kind:"npm-global",latestInstallTarget:"portless@latest",packageName:"portless",requiredBins:["node"]},{ensureCommands:[],id:"skills",kind:"npm-global",latestInstallTarget:"skills@latest",packageName:"skills",requiredBins:["node"]},{id:"earshot",installArgs:["--torch-backend","cpu"],kind:"uv",pin:"591fa3e028032e6dce56620a20e932e35667e8d8",requiredBins:["uv"],requirement:"earshot[mcp] @ git+https://github.com/Leonxlnx/earshot"},{id:"uv",kind:"check-only"},{id:"ffmpeg",kind:"check-only"},{id:"ffprobe",kind:"check-only"},{id:"python3",kind:"check-only",minimumVersion:"3.11",versionCommand:["python3","--version"]},{id:"node",kind:"check-only",minimumVersion:"22",versionCommand:["node","--version"]}];import{spawnSync}from"node:child_process";var childEnvironment=(baseEnvironment,overrides)=>{const env={};for(const[key,value3]of Object.entries(baseEnvironment??process.env)){if(value3!==undefined){env[key]=value3}}for(const[key,value3]of Object.entries(overrides??{})){if(value3===undefined){Reflect.deleteProperty(env,key)}else{env[key]=value3}}return env};var processOutputMaxBuffer=256*1024*1024;var nodeProcess={capture:(command,args2,options3)=>{const result3=spawnSync(command,args2,{cwd:options3?.cwd,encoding:"utf-8",env:childEnvironment(options3?.baseEnvironment,options3?.env),maxBuffer:processOutputMaxBuffer,stdio:["ignore","pipe","pipe"]});return{...result3.error===undefined?{}:{error:result3.error},signal:result3.signal,status:result3.status,stderr:result3.stderr,stdout:result3.stdout}},execute:(command,args2,options3)=>{const result3=nodeProcess.capture(command,args2,options3);if(result3.status!==0){throw Object.assign(new Error(`Process exited with status ${result3.status??"unknown"}.`),{cause:result3.error,...result3})}}};var redactProcessDiagnostic=(value3)=>value3.replaceAll(/(?<prefix>(?:token|password|secret|authorization|_authToken)\s*[=:]\s*)(?:Bearer\s+)?[^\s"']+/giu,"$<prefix>[redacted]").replaceAll(/(?<protocol>https?:\/\/)[^\s/@]+:[^\s/@]+@/giu,"$<protocol>[redacted]@").slice(0,8192);import{existsSync,readFileSync}from"node:fs";import path4 from"node:path";var repositoryManagers=["azure-devops","bitbucket","github","gitlab"];var backlogProviders=["azure-devops","github","linear","monday"];var repositoryManagerTools={"azure-devops":["az"],bitbucket:[],github:["gh"],gitlab:["glab"]};var providerCliTools=[...new Set(Object.values(repositoryManagerTools).flat())];var requiredToolsForRepositoryManager=(repositoryManager)=>repositoryManagerTools[repositoryManager];var isRepositoryManager=(value3)=>typeof value3==="string"&&repositoryManagers.includes(value3);var isBacklogProvider=(value3)=>typeof value3==="string"&&backlogProviders.includes(value3);var isAssetProvider=(value3)=>isBacklogProvider(value3)||isRepositoryManager(value3);var remoteHosts=[["github.com","github"],["gitlab.com","gitlab"],["dev.azure.com","azure-devops"],["visualstudio.com","azure-devops"],["bitbucket.org","bitbucket"]];var inferRepositoryManager=(rootDirectory)=>{const configPath=path4.join(rootDirectory,".git/config");if(!existsSync(configPath)){return}const content=readFileSync(configPath,"utf-8");return remoteHosts.find(([host])=>content.includes(host))?.[1]};import{existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";import path5 from"node:path";var uvToolDirectory=(runtime)=>{const configured=runtime.env?.UV_TOOL_DIR;if(configured!==undefined&&configured.length>0){return configured}const reported=runtime.execFileOutput?.("uv",["tool","dir"]).trim();return reported===undefined||reported.length===0?undefined:reported};var readUvToolRev=(runtime,toolName)=>{const directory3=uvToolDirectory(runtime);if(directory3===undefined){return}const receipt=path5.join(directory3,toolName,"uv-receipt.toml");if(!existsSync2(receipt)){return}return/\bgit\s*=\s*"[^"]*\?rev=(?<rev>[^"&#]+)"/u.exec(readFileSync2(receipt,"utf-8"))?.groups?.rev};var installUvTool=(runtime,{installArgs,pin,requirement},options3)=>{runtime.execFile("uv",["tool","install",...installArgs,`${requirement}@${pin}`],options3)};class ToolManagementFailure extends TaggedErrorClass()("@punks/cli/integrations/tool-management/ToolManagementFailure",{cause:Defect(),message:String4,operation:Literal2("ensure-required-tool"),subprocess:optional(Struct({command:String4,exitCode:NullOr(Finite),phase:Literal2("bootstrap"),signal:NullOr(String4),stderr:String4,stdout:String4}))}){}var toolManagementFailure=(operation,message)=>new ToolManagementFailure({cause:new Error(message),message,operation});var commandExistsOnPath=(command,env={},platform=process.platform)=>{const pathValue=env.PATH??env.Path;if(pathValue===undefined||pathValue.length===0){return false}const isWindows=platform==="win32";const pathSeparator=isWindows?";":":";const pathEntries=pathValue.split(pathSeparator).filter((entry)=>entry.length>0);const pathExtensions=isWindows?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((extension)=>extension.length>0):[""];const commandExtensions=isWindows&&path6.extname(command).length===0?pathExtensions:[""];const hasPathSegment=command.includes("/")||command.includes("\\");const candidates=(hasPathSegment?[""]:pathEntries).flatMap((entry)=>commandExtensions.map((extension)=>hasPathSegment?`${command}${extension}`:path6.join(entry,`${command}${extension}`)));return candidates.some((candidate)=>{try{accessSync(candidate,isWindows?constants2.F_OK:constants2.X_OK);return true}catch{return false}})};var runToolCommand=(environment,command,args2,options3)=>{const result3=nodeProcess.capture(command,args2,{...options3?.cwd===undefined?{}:{cwd:options3.cwd},baseEnvironment:environment});const stdout=redactProcessDiagnostic(result3.stdout??"");const stderr=redactProcessDiagnostic(result3.stderr??"");if(options3?.stdio==="inherit"){process.stdout.write(stdout);process.stderr.write(stderr)}if(result3.status!==0||result3.error!==undefined){const commandLabel=redactProcessDiagnostic([command,...args2].join(" "));const detail=stderr||stdout||redactProcessDiagnostic(result3.error instanceof Error?result3.error.message:"Process did not complete.");const message=redactProcessDiagnostic(`Tool bootstrap failed: ${commandLabel} (exit ${result3.status??"unknown"}, signal ${result3.signal??"none"}): ${detail}`);throw new ToolManagementFailure({cause:new Error(message),message,operation:"ensure-required-tool",subprocess:{command:commandLabel,exitCode:result3.status,phase:"bootstrap",signal:result3.signal??null,stderr,stdout}})}return result3.stdout};var makeToolCommandRuntime=(environment)=>({commandExists:(command)=>commandExistsOnPath(command,environment),cwd:homedir(),env:environment,execFile:(command,args2,options3)=>{runToolCommand(environment,command,args2,options3)},execFileOutput:(command,args2,options3)=>runToolCommand(environment,command,args2,options3)});var defaultToolBootstrapOptions={mode:"repair",stdio:"inherit"};var detectGlobalPackageManager=(runtime)=>{if(runtime.commandExists("bun")){return"bun"}if(runtime.commandExists("pnpm")){return"pnpm"}if(runtime.commandExists("npm")){return"npm"}return null};var globalInstallCommandFor=(packageManager,packageName)=>{switch(packageManager){case"bun":{return["bun","add","-g",packageName]}case"pnpm":{return["pnpm","add","-g",packageName]}case"npm":{return["npm","install","-g",packageName]}default:{return packageManager}}};var parseVersionParts=(value3)=>{const match8=/\d+(?:\.\d+){0,2}/u.exec(value3);if(match8===null){return null}const[matchedVersion]=match8;return matchedVersion===undefined?null:matchedVersion.split(".").map((part)=>Math.trunc(Number(part)))};var compareVersions=(actual,minimum)=>{const length=Math.max(actual.length,minimum.length);for(let index=0;index<length;index+=1){const actualPart=actual[index]??0;const minimumPart=minimum[index]??0;if(actualPart>minimumPart){return 1}if(actualPart<minimumPart){return-1}}return 0};var versionBelowMinimum=(tool,runtime,cwd)=>{if(tool.minimumVersion===undefined||tool.versionCommand===undefined){return}const[command,...args2]=tool.versionCommand;if(command===undefined||runtime.execFileOutput===undefined){return}const actual=parseVersionParts(runtime.execFileOutput(command,args2,{cwd}));const minimum=parseVersionParts(tool.minimumVersion);if(actual===null||minimum===null){throw toolManagementFailure("ensure-required-tool",`Cannot verify required tool version from \`${tool.versionCommand.join(" ")}\`.`)}return compareVersions(actual,minimum)>=0?undefined:actual.join(".")};var commandCandidateValue=(candidate,env)=>{if(typeof candidate==="string"){return candidate}const value3=env[candidate.env];return value3===undefined||value3.length===0?null:value3};var shouldSkipEnsureCommands=(tool,runtime)=>tool.skipEnsureCommandsIfAnyCommandExists?.some((candidate)=>{const command=commandCandidateValue(candidate,runtime.env??{});return command!==null&&runtime.commandExists(command)})??false;var toolCatalogById=new Map(toolCatalog.map((tool)=>[tool.id,tool]));var resolveTool=(toolId)=>toolCatalogById.get(toolId)??(providerCliTools.includes(toolId)?{id:toolId,kind:"check-only"}:undefined);var assertRequiredBins=(tool,runtime)=>{const missingPrerequisites=tool.requiredBins.filter((command)=>!runtime.commandExists(command));if(missingPrerequisites.length>0){throw toolManagementFailure("ensure-required-tool",`Cannot install required tool \`${tool.id}\` because ${missingPrerequisites.join(", ")} is not available on PATH.`)}};var installNpmGlobalTool=({cwd,installTarget,runtime,stdio,tool})=>{const packageManager=detectGlobalPackageManager(runtime);if(packageManager===null){throw toolManagementFailure("ensure-required-tool","Cannot install required tools because no supported global package manager was found on PATH. Install Bun, pnpm, or npm first.")}const[command,...args2]=globalInstallCommandFor(packageManager,installTarget);runtime.execFile(command,args2,{cwd,stdio});if(!runtime.commandExists(tool.id)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${tool.id}\`, but the binary is still not available on PATH afterwards.`)}const found=versionBelowMinimum(tool,runtime,cwd);if(found!==undefined){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${tool.id}\`, but the installed version ${found} does not satisfy ${tool.minimumVersion}.`)}};var checkTool=(tool,{cwd,runtime})=>{if(!runtime.commandExists(tool.id)){throw toolManagementFailure("ensure-required-tool",`Required external tool \`${tool.id}\` is not available on PATH. Install it, then rerun \`hi tools ensure\`.`)}const found=versionBelowMinimum(tool,runtime,cwd);if(found!==undefined){throw toolManagementFailure("ensure-required-tool",`Required external tool \`${tool.id}\` must be at least ${tool.minimumVersion}, but found ${found}. Upgrade it, then rerun \`hi tools ensure\`.`)}return"already-present"};var ensureNpmGlobalTool=(tool,{cwd,options:options3,runtime})=>{assertRequiredBins(tool,runtime);const alreadyPresent=runtime.commandExists(tool.id)&&versionBelowMinimum(tool,runtime,cwd)===undefined;const refreshLatest=options3.mode==="refresh-latest";if(!alreadyPresent||refreshLatest){installNpmGlobalTool({cwd,installTarget:refreshLatest?tool.latestInstallTarget:tool.packageName,runtime,stdio:options3.stdio,tool})}if(!shouldSkipEnsureCommands(tool,runtime)){for(const[command,...args2]of tool.ensureCommands){runtime.execFile(command,args2,{cwd,stdio:options3.stdio})}}return alreadyPresent&&!refreshLatest?"already-present":"installed"};var ensureUvTool=(tool,{cwd,options:options3,runtime})=>{assertRequiredBins(tool,runtime);if(readUvToolRev(runtime,tool.id)===tool.pin){return"already-present"}installUvTool(runtime,tool,{cwd,stdio:options3.stdio});return"installed"};var ensureTool=(tool,context3)=>{switch(tool.kind){case"check-only":{return checkTool(tool,context3)}case"npm-global":{return ensureNpmGlobalTool(tool,context3)}case"uv":{return ensureUvTool(tool,context3)}default:{return tool}}};var ensureToolsInstalled=(toolIds,runtime,options3=defaultToolBootstrapOptions)=>{const context3={cwd:runtime.cwd??homedir(),options:options3,runtime};return toolIds.map((toolId)=>{const tool=resolveTool(toolId);if(tool===undefined){throw toolManagementFailure("ensure-required-tool",`Unknown required tool \`${toolId}\`; the CLI has no install metadata for it.`)}return{status:ensureTool(tool,context3),toolId}})};var errorMessage=(cause)=>redactProcessDiagnostic(cause instanceof Error?cause.message:String(cause));var errorStack=(cause)=>redactProcessDiagnostic(cause instanceof Error?cause.stack??cause.message:String(cause));var ensureToolsInstalledBestEffort=(toolIds,runtime,options3=defaultToolBootstrapOptions)=>toolIds.flatMap((toolId)=>{try{return ensureToolsInstalled([toolId],runtime,options3)}catch(error2){return[{errorMessage:errorMessage(error2),errorStack:errorStack(error2),status:"failed",toolId}]}});var readPackageForInstallation=(rootDirectory)=>{try{const value3=JSON.parse(readFileSync3(path6.join(rootDirectory,"package.json"),"utf-8"));return typeof value3==="object"&&value3!==null&&!Array.isArray(value3)?Object.fromEntries(Object.entries(value3)):null}catch{return null}};var usesClassicYarn=(rootDirectory,configuredManager,configuredVersion)=>{if(configuredManager==="yarn"&&configuredVersion!==null){return/^1(?:\.|$)/u.test(configuredVersion)}if(configuredManager!==null){return false}const yarnLockfile=path6.join(rootDirectory,"yarn.lock");return existsSync3(yarnLockfile)&&/(?:^|\n)# yarn lockfile v1(?:\n|$)/u.test(readFileSync3(yarnLockfile,"utf-8"))};var dependencyInstallationCommand=(rootDirectory)=>{const rootManifest=readPackageForInstallation(rootDirectory);const configuredValue=typeof rootManifest?.packageManager==="string"?rootManifest.packageManager:null;const configuredMatch=configuredValue===null?null:/^(?<manager>[^@]+)(?:@(?<version>.+))?$/u.exec(configuredValue);const configured=configuredMatch?.groups?.manager??null;const configuredVersion=configuredMatch?.groups?.version??null;const manager=configured??[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["package-lock.json","npm"],["yarn.lock","yarn"]].find(([lockfile])=>existsSync3(path6.join(rootDirectory,lockfile)))?.[1]??null;switch(manager){case null:{return null}case"bun":{return["bun",["install","--ignore-scripts"]]}case"npm":{return["npm",["install","--ignore-scripts"]]}case"pnpm":{return["pnpm",["install","--ignore-scripts"]]}case"yarn":{if(usesClassicYarn(rootDirectory,configured,configuredVersion)){return["yarn",["install","--ignore-scripts","--non-interactive"]]}return["yarn",["install","--mode=skip-build"]]}default:{return null}}};var runtimeReceiptName=".hi-runtime.json";var npmInstallTimeoutMs=10*60*1000;var nodeVersionTimeoutMs=30*1000;var outputLimit=1024*1024;var platformLayer=mergeAll2(layer5,layer7,layer9);var processLayer=layer3.pipe(provide2(platformLayer));var platformFailure=(error2)=>error2.cause instanceof Error?error2.cause.message:error2.message;var definedEnvironment=(env)=>Object.fromEntries(Object.entries(env).flatMap(([key,value3])=>value3===undefined?[]:[[key,value3]]));var sweepGroup=(pid)=>process.platform==="win32"?void_3:ignore2(try_3(()=>{process.kill(-pid,"SIGKILL")}));var appendTail=(current,chunk)=>{const next=current+chunk;return next.length>outputLimit?next.slice(-outputLimit):next};var outputTail=(output)=>output.pipe(decodeText(),runFold2(()=>"",appendTail));var runCommand=(request)=>gen2(function*runToCompletion(){const child=yield*exports_ChildProcess.make(request.command,request.args,{cwd:request.cwd,env:definedEnvironment(request.env),killSignal:"SIGKILL",shell:request.shell??false,stdin:"ignore"});yield*addFinalizer3(()=>sweepGroup(child.pid));const[stdout,stderr,exitCode]=yield*all2([outputTail(child.stdout),outputTail(child.stderr),child.exitCode.pipe(map6((code)=>code),orElseSucceed2(()=>null))],{concurrency:"unbounded"});return{exitCode,stderr,stdout,timedOut:false}}).pipe(scoped2,catchTag2("PlatformError",(failure)=>succeed6({error:platformFailure(failure),exitCode:null,stderr:"",stdout:"",timedOut:false})),timeoutOption2(request.timeoutMs),map6(getOrElse(()=>({exitCode:null,stderr:"",stdout:"",timedOut:true}))),provide4(processLayer));var commandFailureDetail=(label,result3,timeoutMs)=>{if(result3.timedOut){return`${label} timed out after ${String(Math.round(timeoutMs/1000))}s`}const output=(result3.error??(result3.stderr.trim()||result3.stdout.trim())).split(`
|
|
280
280
|
`);const detail=output.filter((line)=>line.trim().length>0).slice(-3).join(" | ");const exit3=result3.exitCode===null?"did not run":`exit ${String(result3.exitCode)}`;return redactProcessDiagnostic(`${label} ${exit3}${detail.length>0?`: ${detail}`:""}`).slice(0,500)};var nonEmpty=(value3)=>value3===undefined||value3.length===0?undefined:value3;var dataDirectory=(path7,env,spec)=>{const dataHome=nonEmpty(env.XDG_DATA_HOME)??path7.join(nonEmpty(env.HOME)??nonEmpty(env.USERPROFILE)??homedir2(),".local","share");return path7.join(dataHome,"hi-tools",spec.id,spec.version)};var lockDigest=(spec)=>Crypto.use((crypto)=>crypto.digest("SHA-256",new TextEncoder().encode(spec.lockfile))).pipe(map6(encodeHex));var receiptText=(spec,lockSha256)=>`${JSON.stringify({id:spec.id,lockSha256,version:spec.version},null,2)}
|
|
281
|
-
`;var decodeReceipt=decodeUnknownOption2(fromJsonString2(Struct({lockSha256:String4})));var pathExists=(fs,target)=>fs.exists(target).pipe(orElseSucceed2(()=>false));var mismatch=(directory3,spec)=>gen2(function*runtimeMismatch(){const fs=yield*FileSystem;const path7=yield*Path;const text3=yield*fs.readFileString(path7.join(directory3,runtimeReceiptName)).pipe(option2);if(isNone2(text3)){return`${spec.id} ${spec.version} is not installed at ${directory3}`}const digest2=yield*lockDigest(spec).pipe(result2);if(isFailure2(digest2)){return`cannot hash the ${spec.id} ${spec.version} lockfile: ${platformFailure(digest2.failure)}`}const receipt=decodeReceipt(text3.value);if(isNone2(receipt)||receipt.value.lockSha256!==digest2.success){return`${spec.id} ${spec.version} at ${directory3} was installed from a different lockfile`}return(yield*pathExists(fs,path7.join(directory3,spec.server)))?undefined:`${spec.id} ${spec.version} at ${directory3} is missing ${spec.server}`});var inspectToolRuntime=(env,spec)=>gen2(function*inspectRuntime(){const directory3=dataDirectory(yield*Path,env,spec);const reason=yield*mismatch(directory3,spec);return{installed:reason===undefined,path:directory3,version:spec.version,...reason===undefined?{}:{reason}}}).pipe(provide4(platformLayer));class RuntimeUnavailable extends TaggedErrorClass()("@punks/cli/features/typescript-semantic-reads/RuntimeUnavailable",{reason:String4}){}var versionParts=(value3)=>{const match8=/(?<version>\d+(?:\.\d+){0,2})/u.exec(value3)?.groups?.version;return match8?.split(".").map(Number)};var atLeast3=(actual,minimum)=>{for(let index=0;index<Math.max(actual.length,minimum.length);index+=1){const difference=(actual[index]??0)-(minimum[index]??0);if(difference!==0){return difference>0}}return true};var unavailable=(reason)=>new RuntimeUnavailable({reason});var attempt=(label,effect2)=>effect2.pipe(mapError3((cause)=>unavailable(`${label}: ${platformFailure(cause)}`)));var checkPreconditions=(spec,env,run6)=>gen2(function*checkRuntimePreconditions(){const minimum=/^>=\s*(?<version>\d+(?:\.\d+){0,2})$/u.exec(spec.node.trim())?.groups?.version;if(minimum===undefined){return yield*unavailable(`unsupported Node requirement "${spec.node}"`)}if(!commandExistsOnPath("npm",env)){return yield*unavailable(`npm is not on PATH; it is required to install ${spec.id}`)}const result3=yield*run6({args:["--version"],command:"node",cwd:homedir2(),env,timeoutMs:nodeVersionTimeoutMs});const actual=result3.exitCode===0?versionParts(result3.stdout):undefined;if(actual===undefined){return yield*unavailable(commandFailureDetail("node --version",result3,nodeVersionTimeoutMs))}if(!atLeast3(actual,minimum.split(".").map(Number))){return yield*unavailable(`Node ${actual.join(".")} does not satisfy ${spec.id}'s ${spec.node}`)}return actual.join(".")});var moveIntoPlace=(fs,staged,directory3)=>attempt(`replace ${directory3}`,gen2(function*replaceInstall(){if(yield*pathExists(fs,directory3)){const aside=`${staged}.previous`;yield*fs.rename(directory3,aside);yield*fs.rename(staged,directory3).pipe(tapError2(()=>fs.rename(aside,directory3)));yield*fs.remove(aside,{force:true,recursive:true})}else{yield*fs.rename(staged,directory3)}}));var install=(spec,env,run6)=>gen2(function*installToolRuntime(){const fs=yield*FileSystem;const path7=yield*Path;const directory3=dataDirectory(path7,env,spec);yield*checkPreconditions(spec,env,run6);yield*acquireUseRelease2(attempt(`create a staging directory beside ${directory3}`,fs.makeDirectory(path7.dirname(directory3),{recursive:true}).pipe(andThen2(fs.makeTempDirectory({directory:path7.dirname(directory3),prefix:`.${spec.version}.staging-`})))),(staged)=>gen2(function*stageToolRuntime(){yield*attempt("write the pinned manifest",fs.writeFileString(path7.join(staged,"package.json"),spec.manifest).pipe(andThen2(fs.writeFileString(path7.join(staged,"package-lock.json"),spec.lockfile))));const result3=yield*run6({args:["ci","--ignore-scripts","--no-audit","--no-fund"],command:"npm",cwd:staged,env,shell:process.platform==="win32",timeoutMs:npmInstallTimeoutMs});if(result3.exitCode!==0){return yield*unavailable(commandFailureDetail("npm ci",result3,npmInstallTimeoutMs))}if(!(yield*pathExists(fs,path7.join(staged,spec.server)))){return yield*unavailable(`npm ci completed without ${spec.server}`)}yield*attempt("write the runtime receipt",lockDigest(spec).pipe(flatMap3((lockSha256)=>fs.writeFileString(path7.join(staged,runtimeReceiptName),receiptText(spec,lockSha256)))));return yield*moveIntoPlace(fs,staged,directory3)}),(staged)=>fs.remove(staged,{force:true,recursive:true}).pipe(orDie2));return directory3});var ensureToolRuntime=({env,run:run6=runCommand,spec})=>gen2(function*ensureRuntime(){const directory3=dataDirectory(yield*Path,env,spec);if((yield*mismatch(directory3,spec))===undefined){return{_tag:"Reused",path:directory3}}return yield*install(spec,env,run6).pipe(match6({onFailure:(failure)=>({_tag:"Unavailable",reason:failure.reason}),onSuccess:(installed)=>({_tag:"Installed",path:installed})}))}).pipe(provide4(platformLayer));import{existsSync as existsSync4,realpathSync}from"node:fs";import path7 from"node:path";var isInside=(root,absolute)=>{const relative=path7.relative(root,absolute);return relative===""||!relative.startsWith("..")&&!path7.isAbsolute(relative)};var escapesRepository=(root,relative)=>{const absolute=path7.resolve(root,relative);if(!isInside(root,absolute)){return`${relative} is outside the repository`}let ancestor=path7.dirname(absolute);while(!existsSync4(ancestor)&&isInside(root,ancestor)&&ancestor!==root){ancestor=path7.dirname(ancestor)}return isInside(realpathSync(root),realpathSync(ancestor))?undefined:`${relative} resolves outside the repository`};var confined=(root,relative)=>{const problem=escapesRepository(root,relative);if(problem!==undefined){throw new Error(problem)}return path7.resolve(root,relative)};class RegistryUnavailable extends TaggedErrorClass()("RegistryUnavailable",{detail:String4,url:String4}){}class RegistryIntegrityError extends TaggedErrorClass()("RegistryIntegrityError",{detail:String4,url:String4}){}class CliOutsideRange extends TaggedErrorClass()("CliOutsideRange",{baseline:String4,cliVersion:String4,cliVersionRange:String4}){}class InvalidMergeTarget extends TaggedErrorClass()("InvalidMergeTarget",{detail:String4,path:String4}){}class InstallerFilesystemError extends TaggedErrorClass()("InstallerFilesystemError",{detail:String4,path:String4}){}class ProjectIntentError extends TaggedErrorClass()("ProjectIntentError",{detail:String4}){}import{chmodSync,existsSync as existsSync5,mkdirSync,readFileSync as readFileSync4,renameSync,statSync,writeFileSync}from"node:fs";import path8 from"node:path";var defaultRegistryUrl="https://api.harness-intelligence.devpunks.com/r";var settingsPath=".devpunks/settings.json";var installedRecordPath=".devpunks/installed.json";var subagentManifestPath=".agents/subagents/manifest.mjs";var baselineVersionPattern=/^\d{4}\.\d{2}\.\d{2}-[0-9a-f]{7,40}$/u;var BaselineVersion=String4.check(makeFilter2((value3)=>baselineVersionPattern.test(value3)||"Expected a Baseline version YYYY.MM.DD-<sha>"));var RegistryItemName=String4.check(makeFilter2((value3)=>/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(value3)&&value3!=="registry"||"Expected a Registry Item name (lowercase kebab-case, not registry)"));var registryPaths={item:(version2,name)=>`${version2}/${name}.json`,latestCatalog:"registry.json",versionCatalog:(version2)=>`${version2}/registry.json`};var ArtifactKind=Literals(["copied","built","authored"]);var Expansion=Literals(["none","softwareScopes","workspaces"]);var HiCondition=Struct({languages:optional(ArraySchema(String4)),packs:optional(ArraySchema(String4)),technologies:optional(ArraySchema(String4))});var HiFileMeta=Struct({artifact:ArtifactKind,builder:optional(String4),encoding:optional(Literals(["utf-8","base64"])),executable:optional(Boolean3),expand:optional(Expansion),inputs:optional(ArraySchema(String4)),template:optional(Boolean3),when:optional(HiCondition)});var HiSymlink=Struct({expand:optional(Expansion),path:String4,target:String4});var HiMerge=Struct({expand:optional(Expansion),format:Literals(["json","yaml"]),target:String4,value:Unknown2});var HiWorkspaceDependencies=Struct({expand:Expansion,packages:Record(String4,String4),when:optional(HiCondition)});var PackCategory=Literals(["default","detected","surface","language","optional"]);var HiPackMeta=Struct({category:PackCategory,languages:optional(ArraySchema(String4)),promptSurfaces:optional(ArraySchema(String4)),technologies:optional(ArraySchema(String4)),triggerPackages:optional(ArraySchema(String4))});var ItemKind=Literals(["pack","skill","hook","script","source-guide","lint","prompt","subagents","handoff","commit-gate","wiki","tools","harness"]);var safeSegment=(label,pattern)=>String4.check(makeFilter2((value3)=>pattern.test(value3)&&value3!==".."&&value3!=="."||`Expected ${label}`));var HiToolRuntime=Struct({id:safeSegment("a Tool Runtime id",/^[a-z0-9-]+$/u),lockfile:String4,manifest:String4,node:String4,server:String4.check(makeFilter2((value3)=>!value3.startsWith("/")&&!value3.includes("\\")&&!value3.split("/").includes("..")||"Expected a Tool Runtime server path inside the runtime directory")),version:safeSegment("a Tool Runtime version",/^[0-9A-Za-z.+-]+$/u)});var HiItemMeta=Struct({files:optional(Record(String4,HiFileMeta)),harnessAdapters:optional(Boolean3),postInstall:optional(ArraySchema(String4)),kind:ItemKind,merges:optional(ArraySchema(HiMerge)),pack:optional(HiPackMeta),requiredTools:optional(ArraySchema(String4)),skillId:optional(String4),symlinks:optional(ArraySchema(HiSymlink)),toolRuntime:optional(HiToolRuntime),workspaceDependencies:optional(ArraySchema(HiWorkspaceDependencies))});var RegistryItemType=Literals(["registry:item","registry:file"]);var RegistryFile=Struct({content:String4,path:String4,target:String4,type:Literal2("registry:file")});var RegistryItem=Struct({$schema:optional(String4),description:optional(String4),files:optional(ArraySchema(RegistryFile)),meta:Struct({hi:HiItemMeta}),name:RegistryItemName,registryDependencies:optional(ArraySchema(RegistryItemName)),title:optional(String4),type:RegistryItemType});var CatalogEntry=Struct({description:optional(String4),meta:Struct({hi:Struct({kind:ItemKind,pack:optional(HiPackMeta)}),sha256:String4}),name:RegistryItemName,registryDependencies:optional(ArraySchema(RegistryItemName)),title:optional(String4),type:RegistryItemType});var Catalog=Struct({$schema:optional(String4),cliVersionRange:String4,homepage:String4,items:ArraySchema(CatalogEntry),latest:optional(BaselineVersion),name:String4,version:BaselineVersion});var RecordedWorkspace=Struct({languages:ArraySchema(String4),name:optional(String4),path:String4,technologies:ArraySchema(String4)});var RecordedShape=Struct({docsRoot:optional(String4),languages:ArraySchema(String4),monorepo:Boolean3,packs:ArraySchema(String4),technologies:ArraySchema(String4),wikiRoot:optional(String4),workspaces:ArraySchema(RecordedWorkspace)});var RecordedPath=Struct({artifact:Literals(["copied","built","authored","symlink"]),item:String4});var FailedLink=Struct({path:String4,reason:String4,target:String4});var InstalledRecord=Struct({baseline:BaselineVersion,dependencies:Record(String4,ArraySchema(String4)),detectedPacks:optional(ArraySchema(String4)),failedLinks:ArraySchema(FailedLink),items:ArraySchema(String4),paths:Record(String4,RecordedPath),schemaVersion:Literal2(1),shape:RecordedShape});var harnessIds=["claude","codex","cursor","opencode"];var CheckStatus=Literals(["current","update-available","unavailable","not-installed"]);var DriftClass=Literals(["update-available","local-edit","conflict","shape-drift","missing","stale","link-failed"]);var UpdateAction=Literals(["written","skipped","overwritten-local-edit","created","kept","merged","linked","link-failed","dependency-added","dependency-removed","dependency-kept","dependency-range-unreproducible","removed","stale-reported","moved-project-skill","renamed-project-skill","migrated-deleted","migrated-skipped"]);var isPlainObject=(value3)=>value3!==null&&typeof value3==="object"&&!Array.isArray(value3);var sortKeys=(value3)=>{if(Array.isArray(value3)){return value3.map(sortKeys)}if(isPlainObject(value3)){return Object.fromEntries(Object.keys(value3).toSorted().map((key)=>[key,sortKeys(value3[key])]))}return value3};var canonicalJson=(value3)=>`${JSON.stringify(sortKeys(value3),null,2)}
|
|
281
|
+
`;var decodeReceipt=decodeUnknownOption2(fromJsonString2(Struct({lockSha256:String4})));var pathExists=(fs,target)=>fs.exists(target).pipe(orElseSucceed2(()=>false));var mismatch=(directory3,spec)=>gen2(function*runtimeMismatch(){const fs=yield*FileSystem;const path7=yield*Path;const text3=yield*fs.readFileString(path7.join(directory3,runtimeReceiptName)).pipe(option2);if(isNone2(text3)){return`${spec.id} ${spec.version} is not installed at ${directory3}`}const digest2=yield*lockDigest(spec).pipe(result2);if(isFailure2(digest2)){return`cannot hash the ${spec.id} ${spec.version} lockfile: ${platformFailure(digest2.failure)}`}const receipt=decodeReceipt(text3.value);if(isNone2(receipt)||receipt.value.lockSha256!==digest2.success){return`${spec.id} ${spec.version} at ${directory3} was installed from a different lockfile`}return(yield*pathExists(fs,path7.join(directory3,spec.server)))?undefined:`${spec.id} ${spec.version} at ${directory3} is missing ${spec.server}`});var inspectToolRuntime=(env,spec)=>gen2(function*inspectRuntime(){const directory3=dataDirectory(yield*Path,env,spec);const reason=yield*mismatch(directory3,spec);return{installed:reason===undefined,path:directory3,version:spec.version,...reason===undefined?{}:{reason}}}).pipe(provide4(platformLayer));class RuntimeUnavailable extends TaggedErrorClass()("@punks/cli/features/typescript-semantic-reads/RuntimeUnavailable",{reason:String4}){}var versionParts=(value3)=>{const match8=/(?<version>\d+(?:\.\d+){0,2})/u.exec(value3)?.groups?.version;return match8?.split(".").map(Number)};var atLeast3=(actual,minimum)=>{for(let index=0;index<Math.max(actual.length,minimum.length);index+=1){const difference=(actual[index]??0)-(minimum[index]??0);if(difference!==0){return difference>0}}return true};var unavailable=(reason)=>new RuntimeUnavailable({reason});var attempt=(label,effect2)=>effect2.pipe(mapError3((cause)=>unavailable(`${label}: ${platformFailure(cause)}`)));var checkPreconditions=(spec,env,run6)=>gen2(function*checkRuntimePreconditions(){const minimum=/^>=\s*(?<version>\d+(?:\.\d+){0,2})$/u.exec(spec.node.trim())?.groups?.version;if(minimum===undefined){return yield*unavailable(`unsupported Node requirement "${spec.node}"`)}if(!commandExistsOnPath("npm",env)){return yield*unavailable(`npm is not on PATH; it is required to install ${spec.id}`)}const result3=yield*run6({args:["--version"],command:"node",cwd:homedir2(),env,timeoutMs:nodeVersionTimeoutMs});const actual=result3.exitCode===0?versionParts(result3.stdout):undefined;if(actual===undefined){return yield*unavailable(commandFailureDetail("node --version",result3,nodeVersionTimeoutMs))}if(!atLeast3(actual,minimum.split(".").map(Number))){return yield*unavailable(`Node ${actual.join(".")} does not satisfy ${spec.id}'s ${spec.node}`)}return actual.join(".")});var moveIntoPlace=(fs,staged,directory3)=>attempt(`replace ${directory3}`,gen2(function*replaceInstall(){if(yield*pathExists(fs,directory3)){const aside=`${staged}.previous`;yield*fs.rename(directory3,aside);yield*fs.rename(staged,directory3).pipe(tapError2(()=>fs.rename(aside,directory3)));yield*fs.remove(aside,{force:true,recursive:true})}else{yield*fs.rename(staged,directory3)}}));var install=(spec,env,run6)=>gen2(function*installToolRuntime(){const fs=yield*FileSystem;const path7=yield*Path;const directory3=dataDirectory(path7,env,spec);yield*checkPreconditions(spec,env,run6);yield*acquireUseRelease2(attempt(`create a staging directory beside ${directory3}`,fs.makeDirectory(path7.dirname(directory3),{recursive:true}).pipe(andThen2(fs.makeTempDirectory({directory:path7.dirname(directory3),prefix:`.${spec.version}.staging-`})))),(staged)=>gen2(function*stageToolRuntime(){yield*attempt("write the pinned manifest",fs.writeFileString(path7.join(staged,"package.json"),spec.manifest).pipe(andThen2(fs.writeFileString(path7.join(staged,"package-lock.json"),spec.lockfile))));const result3=yield*run6({args:["ci","--ignore-scripts","--no-audit","--no-fund"],command:"npm",cwd:staged,env,shell:process.platform==="win32",timeoutMs:npmInstallTimeoutMs});if(result3.exitCode!==0){return yield*unavailable(commandFailureDetail("npm ci",result3,npmInstallTimeoutMs))}if(!(yield*pathExists(fs,path7.join(staged,spec.server)))){return yield*unavailable(`npm ci completed without ${spec.server}`)}yield*attempt("write the runtime receipt",lockDigest(spec).pipe(flatMap3((lockSha256)=>fs.writeFileString(path7.join(staged,runtimeReceiptName),receiptText(spec,lockSha256)))));return yield*moveIntoPlace(fs,staged,directory3)}),(staged)=>fs.remove(staged,{force:true,recursive:true}).pipe(orDie2));return directory3});var ensureToolRuntime=({env,run:run6=runCommand,spec})=>gen2(function*ensureRuntime(){const directory3=dataDirectory(yield*Path,env,spec);if((yield*mismatch(directory3,spec))===undefined){return{_tag:"Reused",path:directory3}}return yield*install(spec,env,run6).pipe(match6({onFailure:(failure)=>({_tag:"Unavailable",reason:failure.reason}),onSuccess:(installed)=>({_tag:"Installed",path:installed})}))}).pipe(provide4(platformLayer));import{existsSync as existsSync4,realpathSync}from"node:fs";import path7 from"node:path";var isInside=(root,absolute)=>{const relative=path7.relative(root,absolute);return relative===""||!relative.startsWith("..")&&!path7.isAbsolute(relative)};var escapesRepository=(root,relative)=>{const absolute=path7.resolve(root,relative);if(!isInside(root,absolute)){return`${relative} is outside the repository`}let ancestor=path7.dirname(absolute);while(!existsSync4(ancestor)&&isInside(root,ancestor)&&ancestor!==root){ancestor=path7.dirname(ancestor)}return isInside(realpathSync(root),realpathSync(ancestor))?undefined:`${relative} resolves outside the repository`};var confined=(root,relative)=>{const problem=escapesRepository(root,relative);if(problem!==undefined){throw new Error(problem)}return path7.resolve(root,relative)};class RegistryUnavailable extends TaggedErrorClass()("RegistryUnavailable",{detail:String4,url:String4}){}class RegistryIntegrityError extends TaggedErrorClass()("RegistryIntegrityError",{detail:String4,url:String4}){}class CliOutsideRange extends TaggedErrorClass()("CliOutsideRange",{baseline:String4,cliVersion:String4,cliVersionRange:String4}){}class InvalidMergeTarget extends TaggedErrorClass()("InvalidMergeTarget",{detail:String4,path:String4}){}class InstallerFilesystemError extends TaggedErrorClass()("InstallerFilesystemError",{detail:String4,path:String4}){}class ProjectIntentError extends TaggedErrorClass()("ProjectIntentError",{detail:String4}){}import{chmodSync,existsSync as existsSync5,mkdirSync,readFileSync as readFileSync4,renameSync,statSync,writeFileSync}from"node:fs";import path8 from"node:path";var defaultRegistryUrl="https://api.harness-intelligence.devpunks.com/r";var settingsPath=".devpunks/settings.json";var installedRecordPath=".devpunks/installed.json";var subagentManifestPath=".agents/subagents/manifest.mjs";var baselineVersionPattern=/^\d{4}\.\d{2}\.\d{2}-[0-9a-f]{7,40}$/u;var BaselineVersion=String4.check(makeFilter2((value3)=>baselineVersionPattern.test(value3)||"Expected a Baseline version YYYY.MM.DD-<sha>"));var RegistryItemName=String4.check(makeFilter2((value3)=>/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(value3)&&value3!=="registry"||"Expected a Registry Item name (lowercase kebab-case, not registry)"));var registryPaths={item:(version2,name)=>`${version2}/${name}.json`,latestCatalog:"registry.json",versionCatalog:(version2)=>`${version2}/registry.json`};var ArtifactKind=Literals(["copied","built","authored"]);var Expansion=Literals(["none","softwareScopes","workspaces"]);var HiCondition=Struct({languages:optional(ArraySchema(String4)),packs:optional(ArraySchema(String4)),technologies:optional(ArraySchema(String4))});var HiFileMeta=Struct({artifact:ArtifactKind,builder:optional(String4),encoding:optional(Literals(["utf-8","base64"])),executable:optional(Boolean3),expand:optional(Expansion),inputs:optional(ArraySchema(String4)),template:optional(Boolean3),when:optional(HiCondition)});var HiSymlink=Struct({expand:optional(Expansion),path:String4,target:String4});var HiMerge=Struct({expand:optional(Expansion),format:Literals(["json","yaml"]),target:String4,value:Unknown2});var HiWorkspaceDependencies=Struct({expand:Expansion,packages:Record(String4,String4),when:optional(HiCondition)});var PackCategory=Literals(["default","detected","surface","language","optional"]);var HiPackMeta=Struct({category:PackCategory,languages:optional(ArraySchema(String4)),promptSurfaces:optional(ArraySchema(String4)),technologies:optional(ArraySchema(String4)),triggerPackages:optional(ArraySchema(String4))});var ItemKind=Literals(["pack","skill","hook","script","source-guide","lint","prompt","subagents","handoff","commit-gate","wiki","tools","harness"]);var safeSegment=(label,pattern)=>String4.check(makeFilter2((value3)=>pattern.test(value3)&&value3!==".."&&value3!=="."||`Expected ${label}`));var HiToolRuntime=Struct({id:safeSegment("a Tool Runtime id",/^[a-z0-9-]+$/u),lockfile:String4,manifest:String4,node:String4,server:String4.check(makeFilter2((value3)=>!value3.startsWith("/")&&!value3.includes("\\")&&!value3.split("/").includes("..")||"Expected a Tool Runtime server path inside the runtime directory")),version:safeSegment("a Tool Runtime version",/^[0-9A-Za-z.+-]+$/u)});var HiItemMeta=Struct({files:optional(Record(String4,HiFileMeta)),harnessAdapters:optional(Boolean3),kind:ItemKind,merges:optional(ArraySchema(HiMerge)),pack:optional(HiPackMeta),requiredTools:optional(ArraySchema(String4)),skillId:optional(String4),symlinks:optional(ArraySchema(HiSymlink)),toolRuntime:optional(HiToolRuntime),workspaceDependencies:optional(ArraySchema(HiWorkspaceDependencies))});var RegistryItemType=Literals(["registry:item","registry:file"]);var RegistryFile=Struct({content:String4,path:String4,target:String4,type:Literal2("registry:file")});var RegistryItem=Struct({$schema:optional(String4),description:optional(String4),files:optional(ArraySchema(RegistryFile)),meta:Struct({hi:HiItemMeta}),name:RegistryItemName,registryDependencies:optional(ArraySchema(RegistryItemName)),title:optional(String4),type:RegistryItemType});var CatalogEntry=Struct({description:optional(String4),meta:Struct({hi:Struct({kind:ItemKind,pack:optional(HiPackMeta)}),sha256:String4}),name:RegistryItemName,registryDependencies:optional(ArraySchema(RegistryItemName)),title:optional(String4),type:RegistryItemType});var Catalog=Struct({$schema:optional(String4),cliVersionRange:String4,homepage:String4,items:ArraySchema(CatalogEntry),latest:optional(BaselineVersion),name:String4,version:BaselineVersion});var RecordedWorkspace=Struct({languages:ArraySchema(String4),name:optional(String4),path:String4,technologies:ArraySchema(String4)});var RecordedShape=Struct({docsRoot:optional(String4),languages:ArraySchema(String4),monorepo:Boolean3,packs:ArraySchema(String4),technologies:ArraySchema(String4),wikiRoot:optional(String4),workspaces:ArraySchema(RecordedWorkspace)});var RecordedPath=Struct({artifact:Literals(["copied","built","authored","symlink"]),item:String4});var FailedLink=Struct({path:String4,reason:String4,target:String4});var InstalledRecord=Struct({baseline:BaselineVersion,dependencies:Record(String4,ArraySchema(String4)),detectedPacks:optional(ArraySchema(String4)),failedLinks:ArraySchema(FailedLink),items:ArraySchema(String4),paths:Record(String4,RecordedPath),schemaVersion:Literal2(1),shape:RecordedShape});var harnessIds=["claude","codex","cursor","opencode"];var CheckStatus=Literals(["current","update-available","unavailable","not-installed"]);var DriftClass=Literals(["update-available","local-edit","conflict","shape-drift","missing","stale","link-failed"]);var UpdateAction=Literals(["written","skipped","overwritten-local-edit","created","kept","merged","linked","link-failed","dependency-added","dependency-removed","dependency-kept","dependency-range-unreproducible","removed","stale-reported","moved-project-skill","renamed-project-skill","migrated-deleted","migrated-skipped"]);var isPlainObject=(value3)=>value3!==null&&typeof value3==="object"&&!Array.isArray(value3);var sortKeys=(value3)=>{if(Array.isArray(value3)){return value3.map(sortKeys)}if(isPlainObject(value3)){return Object.fromEntries(Object.keys(value3).toSorted().map((key)=>[key,sortKeys(value3[key])]))}return value3};var canonicalJson=(value3)=>`${JSON.stringify(sortKeys(value3),null,2)}
|
|
282
282
|
`;var writeFileAtomic=(absolutePath,content,mode)=>{mkdirSync(path8.dirname(absolutePath),{recursive:true});const existingMode=mode===undefined?statSync(absolutePath,{throwIfNoEntry:false})?.mode:undefined;const temporary=`${absolutePath}.hi-${process.pid}.tmp`;writeFileSync(temporary,content,mode===undefined?undefined:{mode});if(existingMode!==undefined){chmodSync(temporary,existingMode%4096)}renameSync(temporary,absolutePath)};var errorDetail=(cause)=>cause instanceof Error?cause.message:String(cause);var decodeRecord=decodeUnknownSync(fromJsonString2(InstalledRecord));var readInstalledRecord=(root)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:errorDetail(cause),path:installedRecordPath}),try:()=>{const absolute=path8.join(root,installedRecordPath);return existsSync5(absolute)?decodeRecord(readFileSync4(absolute,"utf-8")):undefined}});var normalizeRecord=(record2)=>({...record2,dependencies:Object.fromEntries(Object.entries(record2.dependencies).filter(([,names])=>names.length>0).map(([workspace,names])=>[workspace,[...new Set(names)].toSorted()])),failedLinks:record2.failedLinks.toSorted((left,right)=>left.path.localeCompare(right.path)),items:[...new Set(record2.items)].toSorted()});var writeInstalledRecord=(root,record2)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:errorDetail(cause),path:installedRecordPath}),try:()=>{writeFileAtomic(path8.join(root,installedRecordPath),canonicalJson(normalizeRecord(record2)))}});var begin="# BEGIN hi typegraph (generated by hi update; edits are restored)";var end="# END hi typegraph";var malformed="the hi typegraph block markers are malformed; fix or remove them";var typegraphReads=["ts_find_symbol","ts_definition","ts_references","ts_type_info","ts_module_exports"];var isControl=(character)=>{const code=character.codePointAt(0)??0;return code<32||code===127};var basicString=(value3)=>{let escaped="";for(const character of value3){if(character==="\\"||character==='"'){escaped+=`\\${character}`}else if(isControl(character)){escaped+=`\\u${(character.codePointAt(0)??0).toString(16).padStart(4,"0")}`}else{escaped+=character}}return`"${escaped}"`};var versionPattern=/^[0-9A-Za-z.+-]+$/u;var launchScript=(version2)=>{if(!versionPattern.test(version2)){throw new Error(`Invalid Typegraph version for the Codex launch script: ${version2}`)}return['TYPEGRAPH_PROJECT_ROOT="$(git rev-parse --show-toplevel)"',`exec node "\${XDG_DATA_HOME:-$HOME/.local/share}/hi-tools/typegraph-mcp/${version2}/node_modules/typegraph-mcp/dist/server.cjs"`].join(" ")};var serverTable=(script,{server,tsconfig})=>[`[mcp_servers.${server}]`,'command = "sh"',`args = ["-c", '${script}']`,`env = { TYPEGRAPH_TSCONFIG = ${basicString(tsconfig)} }`,`enabled_tools = [${typegraphReads.map(basicString).join(", ")}]`,'default_tools_approval_mode = "approve"',"startup_timeout_sec = 20","tool_timeout_sec = 60"].join(`
|
|
283
283
|
`);var fenced=(tables)=>tables.length===0?"":[begin,tables.join(`
|
|
284
284
|
|
|
@@ -311,15 +311,15 @@ try {
|
|
|
311
311
|
await client?.close().catch(() => {});
|
|
312
312
|
}
|
|
313
313
|
`;var decodeProbeLine=decodeUnknownOption2(fromJsonString2(Struct({files:optional(Finite),ok:Boolean3,reason:optional(String4)})));var probeResult=(tsconfig,result3,timeoutMs)=>{const lastLine=result3.stdout.trimEnd().split(`
|
|
314
|
-
`).at(-1)??"";const line=result3.timedOut?none2():decodeProbeLine(lastLine);if(isNone2(line)){const failure=commandFailureDetail("load probe",result3,timeoutMs);return{ok:false,reason:result3.exitCode===0?`${failure} (unreadable probe output)`:failure,tsconfig}}const{files,ok,reason}=line.value;return{ok,tsconfig,...files===undefined?{}:{files},...ok||reason===undefined?{}:{reason}}};var probeCompilerProjects=({concurrency=4,env,projectRoot,run:run6=runCommand,runtimePath,timeoutMs=60000,tsconfigs})=>forEach2(tsconfigs,(tsconfig)=>run6({args:["--input-type=module","-e",probeScript,projectRoot,tsconfig],command:"node",cwd:runtimePath,env,timeoutMs}).pipe(map6((result3)=>probeResult(tsconfig,result3,timeoutMs))),{concurrency});var typegraphRuntimeItem="typegraph-runtime";var codexConfigPath=".codex/config.toml";var byTsconfig=(left,right)=>Number(left.tsconfig>right.tsconfig)-Number(left.tsconfig<right.tsconfig);var compilerProjectStatuses=({env,override,probeTimeoutMs,root,run:run6,runtimePath,wikiRoot})=>gen2(function*statuses(){const discovery=yield*discoverCompilerProjects({override,root,wikiRoot});const probes=runtimePath===undefined?undefined:yield*probeCompilerProjects({env,projectRoot:root,runtimePath,tsconfigs:discovery.projects.map((project)=>project.tsconfig),...run6===undefined?{}:{run:run6},...probeTimeoutMs===undefined?{}:{timeoutMs:probeTimeoutMs}});const probed=discovery.projects.map(({server,tsconfig},index)=>{const probe=probes?.[index];if(probe?.ok===true){return{probe:"pass",server,tsconfig,...probe.files===undefined?{}:{files:probe.files}}}const reason=probes===undefined?"not probed: Tool Runtime not installed":probe?.reason??"load probe failed";return{probe:"fail",reason,server,tsconfig}});const ambiguous=discovery.ambiguous.map(({reason,tsconfig})=>({probe:"ambiguous",reason,tsconfig}));return{excluded:discovery.excluded,projects:[...probed,...ambiguous].toSorted(byTsconfig)}});var filesystem=(run6)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:codexConfigPath}),try:run6});var filesystemError=(cause)=>new InstallerFilesystemError({detail:platformFailure(cause),path:codexConfigPath});var readCodexFile=(root)=>gen2(function*readCodex(){const fs=yield*FileSystem;const absolute=yield*filesystem(()=>confined(root,codexConfigPath));if(isSome2(yield*option2(fs.readLink(absolute)))){return{kind:"other"}}const stat3=yield*fs.stat(absolute).pipe(asSome2,catchIf2((error2)=>error2.reason._tag==="NotFound",()=>succeedNone2),mapError3(filesystemError));if(isNone2(stat3)){return{kind:"absent"}}if(stat3.value.type!=="File"){return{kind:"other"}}const content=yield*fs.readFileString(absolute).pipe(mapError3(filesystemError));return{content,kind:"file"}}).pipe(provide4(platformLayer));var readRegisteredServers=(root)=>readCodexFile(root).pipe(map6((file5)=>file5.kind==="file"?readTypegraphBlock(file5.content):[]));var applyCodexBlock=(root,block)=>gen2(function*apply2(){const file5=yield*readCodexFile(root);if(file5.kind==="other"){return{codexConfig:"unchanged",conflicts:block===""?[]:[`${codexConfigPath} is not a regular file; left untouched`]}}const existing=file5.kind==="file"?file5.content:undefined;const next=applyTypegraphBlock(existing,block);if(!next.changed||next.content===undefined){return{codexConfig:"unchanged",conflicts:next.conflicts}}const{content}=next;yield*filesystem(()=>{writeFileAtomic(confined(root,codexConfigPath),content)});return{codexConfig:readTypegraphBlock(content).length===0?"removed":"written",conflicts:next.conflicts}});var syncSemanticReads=({env,override,root,run:run6,runtime,wikiRoot})=>gen2(function*sync4(){if(runtime===undefined){const removed=yield*applyCodexBlock(root,"");return{...removed,excluded:[],projects:[],runtime:{status:"not-selected"}}}const outcome=yield*ensureToolRuntime({env,spec:runtime,...run6===undefined?{}:{run:run6}});if(outcome._tag==="Unavailable"){const removed=yield*applyCodexBlock(root,"");return{...removed,excluded:[],projects:[],runtime:{reason:outcome.reason,status:"unavailable"}}}const{excluded,projects}=yield*compilerProjectStatuses({env,override,root,run:run6,runtimePath:outcome.path,wikiRoot});const passing=projects.flatMap((project)=>project.probe==="pass"?[{server:project.server,tsconfig:project.tsconfig}]:[]);const applied=yield*applyCodexBlock(root,renderTypegraphBlock({projects:passing,version:runtime.version}));return{...applied,excluded,projects,runtime:{path:outcome.path,status:outcome._tag==="Reused"?"reused":"installed"}}});var antiSlopRules={"anti-slop/no-chained-type-assertions":"error","anti-slop/no-conditional-empty-object-spread":"error","anti-slop/no-known-value-widening":"error","anti-slop/no-module-mocking":"error","anti-slop/no-object-parameters":"error","anti-slop/no-reflect-apply":"error","anti-slop/no-reflect-get":"error","anti-slop/no-runtime-typeof":"error","anti-slop/no-shape-in-symbol-names":"error","anti-slop/no-unknown-parameters":"error","anti-slop/no-unknown-returns":"error","anti-slop/no-unknown-type-aliases":"error","anti-slop/no-unsafe-dictionary-type":"error","anti-slop/no-widen-then-assert":"error","anti-slop/require-safety-comment-for-type-assertion":"error"};var sharedReactPlacement={placementNotes:"Add as an override for detected React-rendered code. Keep backend packages outside this override unless they render React.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-react-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected React workspaces"]};var webOnlyPlacement={placementNotes:"Place this in the Next.js app override. If the repo uses a different frontend app path, retarget the file globs to that workspace before composing the final Oxlint config.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-nextjs-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Next.js workspaces"]};var effectPlacement={placementNotes:"Apply this only where Effect code lives. If the target repo renames or splits backend workspaces, move the override with those code paths instead of broadening it repo-wide.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-effect-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Effect workspaces"]};var vitestPlacement={placementNotes:"Attach this to test-only globs. Expand or narrow the file patterns to match the repo's actual Vitest test layout instead of treating it as a global default.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-test-workspace>/**/*.{test,spec}.{js,jsx,ts,tsx}","<detected-test-workspace>/src/test/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript/TypeScript test workspaces"]};var lintCatalog=[{description:"Vendored Anti-Slop rules for rejecting low-evidence TypeScript and JavaScript patterns.",id:"typescript-anti-slop",ignorePatterns:["tools/oxlint/anti-slop/**"],jsPlugins:[{name:"anti-slop",specifier:"./tools/oxlint/anti-slop/index.mjs"}],oxlintPresets:[],placement:{placementNotes:"Apply to JavaScript and TypeScript workspaces.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript and TypeScript workspaces"]},plugins:[],requiredDevDependencies:["@oxlint/plugins"],requiredDevDependencyVersions:{"@oxlint/plugins":"1.86.0"},rules:antiSlopRules,settings:{},sourceFiles:[{sourcePath:"lint/anti-slop/index.mjs",targetPath:"tools/oxlint/anti-slop/index.mjs"},{sourcePath:"lint/anti-slop/LICENSE",targetPath:"tools/oxlint/anti-slop/LICENSE"}]},{description:"Explicit Anti-Slop adoption policy for existing Harness workspaces.",id:"punks-anti-slop-transition",jsPlugins:[],oxlintPresets:[],placement:{placementNotes:"Apply only to existing Harness workspaces while they adopt Anti-Slop.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["Harness workspaces"]},plugins:[],requiredDevDependencies:[],rules:Object.fromEntries(Object.keys(antiSlopRules).map((rule)=>[rule,"off"])),settings:{},targetPackageNames:["@punks/api","@punks/auth","@punks/backoffice","@punks/cli","@punks/config","@punks/contract","@punks/db","@punks/env","@punks/scaffold","@punks/ui","@punks/web","@punks/wiki"]},{categories:{correctness:"error"},description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:["react"],requiredDevDependencies:[],rules:{},settings:{}},{description:"React Hooks lint rules via the JS plugin bridge for Oxlint.",id:"react-hooks",jsPlugins:[{name:"react-hooks-js",specifier:"eslint-plugin-react-hooks"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-hooks"],requiredDevDependencyVersions:{"eslint-plugin-react-hooks":"7.1.1"},rules:Object.fromEntries([["react-hooks-js/exhaustive-deps","error"],["react-hooks-js/component-hook-factories","error"],["react-hooks-js/config","error"],["react-hooks-js/error-boundaries","error"],["react-hooks-js/gating","error"],["react-hooks-js/globals","error"],["react-hooks-js/immutability","error"],["react-hooks-js/incompatible-library","error"],["react-hooks-js/preserve-manual-memoization","error"],["react-hooks-js/purity","error"],["react-hooks-js/refs","error"],["react-hooks-js/rules-of-hooks","error"],["react-hooks-js/set-state-in-effect","error"],["react-hooks-js/set-state-in-render","error"],["react-hooks-js/static-components","error"],["react-hooks-js/unsupported-syntax","error"],["react-hooks-js/use-memo","error"]]),settings:{}},{description:"Guidance rules that push React code away from unnecessary effects.",id:"react-you-might-not-need-an-effect",jsPlugins:[{name:"react-you-might-not-need-an-effect-js",specifier:"eslint-plugin-react-you-might-not-need-an-effect"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-you-might-not-need-an-effect"],requiredDevDependencyVersions:{"eslint-plugin-react-you-might-not-need-an-effect":"1.0.2"},rules:{"react-you-might-not-need-an-effect-js/no-adjust-state-on-prop-change":"error","react-you-might-not-need-an-effect-js/no-chain-state-updates":"error","react-you-might-not-need-an-effect-js/no-derived-state":"error","react-you-might-not-need-an-effect-js/no-event-handler":"error","react-you-might-not-need-an-effect-js/no-initialize-state":"error","react-you-might-not-need-an-effect-js/no-pass-data-to-parent":"error","react-you-might-not-need-an-effect-js/no-pass-live-state-to-parent":"error","react-you-might-not-need-an-effect-js/no-reset-all-state-on-prop-change":"error"},settings:{}},{description:"First-party frontend-domain-structure rules enforcing the layer model: routes, composition, features, modules, integrations, ui.",id:"react-frontend-layers",ignorePatterns:["tools/oxlint/frontend-layers/**"],jsPlugins:[{name:"frontend-layers",specifier:"./tools/oxlint/frontend-layers/index.mjs"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["@oxlint/plugins"],requiredDevDependencyVersions:{"@oxlint/plugins":"1.86.0"},rules:{"frontend-layers/known-top-level":"error","frontend-layers/layer-order":"error","frontend-layers/no-peer-feature":"error","frontend-layers/no-prototype-folder":"error","frontend-layers/public-entrypoint":"error","frontend-layers/route-imports":"error","frontend-layers/ui-placement":"error"},settings:{},sourceFiles:[{sourcePath:"lint/frontend-layers/index.mjs",targetPath:"tools/oxlint/frontend-layers/index.mjs"}]},{description:"Ultracite Next.js preset for the main web application.",id:"next-core",jsPlugins:[],oxlintPresets:["next"],placement:{...webOnlyPlacement,placementNotes:"Place this beside the React app override and set `settings.next.rootDir` to the repo's actual Next workspace roots if the final config needs that plugin setting."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Leafmost-Suspense rule from @punks/lints/next: with cacheComponents on, each data read gets its own <Suspense> at the leaf.",id:"next-leafmost-suspense",jsPlugins:[{name:"punks-next",specifier:"@punks/lints/next"}],oxlintPresets:[],placement:webOnlyPlacement,plugins:[],requiredDevDependencies:["@punks/lints"],requiredDevDependencyVersions:{"@punks/lints":"0.1.0"},rules:{"punks-next/leafmost-suspense":"error"},settings:{}},{description:"Ultracite TanStack preset for query/router/start framework linting.",id:"tanstack-query-core",jsPlugins:[],oxlintPresets:["tanstack"],placement:{...webOnlyPlacement,placementNotes:"Scope this to client code that owns TanStack Query usage. Keep it out of server-only or shared non-query packages unless those paths actually create queries or mutations."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Effect architectural rule that blocks barrel-package imports.",id:"effect-no-barrel-imports",jsPlugins:[{name:"effect-js",specifier:"@effect/eslint-plugin"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/eslint-plugin","@typescript-eslint/utils","eslint"],requiredDevDependencyVersions:{"@effect/eslint-plugin":"0.3.2","@typescript-eslint/utils":"8.22.0",eslint:"9.39.5"},rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},settings:{}},{description:"Effect tsgo recommended type-aware Oxlint rules.",id:"effect-tsgo-recommended",jsPlugins:[],oxlintConfigExtensions:[{exportName:"recommended",specifier:"@effect/tsgo/oxlint-presets"}],oxlintPresets:[],placement:effectPlacement,plugins:[],prepareCommands:["effect-tsgo patch --no-typescript --oxlint"],requiredDevDependencies:["@effect/tsgo","oxlint-tsgolint"],requiredDevDependencyVersions:{"@effect/tsgo":"0.48.1",oxfmt:"0.72.0",oxlint:"1.86.0","oxlint-tsgolint":"7.0.2003",ultracite:"7.12.4"},rules:{},settings:{}},{description:"Ultracite Vitest preset for repo-owned test globs.",id:"vitest-core",jsPlugins:[],oxlintPresets:["vitest"],placement:vitestPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Canonical lint policy for the shipped Harness CLI package.",id:"punks-cli-canonical",ignorePatterns:["src/data/lint/anti-slop/**","src/data/hooks/format-edited-file-core.mjs","src/data/hooks/format-edited-file.mjs","src/data/hooks/scaffold-update-check.mjs"],jsPlugins:[],oxlintPresets:[],placement:{placementNotes:"Apply only to the exact @punks/cli package.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["@punks/cli"]},plugins:[],requiredDevDependencies:[],rules:{},settings:{},targetPackageNames:["@punks/cli"]},{description:"Canonical lint exceptions for the Harness backoffice package.",id:"punks-backoffice-canonical",jsPlugins:[],oxlintPresetRules:{vitest:{"vitest/prefer-import-in-mock":"off","vitest/prefer-importing-vitest-globals":"off"}},oxlintPresets:[],placement:{placementNotes:"Apply only to the exact @punks/backoffice package.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["@punks/backoffice"]},plugins:[],requiredDevDependencies:[],rules:{"eslint/func-style":"off"},settings:{},targetPackageNames:["@punks/backoffice"]}];import{existsSync as existsSync6,readdirSync,readFileSync as readFileSync6}from"node:fs";import path10 from"node:path";import{spawnSync as spawnSync2}from"node:child_process";import nodeModule from"node:module";import{isDeepStrictEqual}from"node:util";import{runInNewContext}from"node:vm";var lintItemPrefix="lint-";var packItemPrefix="pack-";var selectionPath=".devpunks/specs/lint/selection.json";var settingsPath2=".devpunks/settings.json";var lintToolchain={oxfmt:"0.72.0",oxlint:"1.86.0",ultracite:"7.12.4"};var lintAssetSpecPath=(assetId)=>`lint/${assetId}/asset.json`;var JsPlugin=Struct({name:String4,specifier:String4});var UnknownRecord=Record(String4,Unknown2);var LintAssetSpec=Struct({categories:optional(UnknownRecord),description:String4,id:String4,ignorePatterns:optional(ArraySchema(String4)),jsPlugins:ArraySchema(JsPlugin),oxlintConfigExtensions:optional(ArraySchema(Struct({exportName:String4,specifier:String4}))),oxlintPresetRules:optional(Record(String4,UnknownRecord)),oxlintPresets:ArraySchema(String4),plugins:ArraySchema(String4),prepareCommands:optional(ArraySchema(String4)),requiredDevDependencies:ArraySchema(String4),requiredDevDependencyVersions:optional(Record(String4,String4)),rules:UnknownRecord,settings:UnknownRecord,targetPackageNames:optional(ArraySchema(String4))});var decodeSpec=decodeUnknownSync(fromJsonString2(LintAssetSpec));var isRecord2=(value3)=>typeof value3==="object"&&value3!==null&&!Array.isArray(value3);var uniqueSorted=(values)=>[...new Set(values)].toSorted();var intersects=(left,right)=>left.some((value3)=>right.includes(value3));var installedAssets=(context3)=>context3.items.filter((item)=>item.meta.hi.kind==="lint"&&item.name.startsWith(lintItemPrefix)).flatMap((item)=>{const assetId=item.name.slice(lintItemPrefix.length);const file5=item.files?.find((entry)=>entry.path===lintAssetSpecPath(assetId));return file5===undefined?[]:[{assetId,content:file5.content,item}]}).map(({content,item})=>({packs:context3.items.filter((pack)=>pack.meta.hi.kind==="pack"&&pack.registryDependencies?.includes(item.name)===true),spec:decodeSpec(content)})).toSorted((left,right)=>left.spec.id.localeCompare(right.spec.id));var packApplies=(pack,scope3)=>{const technologies=pack.meta.hi.pack?.technologies??[];const languages=pack.meta.hi.pack?.languages??[];return technologies.length===0&&languages.length===0||intersects(technologies,scope3.technologies)||intersects(languages,scope3.languages)};var scopeAssets=(context3,scope3)=>installedAssets(context3).filter(({packs,spec})=>spec.targetPackageNames===undefined?packs.some((pack)=>packApplies(pack,scope3)):spec.targetPackageNames.includes(scope3.name??"")).map(({spec})=>spec).toSorted((left,right)=>Number(left.targetPackageNames!==undefined)-Number(right.targetPackageNames!==undefined));var scopeWorkspace=(context3,scopePath)=>context3.shape.workspaces.find((workspace)=>workspace.path===scopePath)??{languages:[],path:scopePath,technologies:[]};var requireScope=(scope3)=>{if(scope3===undefined){throw new Error("oxlint-config and oxlint-local render once per Software Scope; expand them over softwareScopes.")}return scope3};var requiredDevDependencies=(assets)=>uniqueSorted([...Object.keys(lintToolchain),...assets.flatMap((asset)=>asset.requiredDevDependencies)]);var ultraciteCorePreset="core";var rawTs=(source)=>({rawTs:source});var isRawTs=(value3)=>isRecord2(value3)&&typeof value3.rawTs==="string"&&Object.keys(value3).length===1;var tsPropertyKey=(key)=>/^[A-Z_$][\w$]*$/iu.test(key)?key:JSON.stringify(key);var pad2=(width)=>" ".repeat(width);var encodeTs=(value3,indent=0,leadingWidth=indent)=>{if(isRawTs(value3)){return value3.rawTs}if(Array.isArray(value3)){if(value3.length===0){return"[]"}const compact=`[${value3.map((entry)=>JSON.stringify(entry)).join(", ")}]`;if(value3.every((entry)=>entry===null||typeof entry!=="object")&&leadingWidth+compact.length+1<=100){return compact}return["[",...value3.map((entry)=>`${pad2(indent+2)}${encodeTs(entry,indent+2)},`),`${pad2(indent)}]`].join(`
|
|
314
|
+
`).at(-1)??"";const line=result3.timedOut?none2():decodeProbeLine(lastLine);if(isNone2(line)){const failure=commandFailureDetail("load probe",result3,timeoutMs);return{ok:false,reason:result3.exitCode===0?`${failure} (unreadable probe output)`:failure,tsconfig}}const{files,ok,reason}=line.value;return{ok,tsconfig,...files===undefined?{}:{files},...ok||reason===undefined?{}:{reason}}};var probeCompilerProjects=({concurrency=4,env,projectRoot,run:run6=runCommand,runtimePath,timeoutMs=60000,tsconfigs})=>forEach2(tsconfigs,(tsconfig)=>run6({args:["--input-type=module","-e",probeScript,projectRoot,tsconfig],command:"node",cwd:runtimePath,env,timeoutMs}).pipe(map6((result3)=>probeResult(tsconfig,result3,timeoutMs))),{concurrency});var typegraphRuntimeItem="typegraph-runtime";var codexConfigPath=".codex/config.toml";var byTsconfig=(left,right)=>Number(left.tsconfig>right.tsconfig)-Number(left.tsconfig<right.tsconfig);var compilerProjectStatuses=({env,override,probeTimeoutMs,root,run:run6,runtimePath,wikiRoot})=>gen2(function*statuses(){const discovery=yield*discoverCompilerProjects({override,root,wikiRoot});const probes=runtimePath===undefined?undefined:yield*probeCompilerProjects({env,projectRoot:root,runtimePath,tsconfigs:discovery.projects.map((project)=>project.tsconfig),...run6===undefined?{}:{run:run6},...probeTimeoutMs===undefined?{}:{timeoutMs:probeTimeoutMs}});const probed=discovery.projects.map(({server,tsconfig},index)=>{const probe=probes?.[index];if(probe?.ok===true){return{probe:"pass",server,tsconfig,...probe.files===undefined?{}:{files:probe.files}}}const reason=probes===undefined?"not probed: Tool Runtime not installed":probe?.reason??"load probe failed";return{probe:"fail",reason,server,tsconfig}});const ambiguous=discovery.ambiguous.map(({reason,tsconfig})=>({probe:"ambiguous",reason,tsconfig}));return{excluded:discovery.excluded,projects:[...probed,...ambiguous].toSorted(byTsconfig)}});var filesystem=(run6)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:codexConfigPath}),try:run6});var filesystemError=(cause)=>new InstallerFilesystemError({detail:platformFailure(cause),path:codexConfigPath});var readCodexFile=(root)=>gen2(function*readCodex(){const fs=yield*FileSystem;const absolute=yield*filesystem(()=>confined(root,codexConfigPath));if(isSome2(yield*option2(fs.readLink(absolute)))){return{kind:"other"}}const stat3=yield*fs.stat(absolute).pipe(asSome2,catchIf2((error2)=>error2.reason._tag==="NotFound",()=>succeedNone2),mapError3(filesystemError));if(isNone2(stat3)){return{kind:"absent"}}if(stat3.value.type!=="File"){return{kind:"other"}}const content=yield*fs.readFileString(absolute).pipe(mapError3(filesystemError));return{content,kind:"file"}}).pipe(provide4(platformLayer));var readRegisteredServers=(root)=>readCodexFile(root).pipe(map6((file5)=>file5.kind==="file"?readTypegraphBlock(file5.content):[]));var applyCodexBlock=(root,block)=>gen2(function*apply2(){const file5=yield*readCodexFile(root);if(file5.kind==="other"){return{codexConfig:"unchanged",conflicts:block===""?[]:[`${codexConfigPath} is not a regular file; left untouched`]}}const existing=file5.kind==="file"?file5.content:undefined;const next=applyTypegraphBlock(existing,block);if(!next.changed||next.content===undefined){return{codexConfig:"unchanged",conflicts:next.conflicts}}const{content}=next;yield*filesystem(()=>{writeFileAtomic(confined(root,codexConfigPath),content)});return{codexConfig:readTypegraphBlock(content).length===0?"removed":"written",conflicts:next.conflicts}});var syncSemanticReads=({env,override,root,run:run6,runtime,wikiRoot})=>gen2(function*sync4(){if(runtime===undefined){const removed=yield*applyCodexBlock(root,"");return{...removed,excluded:[],projects:[],runtime:{status:"not-selected"}}}const outcome=yield*ensureToolRuntime({env,spec:runtime,...run6===undefined?{}:{run:run6}});if(outcome._tag==="Unavailable"){const removed=yield*applyCodexBlock(root,"");return{...removed,excluded:[],projects:[],runtime:{reason:outcome.reason,status:"unavailable"}}}const{excluded,projects}=yield*compilerProjectStatuses({env,override,root,run:run6,runtimePath:outcome.path,wikiRoot});const passing=projects.flatMap((project)=>project.probe==="pass"?[{server:project.server,tsconfig:project.tsconfig}]:[]);const applied=yield*applyCodexBlock(root,renderTypegraphBlock({projects:passing,version:runtime.version}));return{...applied,excluded,projects,runtime:{path:outcome.path,status:outcome._tag==="Reused"?"reused":"installed"}}});var antiSlopRules={"anti-slop/no-chained-type-assertions":"error","anti-slop/no-conditional-empty-object-spread":"error","anti-slop/no-known-value-widening":"error","anti-slop/no-module-mocking":"error","anti-slop/no-object-parameters":"error","anti-slop/no-reflect-apply":"error","anti-slop/no-reflect-get":"error","anti-slop/no-runtime-typeof":"error","anti-slop/no-shape-in-symbol-names":"error","anti-slop/no-unknown-parameters":"error","anti-slop/no-unknown-returns":"error","anti-slop/no-unknown-type-aliases":"error","anti-slop/no-unsafe-dictionary-type":"error","anti-slop/no-widen-then-assert":"error","anti-slop/require-safety-comment-for-type-assertion":"error"};var sharedReactPlacement={placementNotes:"Add as an override for detected React-rendered code. Keep backend packages outside this override unless they render React.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-react-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected React workspaces"]};var webOnlyPlacement={placementNotes:"Place this in the Next.js app override. If the repo uses a different frontend app path, retarget the file globs to that workspace before composing the final Oxlint config.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-nextjs-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Next.js workspaces"]};var effectPlacement={placementNotes:"Apply this only where Effect code lives. If the target repo renames or splits backend workspaces, move the override with those code paths instead of broadening it repo-wide.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-effect-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Effect workspaces"]};var vitestPlacement={placementNotes:"Attach this to test-only globs. Expand or narrow the file patterns to match the repo's actual Vitest test layout instead of treating it as a global default.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-test-workspace>/**/*.{test,spec}.{js,jsx,ts,tsx}","<detected-test-workspace>/src/test/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript/TypeScript test workspaces"]};var lintCatalog=[{description:"Vendored Anti-Slop rules for rejecting low-evidence TypeScript and JavaScript patterns.",id:"typescript-anti-slop",ignorePatterns:["tools/oxlint/anti-slop/**"],jsPlugins:[{name:"anti-slop",specifier:"./tools/oxlint/anti-slop/index.mjs"}],oxlintPresets:[],placement:{placementNotes:"Apply to JavaScript and TypeScript workspaces.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript and TypeScript workspaces"]},plugins:[],requiredDevDependencies:["@oxlint/plugins"],requiredDevDependencyVersions:{"@oxlint/plugins":"1.90.0"},rules:antiSlopRules,settings:{},sourceFiles:[{sourcePath:"lint/anti-slop/index.mjs",targetPath:"tools/oxlint/anti-slop/index.mjs"},{sourcePath:"lint/anti-slop/LICENSE",targetPath:"tools/oxlint/anti-slop/LICENSE"}]},{description:"Explicit Anti-Slop adoption policy for existing Harness workspaces.",id:"punks-anti-slop-transition",jsPlugins:[],oxlintPresets:[],placement:{placementNotes:"Apply only to existing Harness workspaces while they adopt Anti-Slop.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["Harness workspaces"]},plugins:[],requiredDevDependencies:[],rules:Object.fromEntries(Object.keys(antiSlopRules).map((rule)=>[rule,"off"])),settings:{},targetPackageNames:["@punks/api","@punks/auth","@punks/backoffice","@punks/cli","@punks/config","@punks/contract","@punks/db","@punks/env","@punks/scaffold","@punks/ui","@punks/web","@punks/wiki"]},{categories:{correctness:"error"},description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:["react"],requiredDevDependencies:[],rules:{},settings:{}},{description:"React Hooks lint rules via the JS plugin bridge for Oxlint.",id:"react-hooks",jsPlugins:[{name:"react-hooks-js",specifier:"eslint-plugin-react-hooks"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-hooks"],requiredDevDependencyVersions:{"eslint-plugin-react-hooks":"7.1.1"},rules:Object.fromEntries([["react-hooks-js/exhaustive-deps","error"],["react-hooks-js/component-hook-factories","error"],["react-hooks-js/config","error"],["react-hooks-js/error-boundaries","error"],["react-hooks-js/gating","error"],["react-hooks-js/globals","error"],["react-hooks-js/immutability","error"],["react-hooks-js/incompatible-library","error"],["react-hooks-js/preserve-manual-memoization","error"],["react-hooks-js/purity","error"],["react-hooks-js/refs","error"],["react-hooks-js/rules-of-hooks","error"],["react-hooks-js/set-state-in-effect","error"],["react-hooks-js/set-state-in-render","error"],["react-hooks-js/static-components","error"],["react-hooks-js/unsupported-syntax","error"],["react-hooks-js/use-memo","error"]]),settings:{}},{description:"Guidance rules that push React code away from unnecessary effects.",id:"react-you-might-not-need-an-effect",jsPlugins:[{name:"react-you-might-not-need-an-effect-js",specifier:"eslint-plugin-react-you-might-not-need-an-effect"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-you-might-not-need-an-effect"],requiredDevDependencyVersions:{"eslint-plugin-react-you-might-not-need-an-effect":"1.0.2"},rules:{"react-you-might-not-need-an-effect-js/no-adjust-state-on-prop-change":"error","react-you-might-not-need-an-effect-js/no-chain-state-updates":"error","react-you-might-not-need-an-effect-js/no-derived-state":"error","react-you-might-not-need-an-effect-js/no-event-handler":"error","react-you-might-not-need-an-effect-js/no-initialize-state":"error","react-you-might-not-need-an-effect-js/no-pass-data-to-parent":"error","react-you-might-not-need-an-effect-js/no-pass-live-state-to-parent":"error","react-you-might-not-need-an-effect-js/no-reset-all-state-on-prop-change":"error"},settings:{}},{description:"First-party frontend-domain-structure rules enforcing the layer model: routes, composition, features, modules, integrations, ui.",id:"react-frontend-layers",ignorePatterns:["tools/oxlint/frontend-layers/**"],jsPlugins:[{name:"frontend-layers",specifier:"./tools/oxlint/frontend-layers/index.mjs"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["@oxlint/plugins"],requiredDevDependencyVersions:{"@oxlint/plugins":"1.90.0"},rules:{"frontend-layers/known-top-level":"error","frontend-layers/layer-order":"error","frontend-layers/no-peer-feature":"error","frontend-layers/no-prototype-folder":"error","frontend-layers/public-entrypoint":"error","frontend-layers/route-imports":"error","frontend-layers/ui-placement":"error"},settings:{},sourceFiles:[{sourcePath:"lint/frontend-layers/index.mjs",targetPath:"tools/oxlint/frontend-layers/index.mjs"}]},{description:"Ultracite Next.js preset for the main web application.",id:"next-core",jsPlugins:[],oxlintPresets:["next"],placement:{...webOnlyPlacement,placementNotes:"Place this beside the React app override and set `settings.next.rootDir` to the repo's actual Next workspace roots if the final config needs that plugin setting."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Leafmost-Suspense rule from @punks/lints/next: with cacheComponents on, each data read gets its own <Suspense> at the leaf.",id:"next-leafmost-suspense",jsPlugins:[{name:"punks-next",specifier:"@punks/lints/next"}],oxlintPresets:[],placement:webOnlyPlacement,plugins:[],requiredDevDependencies:["@punks/lints"],requiredDevDependencyVersions:{"@punks/lints":"0.1.0"},rules:{"punks-next/leafmost-suspense":"error"},settings:{}},{description:"Ultracite TanStack preset for query/router/start framework linting.",id:"tanstack-query-core",jsPlugins:[],oxlintPresets:["tanstack"],placement:{...webOnlyPlacement,placementNotes:"Scope this to client code that owns TanStack Query usage. Keep it out of server-only or shared non-query packages unless those paths actually create queries or mutations."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Effect architectural rule that blocks barrel-package imports.",id:"effect-no-barrel-imports",jsPlugins:[{name:"effect-js",specifier:"@effect/eslint-plugin"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/eslint-plugin","@typescript-eslint/utils","eslint"],requiredDevDependencyVersions:{"@effect/eslint-plugin":"0.3.2","@typescript-eslint/utils":"8.22.0",eslint:"9.39.5"},rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},settings:{}},{description:"Effect tsgo recommended type-aware Oxlint rules.",id:"effect-tsgo-recommended",jsPlugins:[],oxlintConfigExtensions:[{exportName:"recommended",specifier:"@effect/tsgo/oxlint-presets"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/tsgo","oxlint-tsgolint"],requiredDevDependencyVersions:{"@effect/tsgo":"0.63.0",oxfmt:"0.72.0",oxlint:"1.90.0","oxlint-tsgolint":"7.0.2005",ultracite:"7.12.4"},rules:{},settings:{}},{description:"Ultracite Vitest preset for repo-owned test globs.",id:"vitest-core",jsPlugins:[],oxlintPresets:["vitest"],placement:vitestPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Canonical lint policy for the shipped Harness CLI package.",id:"punks-cli-canonical",ignorePatterns:["src/data/lint/anti-slop/**","src/data/hooks/format-edited-file-core.mjs","src/data/hooks/format-edited-file.mjs","src/data/hooks/scaffold-update-check.mjs"],jsPlugins:[],oxlintPresets:[],placement:{placementNotes:"Apply only to the exact @punks/cli package.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["@punks/cli"]},plugins:[],requiredDevDependencies:[],rules:{},settings:{},targetPackageNames:["@punks/cli"]},{description:"Canonical lint exceptions for the Harness backoffice package.",id:"punks-backoffice-canonical",jsPlugins:[],oxlintPresetRules:{vitest:{"vitest/prefer-import-in-mock":"off","vitest/prefer-importing-vitest-globals":"off"}},oxlintPresets:[],placement:{placementNotes:"Apply only to the exact @punks/backoffice package.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["@punks/backoffice"]},plugins:[],requiredDevDependencies:[],rules:{"eslint/func-style":"off"},settings:{},targetPackageNames:["@punks/backoffice"]}];import{existsSync as existsSync6,readdirSync,readFileSync as readFileSync6}from"node:fs";import path10 from"node:path";import{spawnSync as spawnSync2}from"node:child_process";import nodeModule from"node:module";import{isDeepStrictEqual}from"node:util";import{runInNewContext}from"node:vm";var lintItemPrefix="lint-";var packItemPrefix="pack-";var selectionPath=".devpunks/specs/lint/selection.json";var settingsPath2=".devpunks/settings.json";var lintToolchain={oxfmt:"0.72.0",oxlint:"1.90.0",ultracite:"7.12.4"};var lintAssetSpecPath=(assetId)=>`lint/${assetId}/asset.json`;var JsPlugin=Struct({name:String4,specifier:String4});var UnknownRecord=Record(String4,Unknown2);var LintAssetSpec=Struct({categories:optional(UnknownRecord),description:String4,id:String4,ignorePatterns:optional(ArraySchema(String4)),jsPlugins:ArraySchema(JsPlugin),oxlintConfigExtensions:optional(ArraySchema(Struct({exportName:String4,specifier:String4}))),oxlintPresetRules:optional(Record(String4,UnknownRecord)),oxlintPresets:ArraySchema(String4),plugins:ArraySchema(String4),requiredDevDependencies:ArraySchema(String4),requiredDevDependencyVersions:optional(Record(String4,String4)),rules:UnknownRecord,settings:UnknownRecord,targetPackageNames:optional(ArraySchema(String4))});var decodeSpec=decodeUnknownSync(fromJsonString2(LintAssetSpec));var isRecord2=(value3)=>typeof value3==="object"&&value3!==null&&!Array.isArray(value3);var uniqueSorted=(values)=>[...new Set(values)].toSorted();var intersects=(left,right)=>left.some((value3)=>right.includes(value3));var installedAssets=(context3)=>context3.items.filter((item)=>item.meta.hi.kind==="lint"&&item.name.startsWith(lintItemPrefix)).flatMap((item)=>{const assetId=item.name.slice(lintItemPrefix.length);const file5=item.files?.find((entry)=>entry.path===lintAssetSpecPath(assetId));return file5===undefined?[]:[{assetId,content:file5.content,item}]}).map(({content,item})=>({packs:context3.items.filter((pack)=>pack.meta.hi.kind==="pack"&&pack.registryDependencies?.includes(item.name)===true),spec:decodeSpec(content)})).toSorted((left,right)=>left.spec.id.localeCompare(right.spec.id));var packApplies=(pack,scope3)=>{const technologies=pack.meta.hi.pack?.technologies??[];const languages=pack.meta.hi.pack?.languages??[];return technologies.length===0&&languages.length===0||intersects(technologies,scope3.technologies)||intersects(languages,scope3.languages)};var scopeAssets=(context3,scope3)=>installedAssets(context3).filter(({packs,spec})=>spec.targetPackageNames===undefined?packs.some((pack)=>packApplies(pack,scope3)):spec.targetPackageNames.includes(scope3.name??"")).map(({spec})=>spec).toSorted((left,right)=>Number(left.targetPackageNames!==undefined)-Number(right.targetPackageNames!==undefined));var scopeWorkspace=(context3,scopePath)=>context3.shape.workspaces.find((workspace)=>workspace.path===scopePath)??{languages:[],path:scopePath,technologies:[]};var requireScope=(scope3)=>{if(scope3===undefined){throw new Error("oxlint-config and oxlint-local render once per Software Scope; expand them over softwareScopes.")}return scope3};var requiredDevDependencies=(assets)=>uniqueSorted([...Object.keys(lintToolchain),...assets.flatMap((asset)=>asset.requiredDevDependencies)]);var ultraciteCorePreset="core";var rawTs=(source)=>({rawTs:source});var isRawTs=(value3)=>isRecord2(value3)&&typeof value3.rawTs==="string"&&Object.keys(value3).length===1;var tsPropertyKey=(key)=>/^[A-Z_$][\w$]*$/iu.test(key)?key:JSON.stringify(key);var pad2=(width)=>" ".repeat(width);var encodeTs=(value3,indent=0,leadingWidth=indent)=>{if(isRawTs(value3)){return value3.rawTs}if(Array.isArray(value3)){if(value3.length===0){return"[]"}const compact=`[${value3.map((entry)=>JSON.stringify(entry)).join(", ")}]`;if(value3.every((entry)=>entry===null||typeof entry!=="object")&&leadingWidth+compact.length+1<=100){return compact}return["[",...value3.map((entry)=>`${pad2(indent+2)}${encodeTs(entry,indent+2)},`),`${pad2(indent)}]`].join(`
|
|
315
315
|
`)}if(isRecord2(value3)){const keys2=Object.keys(value3).toSorted();if(keys2.length===0){return"{}"}return["{",...keys2.map((key)=>{const prefix3=`${pad2(indent+2)}${tsPropertyKey(key)}: `;return`${prefix3}${encodeTs(value3[key],indent+2,prefix3.length)},`}),`${pad2(indent)}}`].join(`
|
|
316
316
|
`)}return JSON.stringify(value3)??"undefined"};var pascalCase=(value3)=>value3.replaceAll(/[^a-zA-Z0-9]+/gu," ").split(" ").map((segment)=>segment.charAt(0).toUpperCase()+segment.slice(1)).join("");var presetName=(preset)=>preset===ultraciteCorePreset?"core":`ultracite${pascalCase(preset)}`;var pluginAlias=(plugin,scopePath)=>scopePath==="."||!plugin.specifier.startsWith("./tools/oxlint/")?plugin.name:`${plugin.name}-${scopePath.replaceAll(/[^A-Za-z0-9_$]/gu,"-")}`;var configExtensions=(assets,presets)=>{const reserved=new Set(["defineConfig","OxlintConfig","managed","project","projectConfig",...presets.flatMap((preset)=>{const name=presetName(preset);return[name,`${name}LocalRules`,`${name}WithLocalRules`]})]);const unique=new Map(assets.flatMap((asset)=>asset.oxlintConfigExtensions??[]).map((extension)=>[`${extension.specifier}:${extension.exportName}`,extension]));return[...unique.values()].map((extension)=>{const parts=extension.specifier.split("/");const packageName=pascalCase((extension.specifier.startsWith("@")?parts.slice(0,2):parts.slice(0,1)).join(" "));const derived=`${packageName.charAt(0).toLowerCase()}${packageName.slice(1)}${pascalCase(extension.exportName)}`;const base=/^[A-Za-z_$]/u.test(derived)?derived:`_${derived}`;let localName=base;for(let suffix=2;reserved.has(localName);suffix+=1){localName=`${base}${suffix}`}reserved.add(localName);return{...extension,localName}})};var builtinRulePlugins=new Set(["@next/next","@typescript-eslint","deepscan","effecttsgo","eslint","import","import-x","jest","jsdoc","jsx-a11y","jsx_a11y","nextjs","node","oxc","promise","react","react-hooks","react-perf","react_perf","typescript","typescript-eslint","unicorn","vitest","vue"]);var rulePlugin=(rule)=>{const slash=rule.lastIndexOf("/");return slash===-1?undefined:rule.slice(0,slash)};var resolvableRules=(rules,aliases)=>Object.fromEntries(Object.entries(rules).filter(([rule])=>{const plugin=rulePlugin(rule);return plugin===undefined||builtinRulePlugins.has(plugin)||aliases.has(plugin)}));var managedHomePatterns=[".agents/**",".claude/**",".codex/**",".cursor/**",".devpunks-cache/**",".devpunks/**",".opencode/**","opensrc/**"];var managedPolicy=(assets,scopePath)=>{const plugins=[];const jsPlugins=[];const settings={};const rules={};const categories={};const rulePlugins=assets.flatMap((asset)=>asset.jsPlugins);for(const asset of assets){Object.assign(categories,asset.categories??{});plugins.push(...asset.plugins);for(const plugin of asset.jsPlugins){const entry={name:pluginAlias(plugin,scopePath),specifier:plugin.specifier};if(!jsPlugins.some((existing)=>existing.name===entry.name)){jsPlugins.push(entry)}}for(const[key,value3]of Object.entries(asset.settings)){settings[key]??=value3}for(const[key,value3]of Object.entries(asset.rules)){const plugin=rulePlugins.find((candidate)=>key.startsWith(`${candidate.name}/`));const name=plugin===undefined?key:`${pluginAlias(plugin,scopePath)}${key.slice(plugin.name.length)}`;rules[name]=value3}}return{categories,ignorePatterns:uniqueSorted([".devpunks/**",...scopePath==="."?managedHomePatterns:[],...assets.flatMap((asset)=>asset.ignorePatterns??[])]),jsPlugins,plugins:uniqueSorted(plugins),rules:resolvableRules(rules,new Set(jsPlugins.map((plugin)=>plugin.name))),settings}};var projectConfigFile="oxlint.local.ts";var renderMergedConfigEntry=(key)=>["jsPlugins","plugins"].includes(key)?` ${key}: [...managed.${key}, ...(project.${key} ?? [])],`:` ${key}: { ...managed.${key}, ...project.${key} },`;var scopePresets=(assets)=>uniqueSorted([ultraciteCorePreset,...assets.flatMap((asset)=>asset.oxlintPresets)]);var builtHeader="// Built by hi update from the selected lint assets; local edits are overwritten.";var isBuiltConfig=(source)=>source.includes(builtHeader);var renderOxlintConfig=(assets,scopePath)=>{const presets=scopePresets(assets);const extensions=configExtensions(assets,presets);const presetRules={};for(const asset of assets){for(const[preset,overrides]of Object.entries(asset.oxlintPresetRules??{})){presetRules[preset]={...presetRules[preset],...overrides}}}const policy=managedPolicy(assets,scopePath);const presetRuleSources=presets.flatMap((preset)=>{const overrides=presetRules[preset];if(overrides===undefined){return[]}const name=presetName(preset);return[`const ${name}LocalRules = ${encodeTs(resolvableRules(overrides,new Set))} satisfies OxlintConfig["rules"];`,"",`const ${name}WithLocalRules = {`,` ...${name},`,` overrides: (${name}.overrides ?? []).map((override) => ({`," ...override,"," rules: {"," ...override.rules,",` ...${name}LocalRules,`," },"," })),","};",""]});const managed={...Object.keys(policy.categories).length>0?{categories:policy.categories}:{},...policy.jsPlugins.length>0?{jsPlugins:policy.jsPlugins}:{},...policy.plugins.length>0?{plugins:policy.plugins}:{},...Object.keys(policy.rules).length>0?{rules:policy.rules}:{},...Object.keys(policy.settings).length>0?{settings:policy.settings}:{}};const extendsEntries=[...presets.map((preset)=>presetRules[preset]===undefined?presetName(preset):`${presetName(preset)}WithLocalRules`),...extensions.map(({localName})=>localName),"...(project.extends ?? [])"];const managedKeys=Object.keys(managed);const extendsLine=` extends: [${extendsEntries.join(", ")}],`;return[builtHeader,`// Project lint rules belong in ${projectConfigFile}, which applies last and is never overwritten.`,'import type { OxlintConfig } from "oxlint";','import { defineConfig } from "oxlint";',...presets.map((preset)=>`import ${presetName(preset)} from "ultracite/oxlint/${preset}";`),...extensions.map(({exportName,localName,specifier})=>`import { ${exportName} as ${localName} } from ${JSON.stringify(specifier)};`),"",`import projectConfig from "./${projectConfigFile}";`,"",...presetRuleSources,...managedKeys.length>0?[`const managed = ${encodeTs(managed)} satisfies OxlintConfig;`,""]:[],"const project: OxlintConfig = projectConfig;","","export default defineConfig({"," ...project,",...managedKeys.includes("categories")?[renderMergedConfigEntry("categories")]:[],...extendsLine.length<=100?[extendsLine]:[" extends: [",...extendsEntries.map((entry)=>` ${entry},`)," ],"]," ignorePatterns: ["," ...(core.ignorePatterns ?? []),",...policy.ignorePatterns.map((pattern)=>` ${JSON.stringify(pattern)},`)," ...(project.ignorePatterns ?? []),"," ],",...managedKeys.filter((key)=>key!=="categories").map(renderMergedConfigEntry),"});",""].join(`
|
|
317
317
|
`)};var importPattern=/^[ \t]*import\s+(?<typeOnly>type\s+)?(?<bindings>[^;]*?)\s+from\s+["'](?<specifier>[^"']+)["'];?[ \t]*$/gmu;var listParts=(list2)=>list2.split(",").map((part)=>part.trim()).filter((part)=>part.length>0&&!part.startsWith("type "));var importBindings=(source)=>[...source.matchAll(importPattern)].flatMap((match8)=>{const{bindings="",specifier="",typeOnly}=match8.groups??{};if(typeOnly!==undefined){return[]}const from=` from ${JSON.stringify(specifier)};`;const named=/\{(?<names>[^}]*)\}/u.exec(bindings)?.groups?.names??"";return[...listParts(bindings.replace(/\{[^}]*\}/u,"")).map((part)=>{const local=/^\*\s+as\s+(?<local>[\w$]+)$/u.exec(part)?.groups?.local;return local===undefined?{local:part,specifier,statement:`import ${part}${from}`}:{local,specifier,statement:`import * as ${local}${from}`}}),...listParts(named).map((part)=>({local:part.split(/\s+as\s+/u).at(-1)??part,specifier,statement:`import { ${part.replaceAll(/\s+/gu," ")} }${from}`}))]});var importMarker="__hiImport";var stripTypes=(source)=>{const bun=Reflect.get(globalThis,"Bun");const{stripTypeScriptTypes}=nodeModule;try{if(bun===undefined){return stripTypeScriptTypes?.(source)}if(typeof bun!=="object"||bun===null){return}const Transpiler=Reflect.get(bun,"Transpiler");if(typeof Transpiler!=="function"){return}const instance=Reflect.construct(Transpiler,[{loader:"ts"}]);if(typeof instance!=="object"||instance===null){return}const transformSync=Reflect.get(instance,"transformSync");if(typeof transformSync!=="function"){return}const transformed=Reflect.apply(transformSync,instance,[source]);return typeof transformed==="string"?transformed:undefined}catch{return}};var evaluateConfig=(source,bindings)=>{const evaluate2=(code)=>{const globals=Object.fromEntries(bindings.map(({local})=>[local,{ignorePatterns:[],overrides:[],[importMarker]:local}]));globals.defineConfig=(config)=>config;const script=code.replaceAll(importPattern,"").replaceAll(/\s+satisfies\s+[\w$.]+(?:\[[^\]]*\])*/gu,"").replace(/\bexport\s+default\s+/u,"globalThis.exported = ");try{runInNewContext(script,globals,{timeout:1000});const serialized=JSON.stringify(globals.exported??null);const normalized=JSON.parse(serialized??"null");const exported=structuredClone(normalized);return isRecord2(exported)?exported:undefined}catch{return}};const plain=evaluate2(source);if(plain!==undefined){return plain}const stripped=stripTypes(source);return stripped===undefined?undefined:evaluate2(stripped)};var isOff=(value3)=>{const severity=Array.isArray(value3)?value3[0]:value3;return severity==="off"||severity===0};var jsPluginName=(plugin)=>{if(typeof plugin==="string"){return plugin}return isRecord2(plugin)&&typeof plugin.name==="string"?plugin.name:undefined};var withoutManaged=(values,managed)=>Object.fromEntries(Object.entries(values).filter(([key,value3])=>!isDeepStrictEqual(managed[key],value3)));var projectPolicy=(existing,managed)=>{const{$schema:_schema,categories,extends:_extends,ignorePatterns,jsPlugins,overrides,plugins,rules,settings,[importMarker]:_import,...rest}=existing;const declared=Array.isArray(jsPlugins)?jsPlugins:[];const managedAliases=new Set(managed.jsPlugins.map((plugin)=>plugin.name));const used=new Set;const keep=(values,aliases2)=>{const kept=Object.entries(resolvableRules(isRecord2(values)?values:{},aliases2)).filter(([rule,value3])=>{const plugin=rulePlugin(rule);return plugin===undefined||builtinRulePlugins.has(plugin)||!isOff(value3)||managedAliases.has(plugin)});for(const[rule]of kept){used.add(rulePlugin(rule)??"")}return Object.fromEntries(kept)};const aliases=new Set(declared.flatMap((plugin)=>jsPluginName(plugin)??[]));const projectRules=keep(withoutManaged(isRecord2(rules)?rules:{},managed.rules),aliases);const projectOverrides=(Array.isArray(overrides)?overrides:[]).map((override)=>{if(!isRecord2(override)){return override}const own=Array.isArray(override.jsPlugins)?override.jsPlugins:[];const scoped4=new Set([...aliases,...own.flatMap((plugin)=>jsPluginName(plugin)??[])]);return override.rules===undefined?override:{...override,rules:keep(override.rules,scoped4)}});const projectCategories=withoutManaged(isRecord2(categories)?categories:{},managed.categories);const projectSettings=withoutManaged(isRecord2(settings)?settings:{},managed.settings);const projectPlugins=(Array.isArray(plugins)?plugins:[]).filter((plugin)=>!managed.plugins.includes(String(plugin)));const projectJsPlugins=declared.filter((plugin)=>used.has(jsPluginName(plugin)??""));const projectIgnores=(Array.isArray(ignorePatterns)?ignorePatterns:[]).filter((pattern)=>!managed.ignorePatterns.includes(String(pattern)));return{...rest,...Object.keys(projectCategories).length>0?{categories:projectCategories}:{},...projectIgnores.length>0?{ignorePatterns:projectIgnores}:{},...projectJsPlugins.length>0?{jsPlugins:projectJsPlugins}:{},...projectOverrides.length>0?{overrides:projectOverrides}:{},...projectPlugins.length>0?{plugins:projectPlugins}:{},rules:projectRules,...Object.keys(projectSettings).length>0?{settings:projectSettings}:{}}};var projectExtends=(entries,bindings,assets)=>{const managed=new Set([...scopePresets(assets).map((preset)=>`ultracite/oxlint/${preset}`),...assets.flatMap((asset)=>asset.oxlintConfigExtensions??[]).map((extension)=>extension.specifier)]);return(Array.isArray(entries)?entries:[]).flatMap((entry)=>{const local=isRecord2(entry)?entry[importMarker]:undefined;if(typeof local!=="string"){return[{entry,imports:[]}]}const binding=bindings.find((candidate)=>candidate.local===local);return binding===undefined||managed.has(binding.specifier)?[]:[{entry:rawTs(local),imports:[binding.statement]}]})};var preservedConfig=(source)=>["// Preserved verbatim from the previous oxlint.config.ts, which hi could not evaluate.","// The Built oxlint.config.ts applies the managed presets and rules; keep only project policy here.",source].join(`
|
|
318
318
|
`);function renderOxlintLocal(policy,imports=[]){return['import { defineConfig } from "oxlint";',...imports,"","// Project-owned lint rules for this Software Scope. hi writes this file once and never changes it.",`export default defineConfig(${policy===undefined?"{ rules: {} }":encodeTs(policy)});`,""].join(`
|
|
319
|
-
`)}var adoptConfig=(source,assets,scopePath)=>{const bindings=importBindings(source);const existing=evaluateConfig(source,bindings);if(existing===undefined){return preservedConfig(source)}const kept=projectExtends(existing.extends,bindings,assets);return renderOxlintLocal({...projectPolicy(existing,managedPolicy(assets,scopePath)),...kept.length>0?{extends:kept.map(({entry})=>entry)}:{}},[...new Set(kept.flatMap(({imports})=>imports))])};var routeInputs=(scopePath,config,assets)=>uniqueSorted([settingsPath2,selectionPath,"package.json","bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","pnpm-workspace.yaml","yarn.lock",config,scopePath==="."?projectConfigFile:`${scopePath}/${projectConfigFile}`,scopePath==="."?"package.json":`${scopePath}/package.json`,...assets.flatMap((asset)=>asset.jsPlugins.filter((plugin)=>plugin.specifier.startsWith("./")).map((plugin)=>scopePath==="."?plugin.specifier.slice(2):`${scopePath}/${plugin.specifier.slice(2)}`))]);var scopePaths=(context3)=>uniqueSorted(context3.settings.softwareScopes);var lintSelection=async({context:context3})=>{const scopes=scopePaths(context3);const assetsByScope=scopes.map((scopePath)=>({assets:scopeAssets(context3,scopeWorkspace(context3,scopePath)),scopePath}));const routes=assetsByScope.map(({assets,scopePath})=>{const config=scopePath==="."?"oxlint.config.ts":`${scopePath}/oxlint.config.ts`;return{config,inputs:routeInputs(scopePath,config,assets),maxWarnings:0,scope:scopePath,tool:{package:"oxlint"}}});const selection={finalPacks:uniqueSorted(context3.settings.packs),managedLint:{exclude:[...context3.settings.lintExclude],routes,scopes,version:1},requiredDevDependencies:requiredDevDependencies(assetsByScope.flatMap(({assets})=>assets)),selectedAssetIds:installedAssets(context3).map(({spec})=>spec.id),selectedAssetsByScope:Object.fromEntries(assetsByScope.map(({assets,scopePath})=>[scopePath,assets.map((asset)=>asset.id)]))};return await Promise.resolve({json:canonicalJson(selection)})};var codeList=(values)=>values.length===0?"(none)":values.map((value3)=>`\`${value3}\``).join(", ");var lintReadme=async({context:context3})=>{const assets=installedAssets(context3);return await Promise.resolve({assets:assets.map(({packs,spec})=>({dependencies:codeList(spec.requiredDevDependencies),description:spec.description,id:spec.id,packs:codeList(packs.map((pack)=>pack.name.slice(packItemPrefix.length)).toSorted()),presets:codeList(spec.oxlintPresets.map((preset)=>`ultracite/oxlint/${preset}`)),
|
|
319
|
+
`)}var adoptConfig=(source,assets,scopePath)=>{const bindings=importBindings(source);const existing=evaluateConfig(source,bindings);if(existing===undefined){return preservedConfig(source)}const kept=projectExtends(existing.extends,bindings,assets);return renderOxlintLocal({...projectPolicy(existing,managedPolicy(assets,scopePath)),...kept.length>0?{extends:kept.map(({entry})=>entry)}:{}},[...new Set(kept.flatMap(({imports})=>imports))])};var routeInputs=(scopePath,config,assets)=>uniqueSorted([settingsPath2,selectionPath,"package.json","bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","pnpm-workspace.yaml","yarn.lock",config,scopePath==="."?projectConfigFile:`${scopePath}/${projectConfigFile}`,scopePath==="."?"package.json":`${scopePath}/package.json`,...assets.flatMap((asset)=>asset.jsPlugins.filter((plugin)=>plugin.specifier.startsWith("./")).map((plugin)=>scopePath==="."?plugin.specifier.slice(2):`${scopePath}/${plugin.specifier.slice(2)}`))]);var scopePaths=(context3)=>uniqueSorted(context3.settings.softwareScopes);var lintSelection=async({context:context3})=>{const scopes=scopePaths(context3);const assetsByScope=scopes.map((scopePath)=>({assets:scopeAssets(context3,scopeWorkspace(context3,scopePath)),scopePath}));const routes=assetsByScope.map(({assets,scopePath})=>{const config=scopePath==="."?"oxlint.config.ts":`${scopePath}/oxlint.config.ts`;return{config,inputs:routeInputs(scopePath,config,assets),maxWarnings:0,scope:scopePath,tool:{package:"oxlint"}}});const selection={finalPacks:uniqueSorted(context3.settings.packs),managedLint:{exclude:[...context3.settings.lintExclude],routes,scopes,version:1},requiredDevDependencies:requiredDevDependencies(assetsByScope.flatMap(({assets})=>assets)),selectedAssetIds:installedAssets(context3).map(({spec})=>spec.id),selectedAssetsByScope:Object.fromEntries(assetsByScope.map(({assets,scopePath})=>[scopePath,assets.map((asset)=>asset.id)]))};return await Promise.resolve({json:canonicalJson(selection)})};var codeList=(values)=>values.length===0?"(none)":values.map((value3)=>`\`${value3}\``).join(", ");var lintReadme=async({context:context3})=>{const assets=installedAssets(context3);return await Promise.resolve({assets:assets.map(({packs,spec})=>({dependencies:codeList(spec.requiredDevDependencies),description:spec.description,id:spec.id,packs:codeList(packs.map((pack)=>pack.name.slice(packItemPrefix.length)).toSorted()),presets:codeList(spec.oxlintPresets.map((preset)=>`ultracite/oxlint/${preset}`)),targets:spec.targetPackageNames===undefined?"":codeList(spec.targetPackageNames)})),scopes:scopePaths(context3).map((scopePath)=>({assets:codeList(scopeAssets(context3,scopeWorkspace(context3,scopePath)).map((a)=>a.id)),path:scopePath})),toolchain:codeList(Object.entries(lintToolchain).map(([name,version2])=>`${name}@${version2}`))})};var oxlintConfig=async({context:context3,scope:scope3})=>{const workspace=requireScope(scope3);return await Promise.resolve({source:renderOxlintConfig(scopeAssets(context3,workspace),workspace.path)})};var committedFileReader=(root)=>(path9)=>{const result3=spawnSync2("git",["show",`HEAD:./${path9}`],{cwd:root,encoding:"utf-8",maxBuffer:16*1024*1024,stdio:["ignore","pipe","ignore"]});return result3.status===0?result3.stdout:undefined};var oxlintLocal=async({context:context3,scope:scope3})=>{const workspace=requireScope(scope3);const configPath=workspace.path==="."?"oxlint.config.ts":`${workspace.path}/oxlint.config.ts`;const current=context3.readRepositoryFile(configPath);const previous=current!==undefined&&isBuiltConfig(current)?context3.readCommittedFile?.(configPath):current;return await Promise.resolve({source:previous===undefined||isBuiltConfig(previous)?renderOxlintLocal():adoptConfig(previous,scopeAssets(context3,workspace),workspace.path)})};var lintBuilders={"lint-readme":lintReadme,"lint-selection":lintSelection,"oxlint-config":oxlintConfig,"oxlint-local":oxlintLocal};import{lstatSync,readFileSync as readFileSync5}from"node:fs";import path9 from"node:path";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";var isPlainObject2=(value3)=>value3!==null&&typeof value3==="object"&&!Array.isArray(value3);var runsCommand=(script,command)=>script.split("&&").some((segment)=>segment.trim()===command.trim());var mergeAt=(keys2,existing,value3)=>{if(isPlainObject2(value3)){const base=isPlainObject2(existing)?existing:{};const merged={...base};for(const[key,next]of Object.entries(value3)){merged[key]=mergeAt([...keys2,key],base[key],next)}return merged}if(keys2.length===2&&keys2[0]==="scripts"&&typeof existing==="string"&&typeof value3==="string"&&runsCommand(existing,value3)){return existing}if(Array.isArray(value3)){const base=Array.isArray(existing)?existing:[];const merged=[...base];for(const element of value3){if(!merged.some((present2)=>isDeepStrictEqual2(present2,element))){merged.push(element)}}return merged}return value3};var mergeValue=(existing,value3)=>mergeAt([],existing,value3);var parseJsonObject=(content)=>{const parsed=JSON.parse(content);if(!isPlainObject2(parsed)){throw new TypeError("Expected a JSON object at the top level")}return{...parsed}};var parseYamlDocument=(content)=>{const document=$parseDocument(content);const[error2]=document.errors;if(error2!==undefined){throw error2}if(document.contents!==null&&!$isMap(document.contents)){throw new TypeError("Expected a YAML mapping at the top level")}return document};var mergeYaml=(document,keys2,value3)=>{const node=keys2.length===0?document.contents:document.getIn(keys2,true);if(isPlainObject2(value3)&&($isMap(node)||keys2.length===0&&node===null)){let changed=false;for(const[key,next]of Object.entries(value3)){changed=mergeYaml(document,[...keys2,key],next)||changed}return changed}if(Array.isArray(value3)&&$isSeq(node)){const present2=node.toJSON();let changed=false;for(const element of value3){if(!present2.some((item)=>isDeepStrictEqual2(item,element))){node.add(document.createNode(element));present2.push(element);changed=true}}return changed}if(document.hasIn(keys2)&&isDeepStrictEqual2(document.getIn(keys2),value3)){return false}if(!isPlainObject2(value3)&&!Array.isArray(value3)){document.setIn(keys2,value3);return true}document.setIn(keys2,document.createNode(value3));return true};var packageJsonKeyOrder=["$schema","name","displayName","version","private","description","categories","keywords","homepage","bugs","repository","funding","license","author","maintainers","contributors","publisher","sideEffects","type","imports","exports","main","svelte","umd:main","jsdelivr","unpkg","module","source","jsnext:main","browser","react-native","types","typesVersions","typings","style","example","examplestyle","assets","bin","man","directories","files","workspaces","binary","scripts","betterScripts","contributes","activationEvents","husky","simple-git-hooks","pre-commit","commitlint","lint-staged","nano-staged","config","nodemonConfig","browserify","babel","browserslist","xo","prettier","eslintConfig","eslintIgnore","npmpackagejsonlint","release","remarkConfig","stylelint","ava","jest","jest-junit","jest-stare","mocha","nyc","c8","tap","oclif","resolutions","dependencies","devDependencies","dependenciesMeta","peerDependencies","peerDependenciesMeta","optionalDependencies","bundledDependencies","bundleDependencies","extensionPack","extensionDependencies","flat","packageManager","engines","engineStrict","volta","languageName","os","cpu","preferGlobal","publishConfig","icon","badges","galleryBanner","preview","markdown","pnpm"];var packageJsonKeyRank=(key)=>{const index=packageJsonKeyOrder.indexOf(key);return index===-1?packageJsonKeyOrder.length:index};var placePackageJsonKeys=(existing,next)=>{const keys2=Object.keys(existing).filter((key)=>(key in next));for(const key of Object.keys(next)){if(keys2.includes(key)){continue}const before=keys2.findIndex((present2)=>packageJsonKeyRank(present2)>packageJsonKeyRank(key));keys2.splice(before===-1?keys2.length:before,0,key)}return Object.fromEntries(keys2.map((key)=>[key,next[key]]))};var applyMerges=({content,format:format4,target,values})=>{if(format4==="json"){const existing=content===undefined?{}:parseJsonObject(content);let merged=existing;for(const value3 of values){merged=mergeValue(merged,value3)}if(content!==undefined&&isDeepStrictEqual2(merged,existing)){return content}const ordered=target!==undefined&&path9.posix.basename(target)==="package.json"&&isPlainObject2(merged)?placePackageJsonKeys(existing,merged):merged;return`${JSON.stringify(ordered,null,2)}
|
|
320
320
|
`}const document=content===undefined?new $Document:parseYamlDocument(content);let changed=false;for(const value3 of values){changed=mergeYaml(document,[],value3)||changed}return content!==undefined&&!changed?content:document.toString()};var validateMergeTarget=(root,target,format4)=>try_3({catch:(cause)=>new InvalidMergeTarget({detail:cause instanceof Error?cause.message:String(cause),path:target}),try:()=>{const absolute=confined(root,target);const stats=lstatSync(absolute,{throwIfNoEntry:false});if(stats===undefined){return}if(stats.isSymbolicLink()){throw new Error("the merge target is a symlink; replace it with a regular file")}const content=readFileSync5(absolute,"utf-8");if(format4==="json"){parseJsonObject(content)}else{parseYamlDocument(content)}}});var sections=["dependencies","devDependencies","peerDependencies","optionalDependencies"];var ignoredDirectories=new Set([".cache",".git",".next",".output",".turbo",".vercel","build","coverage","dist","node_modules","out"]);var sourceExtensions=/\.(?:[cm]?[jt]s|[jt]sx)$/u;var isRecord3=(value3)=>typeof value3==="object"&&value3!==null&&!Array.isArray(value3);var workspacePackageJson=(workspace)=>workspace==="."?"package.json":`${workspace}/package.json`;var unreproduciblePattern=/^(?:\*?|(?![vV]\d)[A-Za-z][\w.-]*)$/u;var isReproducibleRange=(range2)=>!unreproduciblePattern.test(range2.trim());var declaredRange=(manifest,name)=>{for(const section of sections){const entries=manifest[section];if(isRecord3(entries)&&name in entries){return entries[name]}}return};var unreproducibleRange=(manifest,name)=>{const range2=declaredRange(manifest,name);return typeof range2==="string"&&!isReproducibleRange(range2)?range2:undefined};var rangeFindingDetail=({name,range:range2,seed})=>`${name}: "${range2}" -> pin ${seed}`;var findUnreproducibleRanges=({root,seeds,workspaces})=>workspaces.flatMap((workspace)=>{let manifest;try{manifest=JSON.parse(readFileSync6(path10.join(root,workspacePackageJson(workspace)),"utf-8"))}catch{return[]}if(!isRecord3(manifest)){return[]}return[...seeds].flatMap(([name,seed])=>{const range2=unreproducibleRange(manifest,name);return range2===undefined?[]:[{name,range:range2,seed,workspace}]})});var escapeRegExp=(value3)=>value3.replaceAll(/[$()*+.?[\\\]^{|}]/gu,"\\$&");var importPattern2=(name)=>new RegExp(String.raw`(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(["'])${escapeRegExp(name)}(?:/[^"']*)?\1`,"u");var sourceFiles=(root,workspace,managedPaths)=>{const files=[];const visit2=(relativeDirectory)=>{const absolute=path10.join(root,relativeDirectory);for(const entry of readdirSync(absolute,{withFileTypes:true})){const relative=relativeDirectory==="."?entry.name:`${relativeDirectory}/${entry.name}`;if(entry.isDirectory()&&!ignoredDirectories.has(entry.name)){visit2(relative)}else if(entry.isFile()&&sourceExtensions.test(entry.name)&&!managedPaths.has(relative)){files.push(relative)}}};if(existsSync6(path10.join(root,workspace))){visit2(workspace)}return files.toSorted()};var findImporters=(root,workspace,names,managedPaths)=>{const importers=new Map;const patterns=names.map((name)=>[name,importPattern2(name)]);for(const file5 of sourceFiles(root,workspace,managedPaths)){const content=readFileSync6(path10.join(root,file5),"utf-8");for(const[name,pattern]of patterns){if(!importers.has(name)&&pattern.test(content)){importers.set(name,file5)}}if(importers.size===names.length){break}}return importers};var committedLacks=(committed,name)=>{if(committed===undefined){return false}let parsed;try{parsed=JSON.parse(committed)}catch{return false}return isRecord3(parsed)&&!sections.some((section)=>{const entries=parsed[section];return isRecord3(entries)&&name in entries})};var rootManifest=(root)=>{try{const parsed=JSON.parse(readFileSync6(path10.join(root,workspacePackageJson(".")),"utf-8"));return isRecord3(parsed)?parsed:{}}catch{return{}}};var planWorkspace=({managedPaths,readCommitted,recordedNames,required,root,rootRanges,workspace})=>{const manifestPath=workspacePackageJson(workspace);const absolute=path10.join(root,manifestPath);if(!existsSync6(absolute)){const rows2=required.map((dependency)=>({action:"skipped",artifact:"dependency",detail:`${dependency.name}: workspace has no package.json`,item:dependency.item,path:manifestPath}));return{recorded:[],rows:rows2,write:undefined}}const original=readFileSync6(absolute,"utf-8");const parsed=JSON.parse(original);if(!isRecord3(parsed)){throw new TypeError(`${manifestPath} is not a JSON object`)}const manifest={...parsed};const devDependencies=isRecord3(manifest.devDependencies)?{...manifest.devDependencies}:{};let committed;const addedBeforeCommit=(name)=>{if(readCommitted===undefined||!(name in devDependencies)){return false}committed??={text:readCommitted()};return committedLacks(committed.text,name)};const rows=[];const recorded=[];let changed=false;const requiredNames=new Set;for(const dependency of required){if(requiredNames.has(dependency.name)){continue}requiredNames.add(dependency.name);if(declaredRange(manifest,dependency.name)!==undefined){if(recordedNames.includes(dependency.name)&&dependency.name in devDependencies||addedBeforeCommit(dependency.name)){recorded.push(dependency.name)}const range2=unreproducibleRange(manifest,dependency.name);if(range2!==undefined){rows.push({action:"dependency-range-unreproducible",artifact:"dependency",detail:rangeFindingDetail({name:dependency.name,range:range2,seed:dependency.version}),item:dependency.item,path:manifestPath})}continue}const rootRange=declaredRange(rootRanges,dependency.name);const version2=typeof rootRange==="string"&&isReproducibleRange(rootRange)?rootRange:dependency.version;devDependencies[dependency.name]=version2;recorded.push(dependency.name);changed=true;rows.push({action:"dependency-added",artifact:"dependency",detail:`${dependency.name}@${version2}`,item:dependency.item,path:manifestPath})}const stale=recordedNames.filter((name)=>!requiredNames.has(name)&&(name in devDependencies));const importers=findImporters(root,workspace,stale,managedPaths);const removed=new Set;for(const name of stale){const importer=importers.get(name);if(importer===undefined){removed.add(name);rows.push({action:"dependency-removed",artifact:"dependency",detail:name,path:manifestPath})}else{rows.push({action:"dependency-kept",artifact:"dependency",detail:`${name}: imported by ${importer}`,path:manifestPath})}}const nextDevDependencies=Object.fromEntries(Object.keys(devDependencies).filter((name)=>!removed.has(name)).toSorted().map((name)=>[name,devDependencies[name]]));const write2=changed||removed.size>0?{content:`${JSON.stringify(placePackageJsonKeys(manifest,{...manifest,devDependencies:nextDevDependencies}),null,2)}
|
|
321
321
|
`,path:manifestPath}:undefined;return{recorded,rows,write:write2}};var planDependencies=({managedPaths,recorded,required,root})=>{const readCommittedFile=recorded===undefined?committedFileReader(root):undefined;const rootRanges=rootManifest(root);const workspaces=[...new Set([...required.map((dependency)=>dependency.workspace),...Object.keys(recorded??{})])].toSorted();const rows=[];const nextRecorded={};const writes=[];for(const workspace of workspaces){const plan=planWorkspace({managedPaths,readCommitted:readCommittedFile===undefined?undefined:()=>readCommittedFile(workspacePackageJson(workspace)),recordedNames:recorded?.[workspace]??[],required:required.filter((dependency)=>dependency.workspace===workspace),root,rootRanges,workspace});rows.push(...plan.rows);if(plan.recorded.length>0){nextRecorded[workspace]=plan.recorded.toSorted()}if(plan.write!==undefined){writes.push(plan.write)}}return{recorded:nextRecorded,rows,writes}};import{fileURLToPath as fileURLToPath2}from"node:url";var cliPackageRoot=fileURLToPath2(new URL("../../../",import.meta.url));var corePackName="pack-core";var itemNames={commitGate:"commit-gate",handoff:"handoff",harness:"harness",hooks:"hooks",lint:(assetId)=>`lint-${assetId}`,managedLint:"managed-lint",pack:(packId)=>`pack-${packId}`,prompts:"prompts",sharedPrompt:"shared-prompt",skill:(skillId)=>`skill-${skillId}`,sourceGuide:(guideId)=>`source-guide-${guideId}`,subagents:"subagents",tools:"tools",typegraphRuntime:"typegraph-runtime"};var lefthookVersion="2.2.2";var lefthookIntegrity="sha512-37fYHAhL12r1twaEV0PA5TwoIT491eTGGYjhhXxlYNMq3DSkiGZBQ++Jfk5maXj0vq52NRauLtMikBKtbNJs3Q==";var prereleaseIdentifier=String.raw`(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)`;var buildIdentifier=String.raw`[0-9A-Za-z-]+`;var prerelease=String.raw`(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?`;var build=String.raw`(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?`;var versionPattern2=new RegExp(String.raw`^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)${prerelease}${build}$`,"u");var constraintPattern=new RegExp(String.raw`^(?<operator>>=|<=|>|<|=)?(?<major>\d+)(?:\.(?<minor>\d+)(?:\.(?<patch>\d+)${prerelease}${build})?)?$`,"u");var numericIdentifierPattern=/^\d+$/u;var parseVersion=(value3)=>{const groups=versionPattern2.exec(value3)?.groups;return groups===undefined?undefined:[Number(groups.major),Number(groups.minor),Number(groups.patch),groups.prerelease?.split(".")??[]]};var compareIdentifiers=(left,right)=>{const leftNumeric=numericIdentifierPattern.test(left);const rightNumeric=numericIdentifierPattern.test(right);if(leftNumeric&&rightNumeric){const difference=BigInt(left)-BigInt(right);return difference===0n?0:Math.sign(Number(difference))}if(leftNumeric!==rightNumeric){return leftNumeric?-1:1}if(left===right){return 0}return left<right?-1:1};var comparePrereleases=(left,right)=>{if(left.length===0||right.length===0){return Math.sign(right.length-left.length)}for(let index=0;index<Math.max(left.length,right.length);index+=1){const leftIdentifier=left[index];const rightIdentifier=right[index];if(leftIdentifier===undefined||rightIdentifier===undefined){return leftIdentifier===undefined?-1:1}const compared=compareIdentifiers(leftIdentifier,rightIdentifier);if(compared!==0){return compared}}return 0};var compareCore=(left,right)=>left[0]-right[0]||left[1]-right[1]||left[2]-right[2];var compareFull=(left,right)=>compareCore(left,right)||comparePrereleases(left[3],right[3]);var parseConstraint=(value3)=>{const groups=constraintPattern.exec(value3)?.groups;if(groups===undefined){return}let precision=1;if(groups.patch!==undefined){precision=3}else if(groups.minor!==undefined){precision=2}return{operator:groups.operator??"=",precision,target:[Number(groups.major),Number(groups.minor??0),Number(groups.patch??0),groups.prerelease?.split(".")??[]]}};var parseRange=(range2)=>range2.trim()==="*"?[]:range2.trim().split(/\s+/u).map(parseConstraint);var satisfiesConstraint=(current,{operator,precision,target})=>{const compare=precision===3?compareFull:compareCore;const compared=compare(current,target);let next;if(precision===1){next=[target[0]+1,0,0,[]]}else if(precision===2){next=[target[0],target[1]+1,0,[]]}switch(operator){case">=":{return compared>=0}case"<=":{return next===undefined?compared<=0:compare(current,next)<0}case">":{return next===undefined?compared>0:compare(current,next)>=0}case"<":{return compared<0}default:{return next===undefined?compared===0:compared>=0&&compare(current,next)<0}}};var satisfiesVersionRange=(version2,range2)=>{const current=parseVersion(version2);const constraints=parseRange(range2);if(current===undefined){return false}return constraints.every((constraint)=>constraint!==undefined&&satisfiesConstraint(current,constraint))};var decodeCheckSettings=decodeUnknownSync(fromJsonString2(Struct({requiredTools:optional(ArraySchema(String4)),typescript:optional(Struct({compilerProjects:optional(ArraySchema(String4))}))})));var readCheckSettings=(root)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:settingsPath}),try:()=>{const absolute=path11.join(root,settingsPath);return existsSync7(absolute)?decodeCheckSettings(readFileSync7(absolute,"utf-8")):{}}});var checkProbeTimeoutMs=1e4;var checkProbeBudgetMs=30000;var inspectRuntime=fn2("Registry.inspectTypegraphRuntime")(function*inspectRuntime2(client,baseline,env){const item=yield*result2(client.fetchCatalog(baseline).pipe(flatMap3((catalog)=>client.fetchItem(catalog,typegraphRuntimeItem))));if(item._tag==="Failure"){const unavailable2={installed:false,reason:`Tool Runtime spec unavailable: ${item.failure.detail}`};return unavailable2}const spec=item.success.meta.hi.toolRuntime;const runtime=spec===undefined?{installed:false,reason:`${typegraphRuntimeItem} names no Tool Runtime`}:yield*inspectToolRuntime(env,spec);return runtime});var checkSemanticReads=fn2("Registry.checkSemanticReads")(function*checkSemanticReads2(input,record2,compilerProjects){const env=input.commandEnvironment??process.env;const runtime=yield*inspectRuntime(input.client,record2.baseline,env);const servers=yield*readRegisteredServers(input.root);const statuses=(runtimePath)=>compilerProjectStatuses({env,override:compilerProjects,probeTimeoutMs:checkProbeTimeoutMs,root:input.root,run:input.runCommand,runtimePath,wikiRoot:record2.shape.wikiRoot});const budgetMs=input.probeBudgetMs??checkProbeBudgetMs;const probed=yield*statuses(runtime.installed?runtime.path:undefined).pipe(timeoutOption2(budgetMs));const projects=isSome2(probed)?probed.value.projects:(yield*statuses()).projects.map((project)=>project.probe==="fail"?{...project,reason:`not probed: hi check probe budget (${budgetMs/1000} s) spent`}:project);const check2={compilerProjects:projects.map((project)=>({...project,registered:project.probe!=="ambiguous"&&servers.some(({server,tsconfig})=>server===project.server&&tsconfig===project.tsconfig)})),registered:{count:servers.length,servers:servers.map(({server})=>server)},runtime};return check2});var onPath=(name)=>commandExistsOnPath(name,process.env);var lintAssets=lintCatalog;var catalogSeeds=(items)=>new Map([...lintAssets.filter((asset)=>items.includes(itemNames.lint(asset.id))).flatMap((asset)=>Object.entries(asset.requiredDevDependencyVersions??{})),...items.includes(itemNames.commitGate)?[["lefthook",lefthookVersion]]:[]]);var rangeFindings=(root,record2)=>findUnreproducibleRanges({root,seeds:catalogSeeds(record2.items),workspaces:[...new Set([".",...record2.shape.workspaces.map((workspace)=>workspace.path),...Object.keys(record2.dependencies)])].toSorted()});var runCheck=fn2("Registry.runCheck")(function*runCheck2(input){const record2=yield*readInstalledRecord(input.root);const settings=yield*readCheckSettings(input.root);const findTool=input.findTool??onPath;const missingTools=(settings.requiredTools??[]).filter((tool)=>!findTool(tool));if(record2===undefined){const notInstalled={dependencyFindings:[],missingTools,status:"not-installed"};return notInstalled}const installed=record2.baseline;const dependencyFindings=rangeFindings(input.root,record2);const registry=yield*input.client.fetchLatestCatalog.pipe(map6((catalog)=>{const latest=catalog.latest??catalog.version;return{cliCompatible:satisfiesVersionRange(input.cliVersion,catalog.cliVersionRange),cliVersionRange:catalog.cliVersionRange,dependencyFindings,installed,latest,missingTools,status:latest===installed?"current":"update-available"}}),catch_2((error2)=>succeed6({dependencyFindings,detail:error2.detail,installed,missingTools,status:"unavailable"})));if(!record2.items.includes(typegraphRuntimeItem)){return registry}const semanticReads=yield*checkSemanticReads(input,record2,settings.typescript?.compilerProjects);return{...registry,semanticReads}});var headlines={current:(result3)=>`Baseline ${result3.installed??"unknown"} is current. Run hi diff for a Drift Check.`,"not-installed":()=>`No Installed Record (${installedRecordPath}). Run hi update to install the Baseline (hi init for a new repository).`,unavailable:(result3)=>`Registry unavailable${result3.detail===undefined?"":` (${result3.detail})`}. Installed Baseline ${result3.installed??"unknown"}; the latest Baseline and drift were not checked.`,"update-available":(result3)=>`Baseline ${result3.latest??"unknown"} is available (installed ${result3.installed??"unknown"}). Run hi update, or hi diff for a Drift Check.`};var semanticReadsLines=({compilerProjects,registered,runtime})=>{const count=(probe)=>compilerProjects.filter((project)=>project.probe===probe).length;const ambiguous=count("ambiguous");return[runtime.installed?`Typegraph runtime: installed ${runtime.version} (${runtime.path})`:`Typegraph runtime: not installed: ${runtime.reason??"unknown reason"}`,`Codex entries: ${registered.count} registered`,`Compiler projects: ${count("pass")} pass, ${count("fail")} fail${ambiguous===0?"":`, ${ambiguous} ambiguous`}`,...compilerProjects.flatMap((project)=>project.probe==="pass"?[]:[` ${project.probe} ${project.tsconfig}: ${project.reason}`])]};var formatCheckHuman=(result3)=>{const lines2=[headlines[result3.status](result3)];if(result3.cliCompatible===false){lines2.push(`This CLI is outside the latest Baseline CLI range ${result3.cliVersionRange??""}. Run hi upgrade first.`)}if(result3.missingTools.length>0){lines2.push(`Missing required tools: ${result3.missingTools.join(", ")}.`)}if(result3.dependencyFindings.length>0){lines2.push("Non-reproducible ranges (pin them yourself; hi never rewrites project versions):",...result3.dependencyFindings.map((finding)=>` ${workspacePackageJson(finding.workspace)}: ${rangeFindingDetail(finding)}`))}if(result3.semanticReads!==undefined){lines2.push(...semanticReadsLines(result3.semanticReads))}return lines2.join(`
|
|
322
|
-
`)};var CliControlPlaneConfig=Service("@punks/cli/CliControlPlaneConfig");var CliReleaseConfig=Service("@punks/cli/CliReleaseConfig");var CliRuntimeConfig=Service("@punks/cli/CliRuntimeConfig");var controlPlaneEnvironment=makeEnvironmentConfig(Struct({CI:optional(String4),DP_CONTROL_PLANE_URL:optional(URLFromString),DP_DISABLE_BUNDLED_CONTROL_PLANE_URL:optional(Literals(["0","1"])),DP_TELEMETRY_SOURCE:optional(String4),NODE_ENV:optional(String4),VITEST:optional(String4)}));var releaseEnvironment=makeEnvironmentConfig(Struct({DP_UPDATE_TAG:optional(NonEmptyString)}));var runtimeEnvironment=makeEnvironmentConfig(Struct({CI:optional(String4),COLORFGBG:optional(String4),FORCE_COLOR:optional(String4),HI_NO_SKILL_UPDATE_CHECK:optional(Literals(["0","1"])),HI_NO_UPDATE_CHECK:optional(Literals(["0","1"])),HI_STARTUP_CHECK_CLI:optional(Literals(["0","1"])),HI_STARTUP_CHECK_INTERVAL_MS:optional(FiniteFromString.check(isInt(),isGreaterThanOrEqualTo3(0))),HI_STARTUP_CHECK_SKILL:optional(Literals(["0","1"])),HI_STARTUP_CHECK_WORKER:optional(Literals(["0","1"])),HI_THEME:optional(Literals(["dark","light"])),HI_UPDATE_TAG:optional(NonEmptyString),NO_COLOR:optional(String4),NPM_CONFIG_REGISTRY:optional(URLFromString),npm_config_registry:optional(URLFromString),npm_config_user_agent:optional(String4)}));var stripTrailingSlashes=(value3)=>value3.toString().replace(/\/+$/u,"");var commandEnvironmentKeys=["AGENT_BROWSER_EXECUTABLE_PATH","ALL_PROXY","APPDATA","BUN_INSTALL","CI","COLORTERM","COMSPEC","CODEX_HOME","DISPLAY","DP_NO_CLIPBOARD","FORCE_COLOR","GH_CONFIG_DIR","HI_NO_SKILL_UPDATE_CHECK","HI_NO_UPDATE_CHECK","HI_OPERATOR_MIGRATION_RETRY","HI_OPERATOR_MUTATION_RETRY","HI_STARTUP_CHECK_CLI","HI_STARTUP_CHECK_INTERVAL_MS","HI_STARTUP_CHECK_SKILL","HI_STARTUP_CHECK_WORKER","HI_THEME","HI_UPDATE_TAG","HOME","HTTP_PROXY","HTTPS_PROXY","LANG","LC_ALL","LOCALAPPDATA","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_ENV","NO_COLOR","NO_PROXY","NPM_CONFIG_REGISTRY","PATH","PATHEXT","Path","SHELL","SSL_CERT_DIR","SSL_CERT_FILE","SYSTEMROOT","TEMP","TERM","TMP","TMPDIR","TURBO_API","TURBO_REMOTE_CACHE_SIGNATURE_KEY","TURBO_TEAM","TURBO_TEAM_ID","TURBO_TOKEN","USERPROFILE","VITEST","WAYLAND_DISPLAY","WINDIR","XAUTHORITY","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_RUNTIME_DIR","all_proxy","http_proxy","https_proxy","no_proxy","npm_config_registry","npm_config_user_agent"];var commandEnvironment=(input)=>Object.fromEntries(commandEnvironmentKeys.flatMap((key)=>input[key]===undefined?[]:[[key,input[key]]]));var loadCliRuntimeConfiguration=(provider,input)=>decodeEnvironment({config:runtimeEnvironment,name:"CLI runtime",provider}).pipe(map6((environment)=>{const ciPresent=input.CI!==undefined||environment.CI!==undefined;const forceColor=input.FORCE_COLOR??environment.FORCE_COLOR;const noColorPresent=input.NO_COLOR!==undefined||environment.NO_COLOR!==undefined;return{commandEnvironment:commandEnvironment(input),forceColor:forceColor!==undefined&&forceColor!=="0",noColor:noColorPresent,npmRegistry:(environment.npm_config_registry?.toString()??environment.NPM_CONFIG_REGISTRY?.toString()??"https://registry.npmjs.org").replace(/\/+$/u,""),...environment.npm_config_user_agent===undefined?{}:{npmUserAgent:environment.npm_config_user_agent},skillUpdateChecksEnabled:environment.HI_NO_SKILL_UPDATE_CHECK!=="1"&&!ciPresent,startupCheckCli:environment.HI_STARTUP_CHECK_CLI==="1",startupCheckIntervalMs:environment.HI_STARTUP_CHECK_INTERVAL_MS??12*60*60*1000,startupCheckSkill:environment.HI_STARTUP_CHECK_SKILL==="1",startupWorker:environment.HI_STARTUP_CHECK_WORKER==="1",updateChecksEnabled:environment.HI_NO_UPDATE_CHECK!=="1"&&!ciPresent,updateTag:environment.HI_UPDATE_TAG??"latest",...environment.HI_THEME===undefined?{}:{terminalTheme:environment.HI_THEME},...environment.COLORFGBG===undefined?{}:{colorForegroundBackground:environment.COLORFGBG}}}));var makeCliConfigLayer=(provider,input={})=>mergeAll2(effect(CliControlPlaneConfig,decodeEnvironment({config:controlPlaneEnvironment,name:"CLI control plane",provider}).pipe(map6((environment)=>{let telemetrySource;const ciPresent=input.CI!==undefined||environment.CI!==undefined;const vitestPresent=input.VITEST!==undefined||environment.VITEST!==undefined;if(ciPresent){telemetrySource="ci"}else if(environment.DP_TELEMETRY_SOURCE==="debug"){telemetrySource="debug"}else if(environment.NODE_ENV==="test"||vitestPresent){telemetrySource="test"}return{disableBundledUrl:environment.DP_DISABLE_BUNDLED_CONTROL_PLANE_URL==="1",...environment.DP_CONTROL_PLANE_URL===undefined?{}:{baseUrl:stripTrailingSlashes(environment.DP_CONTROL_PLANE_URL)},...telemetrySource===undefined?{}:{telemetrySource}}}))),effect(CliReleaseConfig,decodeEnvironment({config:releaseEnvironment,name:"CLI release",provider}).pipe(map6((environment)=>({updateTag:environment.DP_UPDATE_TAG??"latest"})))),effect(CliRuntimeConfig,loadCliRuntimeConfiguration(provider,input)));var name="@punks/cli";var version2="6.5.1";var metadataKeys=new Set(["path","name","group","summary","options","examples","interaction","outputModes"]);var optionKeys=new Set(["name","summary"]);var exampleKeys=new Set(["command","summary"]);class CommandMetadataError extends Error{_tag="CommandMetadataError";constructor(message){super(message);this.name="CommandMetadataError"}}var isRecord4=(value3)=>typeof value3==="object"&&value3!==null&&!Array.isArray(value3);var isCommandInteractionRequirement=(value3)=>value3==="none"||value3==="optional"||value3==="required";var isCommandOutputMode=(value3)=>value3==="interactive"||value3==="plain"||value3==="json";var isNonEmptyStringTuple=(value3)=>Array.isArray(value3)&&value3.length>0&&value3.every((segment)=>typeof segment==="string");var assertString=(value3,label)=>{if(typeof value3!=="string"||value3.trim()===""){throw new CommandMetadataError(`${label} must be a non-empty string.`)}};var assertAllowedKeys=(value3,keys2,label)=>{for(const key of Object.keys(value3)){if(!keys2.has(key)){throw new CommandMetadataError(`${label} contains unsupported behavior or metadata key '${key}'.`)}}};var validateOption=(value3,index)=>{if(!isRecord4(value3)){throw new CommandMetadataError(`Command option ${index} must be an object.`)}assertAllowedKeys(value3,optionKeys,`Command option ${index}`);assertString(value3.name,`Command option ${index}.name`);assertString(value3.summary,`Command option ${index}.summary`);return{name:value3.name,summary:value3.summary}};var validateExample=(value3,index)=>{if(!isRecord4(value3)){throw new CommandMetadataError(`Command example ${index} must be an object.`)}assertAllowedKeys(value3,exampleKeys,`Command example ${index}`);assertString(value3.command,`Command example ${index}.command`);assertString(value3.summary,`Command example ${index}.summary`);return{command:value3.command,summary:value3.summary}};var validateEntry=(value3,index)=>{if(!isRecord4(value3)){throw new CommandMetadataError(`Command metadata entry ${index} must be an object.`)}assertAllowedKeys(value3,metadataKeys,`Command metadata entry ${index}`);if(!isNonEmptyStringTuple(value3.path)){throw new CommandMetadataError(`Command metadata entry ${index}.path must not be empty.`)}for(const[segmentIndex,segment]of value3.path.entries()){assertString(segment,`Command metadata entry ${index}.path[${segmentIndex}]`);if(/^[-_]/u.test(segment)||/\s/u.test(segment)){throw new CommandMetadataError(`Command metadata entry ${index}.path contains an invalid segment.`)}}assertString(value3.name,`Command metadata entry ${index}.name`);if(value3.name!==value3.path.at(-1)){throw new CommandMetadataError(`Command metadata entry ${index}.name must match the final path segment.`)}assertString(value3.group,`Command metadata entry ${index}.group`);assertString(value3.summary,`Command metadata entry ${index}.summary`);if(!Array.isArray(value3.options)){throw new CommandMetadataError(`Command metadata entry ${index}.options must be an array.`)}if(!Array.isArray(value3.examples)){throw new CommandMetadataError(`Command metadata entry ${index}.examples must be an array.`)}if(!isCommandInteractionRequirement(value3.interaction)){throw new CommandMetadataError(`Command metadata entry ${index}.interaction is invalid.`)}if(!Array.isArray(value3.outputModes)||value3.outputModes.length===0){throw new CommandMetadataError(`Command metadata entry ${index}.outputModes must not be empty.`)}const outputModes=value3.outputModes.map((mode,modeIndex)=>{if(!isCommandOutputMode(mode)){throw new CommandMetadataError(`Command metadata entry ${index}.outputModes[${modeIndex}] is invalid.`)}return mode});if(new Set(outputModes).size!==outputModes.length){throw new CommandMetadataError(`Command metadata entry ${index} has duplicate output modes.`)}const options3=value3.options.map(validateOption);if(new Set(options3.map((option4)=>option4.name)).size!==options3.length){throw new CommandMetadataError(`Command metadata entry ${index} has duplicate option names.`)}return{examples:value3.examples.map(validateExample),group:value3.group,interaction:value3.interaction,name:value3.name,options:options3,outputModes,path:value3.path,summary:value3.summary}};var createCommandMetadataRegistry=(entries)=>{const validated=entries.map(validateEntry);const paths=new Set;for(const entry of validated){const key=entry.path.join(" ");if(paths.has(key)){throw new CommandMetadataError(`Duplicate command path '${key}'.`)}paths.add(key)}for(const entry of validated){for(let depth=1;depth<entry.path.length;depth+=1){const parent=entry.path.slice(0,depth).join(" ");if(!paths.has(parent)){throw new CommandMetadataError(`Command '${entry.path.join(" ")}' has missing parent '${parent}'.`)}}}return validated.toSorted((left,right)=>left.path.join(" ").localeCompare(right.path.join(" "),"en",{numeric:false}))};var declareCommandMetadata=(declaration)=>declaration;var commandMetadataFromDeclaration=(path12,declaration)=>({...declaration,path:path12});var optionMetadata=(declaration,name2)=>{const option4=declaration.options.find((candidate)=>candidate.name===name2);if(option4===undefined){throw new Error(`Command metadata for '${declaration.name}' does not declare '--${name2}'.`)}return option4};var metadataOptionName=(declaration,name2)=>optionMetadata(declaration,name2).name;var withOptionMetadata=(declaration,name2)=>(flag)=>exports_Flag.withDescription(flag,optionMetadata(declaration,name2).summary);var withCommandMetadata=(declaration)=>(command)=>command.pipe(exports_Command.withDescription(declaration.summary),exports_Command.withExamples(declaration.examples.map(({command:exampleCommand,summary})=>({command:exampleCommand,description:summary}))));import{existsSync as existsSync9,readFileSync as readFileSync9}from"node:fs";import path13 from"node:path";var CommitGatePolicy=Literals(["enabled","disabled"]);var normalizeCommitGatePolicy=(policy)=>policy??"enabled";var CommitGateHookState=Literals(["managed","inactive","other"]);var CommitGateObservedState=Struct({configHash:NullOr(String4),dependencyVersion:NullOr(String4),hookHash:NullOr(String4),hookState:CommitGateHookState,inertHook:NullOr(String4),lintCommandHash:NullOr(String4)});var managedCommitGateCommand="node .agents/scripts/commit-gate-runner.mjs --contracts .devpunks/commit-gate-contracts.json";var activateGitHooksPath=".agents/scripts/activate-git-hooks.mjs";var activateGitHooksCommand=`node ${activateGitHooksPath}`;var managedHooksPath=".githooks";var managedHookScriptPath=`${managedHooksPath}/pre-commit`;var managedHookScriptDigest="dc5dbd86d5ea34be75774fcd582100e376fdbdce77c5a78b333b9f38023afd9b";var verifyCommitGate=({observed,policy})=>{if(normalizeCommitGatePolicy(policy)==="disabled"){return{_tag:"Unresolved",reason:"Commit Gate policy is disabled."}}if(observed.hookState==="inactive"){return{_tag:"Unresolved",reason:`The Commit Gate is inactive: core.hooksPath is unset. Run ${activateGitHooksCommand}.`,recoveryCommand:activateGitHooksCommand}}if(observed.hookState==="other"){return{_tag:"Unresolved",reason:`Another hook manager owns pre-commit: core.hooksPath is not ${managedHooksPath}, ${managedHookScriptPath} is not the Managed Hook Script, or .git/hooks/pre-commit is not a lefthook hook.`}}if(observed.dependencyVersion!==lefthookVersion){return{_tag:"Unresolved",reason:`Project-local lefthook dependency is not ${lefthookVersion}.`}}if(observed.configHash===null||observed.lintCommandHash===null){return{_tag:"Unresolved",reason:"HI-owned pre-commit.commands.lint is not active."}}if(observed.hookHash===null){return{_tag:"Unresolved",reason:"The Git pre-commit hook is not installed."}}return observed.inertHook===null?{_tag:"Verified"}:{_tag:"Verified",inertHook:observed.inertHook}};import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync8,rmSync}from"node:fs";import{readFile as readFile3}from"node:fs/promises";import{homedir as homedir3}from"node:os";import path12 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";var withoutTrailingSlash=(url)=>url.replace(/\/+$/u,"");var isLoopback=(hostname)=>hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="127.0.0.1"||hostname==="[::1]";var registryUrlProblem=(url,source)=>{let parsed;try{parsed=new URL(url)}catch{return`Registry URL ${url} is not a URL`}const local=parsed.protocol==="file:"||parsed.protocol==="http:"&&isLoopback(parsed.hostname);if(parsed.protocol==="https:"||source==="environment"&&local){return}return source==="settings"?`Settings registry ${url} must be an https: URL; use HI_REGISTRY_URL for a file: or loopback http: Registry`:`HI_REGISTRY_URL ${url} must be an https:, file:, or loopback http: URL`};var defaultRegistryCacheDirectory=()=>path12.join(process.env.XDG_CACHE_HOME??path12.join(homedir3(),".cache"),"hi","registry");var sha256=(bytes)=>createHash2("sha256").update(bytes).digest("hex");var errorDetail2=(cause)=>cause instanceof Error?cause.message:String(cause);var decodeJson=(schema2,url,bytes)=>decodeEffect2(fromJsonString2(schema2))(new TextDecoder().decode(bytes)).pipe(mapError3((cause)=>new RegistryIntegrityError({detail:`Invalid document: ${cause.message}`,url})));var makeRegistryClient=(options3)=>{const baseUrl2=withoutTrailingSlash(options3.baseUrl);const cacheRoot=path12.resolve(options3.cacheDirectory??defaultRegistryCacheDirectory(),sha256(new TextEncoder().encode(baseUrl2)).slice(0,16));const fetchImplementation=options3.fetch??globalThis.fetch;const urlOf=(relative)=>`${baseUrl2}/${relative}`;const download=(url)=>tryPromise2({catch:(cause)=>new RegistryUnavailable({detail:errorDetail2(cause),url}),try:async()=>{if(url.startsWith("file:")){return new Uint8Array(await readFile3(fileURLToPath3(url)))}const response=await fetchImplementation(url,{headers:{accept:"application/json"}});if(response.status!==200){throw new Error(`HTTP ${response.status}`)}return new Uint8Array(await response.arrayBuffer())}});const cachePath=(relative)=>{const absolute=path12.resolve(cacheRoot,...relative.split("/"));return absolute.startsWith(`${cacheRoot}${path12.sep}`)?absolute:undefined};const readCache=(relative)=>{const absolute=cachePath(relative);try{return absolute!==undefined&&existsSync8(absolute)?new Uint8Array(readFileSync8(absolute)):undefined}catch{return}};const discardCache=(relative)=>{const absolute=cachePath(relative);if(absolute!==undefined){rmSync(absolute,{force:true})}};const writeCache=(relative,bytes)=>{const absolute=cachePath(relative);try{if(absolute!==undefined){writeFileAtomic(absolute,bytes)}}catch{}};const fetchLatestCatalog=(()=>{const url=urlOf(registryPaths.latestCatalog);return download(url).pipe(flatMap3((bytes)=>decodeJson(Catalog,url,bytes)))})();const fetchCatalog=(version3)=>gen2(function*fetchVersionCatalog(){const relative=registryPaths.versionCatalog(version3);const url=urlOf(relative);const cached3=readCache(relative);if(cached3!==undefined){const decoded=yield*result2(decodeJson(Catalog,url,cached3));if(decoded._tag==="Success"){return decoded.success}discardCache(relative)}const bytes=yield*download(url);const catalog=yield*decodeJson(Catalog,url,bytes);writeCache(relative,bytes);return catalog});const fetchItem=(catalog,name2)=>gen2(function*fetchRegistryItem(){const relative=registryPaths.item(catalog.version,name2);const url=urlOf(relative);const entry=catalog.items.find((candidate)=>candidate.name===name2);if(entry===undefined){return yield*new RegistryIntegrityError({detail:`Item ${name2} is not in the ${catalog.version} catalog`,url})}const cached3=readCache(relative);if(cached3!==undefined&&sha256(cached3)===entry.meta.sha256){return yield*decodeJson(RegistryItem,url,cached3)}if(cached3!==undefined){discardCache(relative)}const bytes=yield*download(url);if(sha256(bytes)!==entry.meta.sha256){return yield*new RegistryIntegrityError({detail:`sha256 mismatch for ${name2}: expected ${entry.meta.sha256}`,url})}const item=yield*decodeJson(RegistryItem,url,bytes);writeCache(relative,bytes);return item});return{baseUrl:baseUrl2,fetchCatalog,fetchItem,fetchLatestCatalog}};var registryClientForSettings=(settingsRegistry,options3={})=>{const fromEnvironment=process.env.HI_REGISTRY_URL?.trim();let chosen=defaultRegistryUrl;let problem;if(fromEnvironment!==undefined&&fromEnvironment.length>0){chosen=fromEnvironment;problem=registryUrlProblem(fromEnvironment,"environment")}else if(settingsRegistry!==undefined){chosen=settingsRegistry;problem=registryUrlProblem(settingsRegistry,"settings")}const baseUrl2=withoutTrailingSlash(chosen);if(problem===undefined){return makeRegistryClient({...options3,baseUrl:baseUrl2})}const refuse=()=>fail6(new RegistryUnavailable({detail:problem,url:baseUrl2}));return{baseUrl:baseUrl2,fetchCatalog:refuse,fetchItem:refuse,fetchLatestCatalog:refuse()}};var registryClientFor=(root)=>{let registry;try{const absolute=path13.join(root,settingsPath);const parsed=existsSync9(absolute)?JSON.parse(readFileSync9(absolute,"utf-8")):undefined;if(typeof parsed==="object"&&parsed!==null&&"registry"in parsed&&typeof parsed.registry==="string"){({registry}=parsed)}}catch{}return registryClientForSettings(registry)};var nonDefaultRegistry=(client)=>client.baseUrl===defaultRegistryUrl?undefined:client.baseUrl;var withRegistryNotice=({client,human})=>{const registry=nonDefaultRegistry(client);return registry===undefined?human:`Registry: ${registry} (not the default public Registry).
|
|
322
|
+
`)};var CliControlPlaneConfig=Service("@punks/cli/CliControlPlaneConfig");var CliReleaseConfig=Service("@punks/cli/CliReleaseConfig");var CliRuntimeConfig=Service("@punks/cli/CliRuntimeConfig");var controlPlaneEnvironment=makeEnvironmentConfig(Struct({CI:optional(String4),DP_CONTROL_PLANE_URL:optional(URLFromString),DP_DISABLE_BUNDLED_CONTROL_PLANE_URL:optional(Literals(["0","1"])),DP_TELEMETRY_SOURCE:optional(String4),NODE_ENV:optional(String4),VITEST:optional(String4)}));var releaseEnvironment=makeEnvironmentConfig(Struct({DP_UPDATE_TAG:optional(NonEmptyString)}));var runtimeEnvironment=makeEnvironmentConfig(Struct({CI:optional(String4),COLORFGBG:optional(String4),FORCE_COLOR:optional(String4),HI_NO_SKILL_UPDATE_CHECK:optional(Literals(["0","1"])),HI_NO_UPDATE_CHECK:optional(Literals(["0","1"])),HI_STARTUP_CHECK_CLI:optional(Literals(["0","1"])),HI_STARTUP_CHECK_INTERVAL_MS:optional(FiniteFromString.check(isInt(),isGreaterThanOrEqualTo3(0))),HI_STARTUP_CHECK_SKILL:optional(Literals(["0","1"])),HI_STARTUP_CHECK_WORKER:optional(Literals(["0","1"])),HI_THEME:optional(Literals(["dark","light"])),HI_UPDATE_TAG:optional(NonEmptyString),NO_COLOR:optional(String4),NPM_CONFIG_REGISTRY:optional(URLFromString),npm_config_registry:optional(URLFromString),npm_config_user_agent:optional(String4)}));var stripTrailingSlashes=(value3)=>value3.toString().replace(/\/+$/u,"");var commandEnvironmentKeys=["AGENT_BROWSER_EXECUTABLE_PATH","ALL_PROXY","APPDATA","BUN_INSTALL","CI","COLORTERM","COMSPEC","CODEX_HOME","DISPLAY","DP_NO_CLIPBOARD","FORCE_COLOR","GH_CONFIG_DIR","HI_NO_SKILL_UPDATE_CHECK","HI_NO_UPDATE_CHECK","HI_OPERATOR_MIGRATION_RETRY","HI_OPERATOR_MUTATION_RETRY","HI_STARTUP_CHECK_CLI","HI_STARTUP_CHECK_INTERVAL_MS","HI_STARTUP_CHECK_SKILL","HI_STARTUP_CHECK_WORKER","HI_THEME","HI_UPDATE_TAG","HOME","HTTP_PROXY","HTTPS_PROXY","LANG","LC_ALL","LOCALAPPDATA","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_ENV","NO_COLOR","NO_PROXY","NPM_CONFIG_REGISTRY","PATH","PATHEXT","Path","SHELL","SSL_CERT_DIR","SSL_CERT_FILE","SYSTEMROOT","TEMP","TERM","TMP","TMPDIR","TURBO_API","TURBO_REMOTE_CACHE_SIGNATURE_KEY","TURBO_TEAM","TURBO_TEAM_ID","TURBO_TOKEN","USERPROFILE","VITEST","WAYLAND_DISPLAY","WINDIR","XAUTHORITY","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_RUNTIME_DIR","all_proxy","http_proxy","https_proxy","no_proxy","npm_config_registry","npm_config_user_agent"];var commandEnvironment=(input)=>Object.fromEntries(commandEnvironmentKeys.flatMap((key)=>input[key]===undefined?[]:[[key,input[key]]]));var loadCliRuntimeConfiguration=(provider,input)=>decodeEnvironment({config:runtimeEnvironment,name:"CLI runtime",provider}).pipe(map6((environment)=>{const ciPresent=input.CI!==undefined||environment.CI!==undefined;const forceColor=input.FORCE_COLOR??environment.FORCE_COLOR;const noColorPresent=input.NO_COLOR!==undefined||environment.NO_COLOR!==undefined;return{commandEnvironment:commandEnvironment(input),forceColor:forceColor!==undefined&&forceColor!=="0",noColor:noColorPresent,npmRegistry:(environment.npm_config_registry?.toString()??environment.NPM_CONFIG_REGISTRY?.toString()??"https://registry.npmjs.org").replace(/\/+$/u,""),...environment.npm_config_user_agent===undefined?{}:{npmUserAgent:environment.npm_config_user_agent},skillUpdateChecksEnabled:environment.HI_NO_SKILL_UPDATE_CHECK!=="1"&&!ciPresent,startupCheckCli:environment.HI_STARTUP_CHECK_CLI==="1",startupCheckIntervalMs:environment.HI_STARTUP_CHECK_INTERVAL_MS??12*60*60*1000,startupCheckSkill:environment.HI_STARTUP_CHECK_SKILL==="1",startupWorker:environment.HI_STARTUP_CHECK_WORKER==="1",updateChecksEnabled:environment.HI_NO_UPDATE_CHECK!=="1"&&!ciPresent,updateTag:environment.HI_UPDATE_TAG??"latest",...environment.HI_THEME===undefined?{}:{terminalTheme:environment.HI_THEME},...environment.COLORFGBG===undefined?{}:{colorForegroundBackground:environment.COLORFGBG}}}));var makeCliConfigLayer=(provider,input={})=>mergeAll2(effect(CliControlPlaneConfig,decodeEnvironment({config:controlPlaneEnvironment,name:"CLI control plane",provider}).pipe(map6((environment)=>{let telemetrySource;const ciPresent=input.CI!==undefined||environment.CI!==undefined;const vitestPresent=input.VITEST!==undefined||environment.VITEST!==undefined;if(ciPresent){telemetrySource="ci"}else if(environment.DP_TELEMETRY_SOURCE==="debug"){telemetrySource="debug"}else if(environment.NODE_ENV==="test"||vitestPresent){telemetrySource="test"}return{disableBundledUrl:environment.DP_DISABLE_BUNDLED_CONTROL_PLANE_URL==="1",...environment.DP_CONTROL_PLANE_URL===undefined?{}:{baseUrl:stripTrailingSlashes(environment.DP_CONTROL_PLANE_URL)},...telemetrySource===undefined?{}:{telemetrySource}}}))),effect(CliReleaseConfig,decodeEnvironment({config:releaseEnvironment,name:"CLI release",provider}).pipe(map6((environment)=>({updateTag:environment.DP_UPDATE_TAG??"latest"})))),effect(CliRuntimeConfig,loadCliRuntimeConfiguration(provider,input)));var name="@punks/cli";var version2="6.6.0";var metadataKeys=new Set(["path","name","group","summary","options","examples","interaction","outputModes"]);var optionKeys=new Set(["name","summary"]);var exampleKeys=new Set(["command","summary"]);class CommandMetadataError extends Error{_tag="CommandMetadataError";constructor(message){super(message);this.name="CommandMetadataError"}}var isRecord4=(value3)=>typeof value3==="object"&&value3!==null&&!Array.isArray(value3);var isCommandInteractionRequirement=(value3)=>value3==="none"||value3==="optional"||value3==="required";var isCommandOutputMode=(value3)=>value3==="interactive"||value3==="plain"||value3==="json";var isNonEmptyStringTuple=(value3)=>Array.isArray(value3)&&value3.length>0&&value3.every((segment)=>typeof segment==="string");var assertString=(value3,label)=>{if(typeof value3!=="string"||value3.trim()===""){throw new CommandMetadataError(`${label} must be a non-empty string.`)}};var assertAllowedKeys=(value3,keys2,label)=>{for(const key of Object.keys(value3)){if(!keys2.has(key)){throw new CommandMetadataError(`${label} contains unsupported behavior or metadata key '${key}'.`)}}};var validateOption=(value3,index)=>{if(!isRecord4(value3)){throw new CommandMetadataError(`Command option ${index} must be an object.`)}assertAllowedKeys(value3,optionKeys,`Command option ${index}`);assertString(value3.name,`Command option ${index}.name`);assertString(value3.summary,`Command option ${index}.summary`);return{name:value3.name,summary:value3.summary}};var validateExample=(value3,index)=>{if(!isRecord4(value3)){throw new CommandMetadataError(`Command example ${index} must be an object.`)}assertAllowedKeys(value3,exampleKeys,`Command example ${index}`);assertString(value3.command,`Command example ${index}.command`);assertString(value3.summary,`Command example ${index}.summary`);return{command:value3.command,summary:value3.summary}};var validateEntry=(value3,index)=>{if(!isRecord4(value3)){throw new CommandMetadataError(`Command metadata entry ${index} must be an object.`)}assertAllowedKeys(value3,metadataKeys,`Command metadata entry ${index}`);if(!isNonEmptyStringTuple(value3.path)){throw new CommandMetadataError(`Command metadata entry ${index}.path must not be empty.`)}for(const[segmentIndex,segment]of value3.path.entries()){assertString(segment,`Command metadata entry ${index}.path[${segmentIndex}]`);if(/^[-_]/u.test(segment)||/\s/u.test(segment)){throw new CommandMetadataError(`Command metadata entry ${index}.path contains an invalid segment.`)}}assertString(value3.name,`Command metadata entry ${index}.name`);if(value3.name!==value3.path.at(-1)){throw new CommandMetadataError(`Command metadata entry ${index}.name must match the final path segment.`)}assertString(value3.group,`Command metadata entry ${index}.group`);assertString(value3.summary,`Command metadata entry ${index}.summary`);if(!Array.isArray(value3.options)){throw new CommandMetadataError(`Command metadata entry ${index}.options must be an array.`)}if(!Array.isArray(value3.examples)){throw new CommandMetadataError(`Command metadata entry ${index}.examples must be an array.`)}if(!isCommandInteractionRequirement(value3.interaction)){throw new CommandMetadataError(`Command metadata entry ${index}.interaction is invalid.`)}if(!Array.isArray(value3.outputModes)||value3.outputModes.length===0){throw new CommandMetadataError(`Command metadata entry ${index}.outputModes must not be empty.`)}const outputModes=value3.outputModes.map((mode,modeIndex)=>{if(!isCommandOutputMode(mode)){throw new CommandMetadataError(`Command metadata entry ${index}.outputModes[${modeIndex}] is invalid.`)}return mode});if(new Set(outputModes).size!==outputModes.length){throw new CommandMetadataError(`Command metadata entry ${index} has duplicate output modes.`)}const options3=value3.options.map(validateOption);if(new Set(options3.map((option4)=>option4.name)).size!==options3.length){throw new CommandMetadataError(`Command metadata entry ${index} has duplicate option names.`)}return{examples:value3.examples.map(validateExample),group:value3.group,interaction:value3.interaction,name:value3.name,options:options3,outputModes,path:value3.path,summary:value3.summary}};var createCommandMetadataRegistry=(entries)=>{const validated=entries.map(validateEntry);const paths=new Set;for(const entry of validated){const key=entry.path.join(" ");if(paths.has(key)){throw new CommandMetadataError(`Duplicate command path '${key}'.`)}paths.add(key)}for(const entry of validated){for(let depth=1;depth<entry.path.length;depth+=1){const parent=entry.path.slice(0,depth).join(" ");if(!paths.has(parent)){throw new CommandMetadataError(`Command '${entry.path.join(" ")}' has missing parent '${parent}'.`)}}}return validated.toSorted((left,right)=>left.path.join(" ").localeCompare(right.path.join(" "),"en",{numeric:false}))};var declareCommandMetadata=(declaration)=>declaration;var commandMetadataFromDeclaration=(path12,declaration)=>({...declaration,path:path12});var optionMetadata=(declaration,name2)=>{const option4=declaration.options.find((candidate)=>candidate.name===name2);if(option4===undefined){throw new Error(`Command metadata for '${declaration.name}' does not declare '--${name2}'.`)}return option4};var metadataOptionName=(declaration,name2)=>optionMetadata(declaration,name2).name;var withOptionMetadata=(declaration,name2)=>(flag)=>exports_Flag.withDescription(flag,optionMetadata(declaration,name2).summary);var withCommandMetadata=(declaration)=>(command)=>command.pipe(exports_Command.withDescription(declaration.summary),exports_Command.withExamples(declaration.examples.map(({command:exampleCommand,summary})=>({command:exampleCommand,description:summary}))));import{existsSync as existsSync9,readFileSync as readFileSync9}from"node:fs";import path13 from"node:path";var CommitGatePolicy=Literals(["enabled","disabled"]);var normalizeCommitGatePolicy=(policy)=>policy??"enabled";var CommitGateHookState=Literals(["managed","inactive","other"]);var CommitGateObservedState=Struct({configHash:NullOr(String4),dependencyVersion:NullOr(String4),hookHash:NullOr(String4),hookState:CommitGateHookState,inertHook:NullOr(String4),lintCommandHash:NullOr(String4)});var managedCommitGateCommand="node .agents/scripts/commit-gate-runner.mjs --contracts .devpunks/commit-gate-contracts.json";var activateGitHooksPath=".agents/scripts/activate-git-hooks.mjs";var activateGitHooksCommand=`node ${activateGitHooksPath}`;var managedHooksPath=".githooks";var managedHookScriptPath=`${managedHooksPath}/pre-commit`;var managedHookScriptDigest="dc5dbd86d5ea34be75774fcd582100e376fdbdce77c5a78b333b9f38023afd9b";var verifyCommitGate=({observed,policy})=>{if(normalizeCommitGatePolicy(policy)==="disabled"){return{_tag:"Unresolved",reason:"Commit Gate policy is disabled."}}if(observed.hookState==="inactive"){return{_tag:"Unresolved",reason:`The Commit Gate is inactive: core.hooksPath is unset. Run ${activateGitHooksCommand}.`,recoveryCommand:activateGitHooksCommand}}if(observed.hookState==="other"){return{_tag:"Unresolved",reason:`Another hook manager owns pre-commit: core.hooksPath is not ${managedHooksPath}, ${managedHookScriptPath} is not the Managed Hook Script, or .git/hooks/pre-commit is not a lefthook hook.`}}if(observed.dependencyVersion!==lefthookVersion){return{_tag:"Unresolved",reason:`Project-local lefthook dependency is not ${lefthookVersion}.`}}if(observed.configHash===null||observed.lintCommandHash===null){return{_tag:"Unresolved",reason:"HI-owned pre-commit.commands.lint is not active."}}if(observed.hookHash===null){return{_tag:"Unresolved",reason:"The Git pre-commit hook is not installed."}}return observed.inertHook===null?{_tag:"Verified"}:{_tag:"Verified",inertHook:observed.inertHook}};import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync8,rmSync}from"node:fs";import{readFile as readFile3}from"node:fs/promises";import{homedir as homedir3}from"node:os";import path12 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";var withoutTrailingSlash=(url)=>url.replace(/\/+$/u,"");var isLoopback=(hostname)=>hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="127.0.0.1"||hostname==="[::1]";var registryUrlProblem=(url,source)=>{let parsed;try{parsed=new URL(url)}catch{return`Registry URL ${url} is not a URL`}const local=parsed.protocol==="file:"||parsed.protocol==="http:"&&isLoopback(parsed.hostname);if(parsed.protocol==="https:"||source==="environment"&&local){return}return source==="settings"?`Settings registry ${url} must be an https: URL; use HI_REGISTRY_URL for a file: or loopback http: Registry`:`HI_REGISTRY_URL ${url} must be an https:, file:, or loopback http: URL`};var defaultRegistryCacheDirectory=()=>path12.join(process.env.XDG_CACHE_HOME??path12.join(homedir3(),".cache"),"hi","registry");var sha256=(bytes)=>createHash2("sha256").update(bytes).digest("hex");var errorDetail2=(cause)=>cause instanceof Error?cause.message:String(cause);var decodeJson=(schema2,url,bytes)=>decodeEffect2(fromJsonString2(schema2))(new TextDecoder().decode(bytes)).pipe(mapError3((cause)=>new RegistryIntegrityError({detail:`Invalid document: ${cause.message}`,url})));var makeRegistryClient=(options3)=>{const baseUrl2=withoutTrailingSlash(options3.baseUrl);const cacheRoot=path12.resolve(options3.cacheDirectory??defaultRegistryCacheDirectory(),sha256(new TextEncoder().encode(baseUrl2)).slice(0,16));const fetchImplementation=options3.fetch??globalThis.fetch;const urlOf=(relative)=>`${baseUrl2}/${relative}`;const download=(url)=>tryPromise2({catch:(cause)=>new RegistryUnavailable({detail:errorDetail2(cause),url}),try:async()=>{if(url.startsWith("file:")){return new Uint8Array(await readFile3(fileURLToPath3(url)))}const response=await fetchImplementation(url,{headers:{accept:"application/json"}});if(response.status!==200){throw new Error(`HTTP ${response.status}`)}return new Uint8Array(await response.arrayBuffer())}});const cachePath=(relative)=>{const absolute=path12.resolve(cacheRoot,...relative.split("/"));return absolute.startsWith(`${cacheRoot}${path12.sep}`)?absolute:undefined};const readCache=(relative)=>{const absolute=cachePath(relative);try{return absolute!==undefined&&existsSync8(absolute)?new Uint8Array(readFileSync8(absolute)):undefined}catch{return}};const discardCache=(relative)=>{const absolute=cachePath(relative);if(absolute!==undefined){rmSync(absolute,{force:true})}};const writeCache=(relative,bytes)=>{const absolute=cachePath(relative);try{if(absolute!==undefined){writeFileAtomic(absolute,bytes)}}catch{}};const fetchLatestCatalog=(()=>{const url=urlOf(registryPaths.latestCatalog);return download(url).pipe(flatMap3((bytes)=>decodeJson(Catalog,url,bytes)))})();const fetchCatalog=(version3)=>gen2(function*fetchVersionCatalog(){const relative=registryPaths.versionCatalog(version3);const url=urlOf(relative);const cached3=readCache(relative);if(cached3!==undefined){const decoded=yield*result2(decodeJson(Catalog,url,cached3));if(decoded._tag==="Success"){return decoded.success}discardCache(relative)}const bytes=yield*download(url);const catalog=yield*decodeJson(Catalog,url,bytes);writeCache(relative,bytes);return catalog});const fetchItem=(catalog,name2)=>gen2(function*fetchRegistryItem(){const relative=registryPaths.item(catalog.version,name2);const url=urlOf(relative);const entry=catalog.items.find((candidate)=>candidate.name===name2);if(entry===undefined){return yield*new RegistryIntegrityError({detail:`Item ${name2} is not in the ${catalog.version} catalog`,url})}const cached3=readCache(relative);if(cached3!==undefined&&sha256(cached3)===entry.meta.sha256){return yield*decodeJson(RegistryItem,url,cached3)}if(cached3!==undefined){discardCache(relative)}const bytes=yield*download(url);if(sha256(bytes)!==entry.meta.sha256){return yield*new RegistryIntegrityError({detail:`sha256 mismatch for ${name2}: expected ${entry.meta.sha256}`,url})}const item=yield*decodeJson(RegistryItem,url,bytes);writeCache(relative,bytes);return item});return{baseUrl:baseUrl2,fetchCatalog,fetchItem,fetchLatestCatalog}};var registryClientForSettings=(settingsRegistry,options3={})=>{const fromEnvironment=process.env.HI_REGISTRY_URL?.trim();let chosen=defaultRegistryUrl;let problem;if(fromEnvironment!==undefined&&fromEnvironment.length>0){chosen=fromEnvironment;problem=registryUrlProblem(fromEnvironment,"environment")}else if(settingsRegistry!==undefined){chosen=settingsRegistry;problem=registryUrlProblem(settingsRegistry,"settings")}const baseUrl2=withoutTrailingSlash(chosen);if(problem===undefined){return makeRegistryClient({...options3,baseUrl:baseUrl2})}const refuse=()=>fail6(new RegistryUnavailable({detail:problem,url:baseUrl2}));return{baseUrl:baseUrl2,fetchCatalog:refuse,fetchItem:refuse,fetchLatestCatalog:refuse()}};var registryClientFor=(root)=>{let registry;try{const absolute=path13.join(root,settingsPath);const parsed=existsSync9(absolute)?JSON.parse(readFileSync9(absolute,"utf-8")):undefined;if(typeof parsed==="object"&&parsed!==null&&"registry"in parsed&&typeof parsed.registry==="string"){({registry}=parsed)}}catch{}return registryClientForSettings(registry)};var nonDefaultRegistry=(client)=>client.baseUrl===defaultRegistryUrl?undefined:client.baseUrl;var withRegistryNotice=({client,human})=>{const registry=nonDefaultRegistry(client);return registry===undefined?human:`Registry: ${registry} (not the default public Registry).
|
|
323
323
|
${human}`};var recoveryFor=(error2)=>{switch(error2._tag){case"ProjectIntentError":{return"hi init"}case"RegistryUnavailable":case"RegistryIntegrityError":{return"hi check"}case"InstallerFilesystemError":{return}default:{return error2}}};var toCommandFailure=(error2)=>{const recoveryCommand=recoveryFor(error2);const location2="path"in error2?`${error2.path}: `:"";return new CliValidationError({cause:error2,message:`${location2}${error2.detail}`,...recoveryCommand===undefined?{}:{recoveryCommand}})};var installExitCode=(result3)=>result3.status==="applied"?0:1;var plural=(count,noun)=>`${count} ${noun}${count===1?"":"s"}`;var rowLine=(row)=>` ${row.path}${row.detail===undefined?"":` (${row.detail})`}`;var isUnchanged=(row)=>row.action==="skipped"||row.action==="kept"&&row.detail===undefined;var actionLabels={"migrated-skipped":"Migration skipped (left in place)","moved-project-skill":"Project Skill moved into .agents/skills","renamed-project-skill":"Project Skill renamed [DEPRECATED] <id>"};var groupedRows=(rows)=>{const groups=new Map;for(const row of rows.filter((candidate)=>!isUnchanged(candidate))){groups.set(row.action,[...groups.get(row.action)??[],row])}return[...groups].flatMap(([action2,group])=>[` ${actionLabels[action2]??action2} (${group.length})`,...group.map(rowLine)])};var refusalLines=(report)=>{const{refusal}=report;if(refusal===undefined){return[]}if(refusal._tag==="CliOutsideRange"){return[`Refused: Baseline ${refusal.baseline} requires CLI ${refusal.cliVersionRange}; this CLI is ${refusal.cliVersion}.`,"Run hi upgrade, then rerun. Nothing was written."]}return[`Refused: ${refusal.path} does not parse (${refusal.detail}).`,"Fix the file, then rerun. Nothing was written."]};var codexConfigNotes={removed:"hi typegraph block removed from .codex/config.toml",unchanged:".codex/config.toml unchanged",written:".codex/config.toml updated; start a new Codex session to load it"};var semanticReadsLines2=(semanticReads)=>{if(semanticReads===undefined){return[]}const{codexConfig,conflicts,projects,runtime}=semanticReads;const conflictLines=conflicts.map((conflict)=>` Codex config conflict: ${conflict}.`);switch(runtime.status){case"not-selected":{return codexConfig==="unchanged"?conflictLines:[`Semantic reads: TypeScript Pack not selected; ${codexConfigNotes[codexConfig]}. The Tool Runtime stays installed.`,...conflictLines]}case"unavailable":{return[`Semantic reads: Tool Runtime unavailable (${runtime.reason}). No Typegraph server is registered; ${codexConfigNotes[codexConfig]}.`,...conflictLines]}case"installed":case"reused":{const passing=projects.filter((project)=>project.probe==="pass").length;return[`Semantic reads: Typegraph runtime ${runtime.status} at ${runtime.path}; load probe passes for ${String(passing)} of ${plural(projects.length,"Compiler Project")}; ${codexConfigNotes[codexConfig]}.`,...projects.flatMap((project)=>project.probe==="pass"?[]:[` ${project.tsconfig}: ${project.probe==="fail"?"load probe failed":"ambiguous"} (${project.reason}).`]),...conflictLines]}default:{return runtime}}};var outcomeLines=(report)=>{const install2=report.dependencyInstallDetail===undefined?report.dependencyInstall:`${report.dependencyInstall} (${report.dependencyInstallDetail})`;const lines2=[`Lint: ${report.lint}. Dependency install: ${install2}.`];if(report.adoptedPacks!==undefined){lines2.push(`Added detected Packs to ${settingsPath} packs: ${report.adoptedPacks.join(", ")}.`)}if(report.migration.migrated){lines2.push(`Migrated a manifest-based repository: ${plural(report.migration.deleted.length,"retired path")} deleted.`)}for(const link4 of report.failedLinks){lines2.push(`Symlink failed: ${link4.path} -> ${link4.target} (${link4.reason}). No copy was made.`)}if(report.rows.some((row)=>row.action==="kept"&&row.detail?.startsWith("conflict")===true)){lines2.push("Locally edited Copied Artifacts with upstream changes were kept. Run hi update --yes to overwrite them; git keeps your version.")}if(report.rows.some((row)=>row.action==="dependency-added"&&row.detail?.startsWith("lefthook@")===true)){lines2.push(`Lefthook was added for the Commit Gate. Run ${activateGitHooksCommand}, then hi commit-gate verify.`)}if(report.dependencyInstall==="failed"){lines2.push("The dependency install failed. Fix it, then rerun hi update.")}if(report.hookActivation!==undefined){const{detail,outcome}=report.hookActivation;lines2.push(outcome==="ran"?detail:`Hook Activation failed (${detail}). Fix it, then rerun ${activateGitHooksCommand}.`)}lines2.push(...semanticReadsLines2(report.semanticReads));if(report.requiredTools.length>0){lines2.push(`Required tools: ${report.requiredTools.join(", ")}. Run hi tools ensure to install them.`)}return lines2};var formatInstallHuman=(result3)=>{const command=`hi ${result3.mode}`;if(result3.status==="unavailable"){return[`${command}: Registry unavailable (${result3.detail}).`,"Nothing was written. hi needs network access to reach the Registry."].join(`
|
|
324
324
|
`)}if(result3.status==="refused"){return[`${command}:`,...refusalLines(result3)].join(`
|
|
325
325
|
`)}const previous=result3.previous===undefined?"first install":`previous ${result3.previous}`;const unchanged=result3.rows.filter(isUnchanged).length;return[`${command}: Baseline ${result3.applied??"unknown"} ${result3.status} (${previous}).`,...groupedRows(result3.rows),` ${plural(unchanged,"path")} unchanged.`,...outcomeLines(result3)].join(`
|
|
@@ -346,8 +346,8 @@ ${content.trim()}`}).join(`
|
|
|
346
346
|
`)===record2.shape.packs.join(`
|
|
347
347
|
`);const latest=getOrUndefined(yield*fetchLatestBaseline(client,{lintDisabledAssets:settings.lintDisabledAssets,packs:latestShape.packs},{catalog:installedCatalog,items:installedItems}));const local=localRepository(root);const context3=(items,shape)=>({items,loadSubagentManifest:async()=>await Promise.resolve(manifest),readRepositoryFile:(relative)=>{const bytes=isConfined(relative)?local.file(relative):undefined;return bytes===undefined?undefined:decoder.decode(bytes)},settings,shape});const render=(version3,items,shape)=>tryPromise2({catch:(cause)=>new RegistryIntegrityError({detail:`Cannot materialize Baseline ${version3}: ${String(cause)}`,url:client.baseUrl}),try:async()=>await materialize2(items,context3(items,shape))}).pipe(map6(byPath2));const installed=yield*render(record2.baseline,installedItems,record2.shape);const withCurrentShape=yield*render(record2.baseline,installedItems,currentShape);const latestEffects=latest===undefined||samePacks&&latest.reused?installed:yield*render(latest.catalog.version,latest.items,latestShape);const harnessItems=new Set([...installedItems,...latest?.items??[]].filter((entry)=>entry.meta.hi.harnessAdapters===true).map((entry)=>entry.name));const failedLinks=new Map(record2.failedLinks.map((link4)=>[link4.path,link4]));const paths=[...new Set([...Object.keys(record2.paths),...failedLinks.keys(),...installed.keys(),...latestEffects.keys(),...withCurrentShape.keys()])].toSorted();const rowFor=(relative)=>{const installedEffect=installed.get(relative);const latestEffect=latestEffects.get(relative);const currentShapeEffect=withCurrentShape.get(relative);const recorded=record2.paths[relative];const effect2=latestEffect??installedEffect??currentShapeEffect;const verdict=classify({currentShape:currentShapeEffect,failedLink:failedLinks.get(relative),harness:effect2?._tag==="File"&&effect2.artifact==="built"&&harnessItems.has(effect2.item),installed:installedEffect,latest:latestEffect,path:relative,recorded},local);const item=effect2?.item??recorded?.item;return{action:verdict.action,artifact:rowArtifact(effect2,recorded),path:relative,...item===undefined?{}:{item},...verdict.detail===undefined?{}:{detail:verdict.detail}}};const rows=yield*effectForEach(paths.filter(isConfined),(relative)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:String(cause),path:relative}),try:()=>rowFor(relative)}));const information=[...latest===undefined?[{detail:`Registry unreachable; compared with the installed Baseline ${record2.baseline} only.`}]:[...authoredTemplateChanges(installed,latestEffects,latest.catalog.version),...latest.unknownPacks.length===0?[]:[{detail:`Settings select Packs the ${latest.catalog.version} Baseline does not provide: ${latest.unknownPacks.join(", ")}`}],...latest.unknownLintAssets.length===0?[]:[{detail:`Settings disable lint assets the ${latest.catalog.version} Baseline does not provide: ${latest.unknownLintAssets.join(", ")}`}]],...paths.filter((relative)=>!isConfined(relative)).map((relative)=>({detail:"Ignored: the path is outside the repository.",path:relative})),...unselectedDetectedPacks(latest?.catalog??installedCatalog,detection,new Set(settings.packs))];const result3={information,installed:record2.baseline,offline:latest===undefined,rows,...latest===undefined?{}:{latest:latest.catalog.version}};return result3});var formatDiffHuman=(result3)=>{const drift=result3.rows.filter((row)=>row.action!=="current");const against=result3.offline?`installed Baseline ${result3.installed}; the Registry was unreachable, so the latest Baseline was not compared`:`installed Baseline ${result3.installed}, latest Baseline ${result3.latest??result3.installed}`;const lines2=[`Drift Check against ${against}.`];const width=Math.max(0,...drift.map((row)=>row.action.length));for(const row of drift){lines2.push(` ${row.action.padEnd(width)} ${row.path}${row.detail===undefined?"":` (${row.detail})`}`)}const currentCount=result3.rows.length-drift.length;lines2.push(drift.length===0?`All ${currentCount} managed paths match the compared Baseline.`:`${drift.length} paths drift; ${currentCount} are current. Run hi update to apply the Baseline.`);for(const entry of result3.information){lines2.push(` info: ${entry.path===undefined?"":`${entry.path}: `}${entry.detail}`)}return lines2.join(`
|
|
348
348
|
`)};var diffCommandMetadata=declareCommandMetadata({examples:[{command:"hi diff",summary:"Run the Drift Check. Writes nothing."}],group:"commands",interaction:"none",name:"diff",options:[{name:"json",summary:"Print the machine-readable Drift Check to stdout."}],outputModes:["interactive","plain","json"],summary:"Run the Drift Check against the installed and latest Baseline. Writes nothing."});var jsonOption2=exports_Flag.boolean(metadataOptionName(diffCommandMetadata,"json")).pipe(withOptionMetadata(diffCommandMetadata,"json"));var diffExitCode=(result3)=>result3.rows.some((row)=>row.action!=="current")?1:0;var diffCommand=exports_Command.make(diffCommandMetadata.name,{json:jsonOption2},()=>gen2(function*runDiffCommand(){const root=process.cwd();const client=registryClientFor(root);const result3=yield*lifecycleFailure(runDiff({client,root}));yield*publishDocument({exitCode:diffExitCode(result3),human:withRegistryNotice({client,human:formatDiffHuman(result3)}),json:result3})})).pipe(withCommandMetadata(diffCommandMetadata));var SelectedOutputMode=Service("@punks/cli/presentation/SelectedOutputMode");var jsonOptionDescriptor={canonicalOption:"--json",takesValue:false};var jsonOptionEntry=["--json",jsonOptionDescriptor];var optionName=(argument)=>{const equalsIndex=argument.indexOf("=");return equalsIndex===-1?argument:argument.slice(0,equalsIndex)};var commandArgumentsFromRootOptions=(args2,rootOptions)=>{const commandArguments=[];const optionDescriptors=new Map([...rootOptions,jsonOptionEntry]);for(let index=0;index<args2.length;index+=1){const argument=args2[index];if(argument==="--"){break}if(!argument.startsWith("-")||argument==="-"){commandArguments.push(argument);continue}if(argument.startsWith("--")){const descriptor=optionDescriptors.get(optionName(argument));if(descriptor?.takesValue===true&&!argument.includes("=")&&args2[index+1]!==undefined&&args2[index+1]!=="--"){index+=1}continue}for(let aliasIndex=1;aliasIndex<argument.length;aliasIndex+=1){const descriptor=optionDescriptors.get(`-${argument[aliasIndex]}`);if(descriptor?.takesValue!==true){continue}if(aliasIndex+1===argument.length&&args2[index+1]!==undefined&&args2[index+1]!=="--"){index+=1}break}}return commandArguments};var selectOutputMode=({jsonSelected,stdinIsTTY,stdoutIsTTY})=>{if(jsonSelected){return"json"}return stdinIsTTY&&stdoutIsTTY?"interactive":"plain"};var processLongArgument=(argument,index,args2,optionDescriptors,state)=>{const option4=optionName(argument);const descriptor=optionDescriptors.get(option4);const equalsIndex=argument.indexOf("=");if(option4==="--json"){const value4=equalsIndex===-1?"true":argument.slice(equalsIndex+1);if(value4==="true"){state.jsonSelected=true;return index}}if(descriptor?.nativeAction===true&&state.nativeAction===undefined){state.nativeAction=option4}if(descriptor?.takesValue!==true){state.normalizedArguments.push(argument);return index}if(equalsIndex!==-1){if(argument.slice(equalsIndex+1).length===0&&state.missingOption===undefined){state.missingOption=option4}state.normalizedArguments.push(argument);return index}const value3=args2[index+1];if(value3===undefined||value3==="--"){state.missingOption??=option4;state.normalizedArguments.push(argument);return index}state.normalizedArguments.push(`${descriptor.canonicalOption}=${value3}`);return index+1};var processShortArgument=(argument,index,args2,optionDescriptors,state)=>{for(let aliasIndex=1;aliasIndex<argument.length;aliasIndex+=1){const option4=`-${argument[aliasIndex]}`;const descriptor=optionDescriptors.get(option4);if(descriptor?.nativeAction===true&&state.nativeAction===undefined){state.nativeAction=option4}if(descriptor?.takesValue!==true){continue}if(aliasIndex+1<argument.length){state.normalizedArguments.push(`${descriptor.canonicalOption}=${argument.slice(aliasIndex+1)}`);return index}const value3=args2[index+1];if(value3===undefined||value3==="--"){state.missingOption??=option4;return index}state.normalizedArguments.push(`${descriptor.canonicalOption}=${value3}`);return index+1}state.normalizedArguments.push(argument);return index};var analyzeCliArguments=({args:args2,commandOptionsForArguments,rootOptions,stdinIsTTY,stdoutIsTTY})=>{const commandArguments=commandArgumentsFromRootOptions(args2,rootOptions);const optionDescriptors=new Map([...rootOptions,...commandOptionsForArguments(commandArguments),jsonOptionEntry]);const state={jsonSelected:false,missingOption:undefined,nativeAction:undefined,normalizedArguments:[]};for(let index=0;index<args2.length;index+=1){const argument=args2[index];if(argument==="--"){state.normalizedArguments.push(...args2.slice(index));break}if(!argument.startsWith("-")||argument==="-"){state.normalizedArguments.push(argument);continue}if(argument.startsWith("--")){index=processLongArgument(argument,index,args2,optionDescriptors,state);continue}index=processShortArgument(argument,index,args2,optionDescriptors,state)}return{arguments:state.normalizedArguments,commandArguments,...state.missingOption===undefined?{}:{missingOption:state.missingOption},mode:selectOutputMode({jsonSelected:state.jsonSelected,stdinIsTTY,stdoutIsTTY}),...state.nativeAction===undefined?{}:{nativeAction:state.nativeAction}}};import{existsSync as existsSync14,readFileSync as readFileSync15}from"node:fs";import path25 from"node:path";import{cp as cp2,lstat as lstat2,mkdir as mkdir2,readFile as readFile5,readdir,rename as rename3,rm as rm2}from"node:fs/promises";import path23 from"node:path";import{existsSync as existsSync12,lstatSync as lstatSync3,mkdirSync as mkdirSync2,readdirSync as readdirSync4,readFileSync as readFileSync13,readlinkSync as readlinkSync2,renameSync as renameSync2,rmdirSync,rmSync as rmSync2}from"node:fs";import path22 from"node:path";var agentsSkillsDirectory=".agents/skills";var harnessSkillDirectories=harnessIds.map((harness)=>`.${harness}/skills`);var deprecatedPrefix="[DEPRECATED] ";var projectSkillMoveAction=(move)=>path22.posix.basename(move.to).startsWith(deprecatedPrefix)?"renamed-project-skill":"moved-project-skill";var lstat=(absolute)=>lstatSync3(absolute,{throwIfNoEntry:false});var isRealDirectory=(absolute)=>lstat(absolute)?.isDirectory()??false;var registrySkillIds=(plannedFiles)=>new Set([...plannedFiles.keys()].flatMap((file5)=>{const[first,second,id]=file5.split("/");return`${first}/${second}`===agentsSkillsDirectory&&id!==undefined?[id]:[]}));var filesUnder=(root,relative)=>readdirSync4(path22.join(root,relative),{withFileTypes:true}).flatMap((entry)=>{const child=`${relative}/${entry.name}`;return entry.isDirectory()?filesUnder(root,child):[child]});var sameBytes=(left,right)=>left.length===right.length&&left.every((byte,index)=>byte===right[index]);var sameTree=(left,right)=>{const[leftStats,rightStats]=[lstatSync3(left),lstatSync3(right)];if(leftStats.isSymbolicLink()||rightStats.isSymbolicLink()){return leftStats.isSymbolicLink()&&rightStats.isSymbolicLink()&&readlinkSync2(left)===readlinkSync2(right)}if(leftStats.isDirectory()||rightStats.isDirectory()){if(!leftStats.isDirectory()||!rightStats.isDirectory()){return false}const names=readdirSync4(left).toSorted();return names.join("\x00")===readdirSync4(right).toSorted().join("\x00")&&names.every((name2)=>sameTree(path22.join(left,name2),path22.join(right,name2)))}return sameBytes(readFileSync13(left),readFileSync13(right))};var holdsOnlyPlannedBytes=(root,directory3,plannedFiles)=>isRealDirectory(path22.join(root,directory3))&&filesUnder(root,directory3).every((file5)=>{const planned=plannedFiles.get(file5);return planned!==undefined&&sameBytes(planned,readFileSync13(path22.join(root,file5)))});var deprecatedName=(root,id)=>{let candidate=`${agentsSkillsDirectory}/${deprecatedPrefix}${id}`;for(let suffix=2;lstat(path22.join(root,candidate))!==undefined;suffix+=1){candidate=`${agentsSkillsDirectory}/${deprecatedPrefix}${id} (${suffix})`}return candidate};var ownsUnder=(baselineOwned,directory3)=>[...baselineOwned].some((owned)=>owned.startsWith(`${directory3}/`));var move=(root,from,to)=>{mkdirSync2(path22.dirname(path22.join(root,to)),{recursive:true});renameSync2(path22.join(root,from),path22.join(root,to));return{from,to}};var adoptHarnessSkill=(root,from,id,home,provided)=>{if(provided){return move(root,from,deprecatedName(root,id))}for(let attempt2=1;;attempt2+=1){const to=attempt2===1?`${agentsSkillsDirectory}/${id}`:`${agentsSkillsDirectory}/${deprecatedPrefix}${id} (${home}${attempt2===2?"":` ${attempt2-1}`})`;if(lstat(path22.join(root,to))===undefined){return move(root,from,to)}if(sameTree(path22.join(root,from),path22.join(root,to))){rmSync2(path22.join(root,from),{force:true,recursive:true});return{from,to}}}};var adoptHarnessSkills=(root,providedIds,baselineOwned)=>{const moves=[];for(const harnessDirectory of harnessSkillDirectories){const absolute=path22.join(root,harnessDirectory);if(!isRealDirectory(absolute)){continue}for(const entry of readdirSync4(absolute,{withFileTypes:true}).toSorted((left,right)=>left.name.localeCompare(right.name))){const from=`${harnessDirectory}/${entry.name}`;if(!entry.isDirectory()||ownsUnder(baselineOwned,from)){continue}const home=harnessDirectory.split("/")[0]?.replace(/^\./u,"")??"";moves.push(adoptHarnessSkill(root,from,entry.name,home,providedIds.has(entry.name)))}if(readdirSync4(absolute).length===0){rmdirSync(absolute)}}return moves};var renameCollidingSkills=(root,plannedFiles,baselineOwned)=>{const directory3=path22.join(root,agentsSkillsDirectory);if(!existsSync12(directory3)){return[]}const providedIds=registrySkillIds(plannedFiles);const moves=[];for(const id of readdirSync4(directory3).toSorted()){const skillDirectory=`${agentsSkillsDirectory}/${id}`;if(providedIds.has(id)&&!ownsUnder(baselineOwned,skillDirectory)&&!holdsOnlyPlannedBytes(root,skillDirectory,plannedFiles)){moves.push(move(root,skillDirectory,deprecatedName(root,id)))}}return moves};var prepareProjectSkills=({baselineOwned,plannedFiles,root})=>[...adoptHarnessSkills(root,registrySkillIds(plannedFiles),baselineOwned),...renameCollidingSkills(root,plannedFiles,baselineOwned)];var legacyManifestPath=".devpunks/scaffold-manifest.json";var archivePath=".devpunks/pre-existing-skills";var projectSkillsPath=".agents/skills";var skillHomes=new Set([".agents",...harnessIds.map((id)=>`.${id}`)]);var retiredPaths=[".agents/scripts/harness-projection",".agents/scripts/sync-subagents.mjs",".devpunks-cache",".devpunks/commit-gate-lifecycle-receipt.json",".devpunks/context-plan.json",".devpunks/harness-projection-receipt.json",".devpunks/managed-hook-paths.json",".devpunks/replaced-scaffold",".devpunks/replaced-skills",".devpunks/required-tools.json",".devpunks/specs/lint/assets.json",".devpunks/specs/subagents/manifest-spec.json"];var legacyOpenCodePlugin=".opencode/plugins/format-edited-file.mjs";var legacyHook=".agents/hooks/format-edited-file.mjs";var notMigrated={deleted:[],migrated:false,movedProjectSkills:[],settingsRewritten:false,skipped:[]};var errorCode=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)?cause.code:undefined;var fsError=(relative,cause)=>new InstallerFilesystemError({detail:String(cause),path:relative});var exists=(root,relative)=>tryPromise2({catch:(cause)=>fsError(relative,cause),try:async()=>{try{await lstat2(path23.join(root,relative));return true}catch(error2){if(errorCode(error2)==="ENOENT"){return false}throw error2}}});var isSymlink=(root,relative)=>tryPromise2({catch:(cause)=>fsError(relative,cause),try:async()=>{try{const stats=await lstat2(path23.join(root,relative));return stats.isSymbolicLink()}catch(error2){if(errorCode(error2)==="ENOENT"){return false}throw error2}}});var readText=(root,relative)=>tryPromise2({catch:(cause)=>fsError(relative,cause),try:async()=>{let text3;try{text3=await readFile5(path23.join(root,relative),"utf-8")}catch(error2){if(errorCode(error2)!=="ENOENT"){throw error2}}return text3}});var parseJson2=(text3)=>{try{return JSON.parse(text3)}catch{return}};var isRecord8=(value3)=>typeof value3==="object"&&value3!==null&&!Array.isArray(value3);var stringArray=(value3)=>Array.isArray(value3)&&value3.every((entry)=>typeof entry==="string")?value3:undefined;var readLegacyManifest=(root)=>map6(readText(root,legacyManifestPath),(text3)=>{const manifest=text3===undefined?undefined:parseJson2(text3);const record2=isRecord8(manifest)?manifest:{};const managedFiles=Array.isArray(record2.managedFiles)?record2.managedFiles:[];const managedPaths=new Set([...managedFiles.flatMap((file5)=>isRecord8(file5)&&typeof file5.path==="string"?[file5.path]:[]),...stringArray(record2.generatedFiles)??[]]);const managedDigests=new Map(managedFiles.flatMap((file5)=>isRecord8(file5)&&typeof file5.path==="string"&&typeof file5.sha256==="string"?[[file5.path,file5.sha256]]:[]));return{finalPacks:stringArray(record2.finalPacks),managedDigests,managedPaths}});var sortKeys2=(value3)=>{if(Array.isArray(value3)){return value3.map(sortKeys2)}if(!isRecord8(value3)){return value3}return Object.fromEntries(Object.keys(value3).toSorted().map((key)=>[key,sortKeys2(value3[key])]))};var canonicalJson2=(value3)=>`${JSON.stringify(sortKeys2(value3),undefined,2)}
|
|
349
|
-
`;var planSettings=(root,fallbackPacks,pending)=>gen2(function*rewrite(){if(yield*isSymlink(root,settingsPath)){return yield*new InstallerFilesystemError({detail:"Project settings must be a regular file, not a symlink",path:settingsPath})}const before=pending??(yield*readText(root,settingsPath));const parsed=before===undefined?{}:parseJson2(before);if(!isRecord8(parsed)){return yield*new InstallerFilesystemError({detail:"Project settings are not a JSON object; fix the file and rerun hi update",path:settingsPath})}const{baselineVersion:_baseline,cliVersion:_cli,...intent}=parsed;const packs=[...new Set(stringArray(intent.packs)??fallbackPacks)].toSorted();const settings=canonicalJson2({...intent,packs});return{settings,settingsRewritten:settings!==before}});var listDirectories=(root,relative)=>tryPromise2({catch:(cause)=>fsError(relative,cause),try:async()=>{try{const entries=await readdir(path23.join(root,relative),{withFileTypes:true});return entries.filter((entry)=>entry.isDirectory()&&!entry.name.startsWith(".hi-")).map((entry)=>entry.name).toSorted()}catch(error2){const code=errorCode(error2);if(code==="ENOENT"||code==="ENOTDIR"){return[]}throw error2}}});var managedSkillIds=(managedPaths)=>new Set([...managedPaths].flatMap((managed)=>{const[home,skills,id]=managed.split("/");return home!==undefined&&skillHomes.has(home)&&skills==="skills"&&id?[id]:[]}));var moveDirectory=(root,from,to)=>tryPromise2({catch:(cause)=>fsError(to,cause),try:async()=>{const source=confined(root,from);const target=confined(root,to);await mkdir2(path23.dirname(target),{recursive:true});try{await rename3(source,target)}catch(error2){if(errorCode(error2)!=="EXDEV"){throw error2}await cp2(source,target,{errorOnExist:true,force:false,recursive:true,verbatimSymlinks:true});await rm2(source,{force:true,recursive:true})}}});var sameContent=(root,left,right)=>try_3({catch:(cause)=>fsError(left,cause),try:()=>{try{return sameTree(path23.join(root,left),path23.join(root,right))}catch(error2){if(errorCode(error2)==="ENOENT"){return false}throw error2}}});var placeArchivedSkill=(root,home,id,claimed)=>gen2(function*place(){const from=`${archivePath}/${home}/skills/${id}`;const candidates=[`${projectSkillsPath}/${id}`,`${projectSkillsPath}/[DEPRECATED] ${id}`,`${projectSkillsPath}/[DEPRECATED] ${id} (${home.replace(/^\./u,"")})`];for(const to of candidates){const claimedFrom=claimed.get(to);if(claimedFrom===undefined&&!(yield*exists(root,to))){claimed.set(to,from);return[{from,to}]}if(yield*sameContent(root,from,claimedFrom??to)){return[]}}return yield*new InstallerFilesystemError({detail:`Every Project Skill name for "${id}" holds different content; move ${from} manually and rerun hi update`,path:from})});var planProjectSkillMoves=(root,managedPaths)=>gen2(function*planMoves(){const baselineIds=managedSkillIds(managedPaths);const claimed=new Map;const moves=[];for(const home of yield*listDirectories(root,archivePath)){for(const id of yield*listDirectories(root,`${archivePath}/${home}/skills`)){if(!baselineIds.has(id)){moves.push(...yield*placeArchivedSkill(root,home,id,claimed))}}}return moves});var isLegacyOpenCodePlugin=(root)=>gen2(function*check2(){if(yield*isSymlink(root,legacyOpenCodePlugin)){return true}return yield*sameContent(root,legacyOpenCodePlugin,legacyHook)});var remove4=(root,relative)=>tryPromise2({catch:(cause)=>fsError(relative,cause),try:async()=>{const absolute=confined(root,relative);let stats;try{stats=await lstat2(absolute)}catch(error2){if(errorCode(error2)==="ENOENT"){return[]}throw error2}const isDirectory2=stats.isDirectory();await rm2(absolute,{force:true,recursive:isDirectory2});return[isDirectory2?`${relative}/`:relative]}});var planMigration=(root,input)=>gen2(function*plan(){const legacy=(yield*exists(root,legacyManifestPath))&&!(yield*exists(root,installedRecordPath));if(legacy){const manifest=yield*readLegacyManifest(root);const settings=yield*planSettings(root,manifest.finalPacks??input.detectShapePacks,input.settings);const conditional=(yield*isLegacyOpenCodePlugin(root))?[legacyOpenCodePlugin]:[];const migration={...settings,deletions:[...retiredPaths,...conditional,archivePath],managedDigests:manifest.managedDigests,moves:yield*planProjectSkillMoves(root,manifest.managedPaths),previouslyManagedPaths:manifest.managedPaths};return some2(migration)}return none2()}).pipe(map6(getOrUndefined));var notFollowed="resolves outside the repository; not followed";var escaping=(root,paths)=>try_3({catch:(cause)=>fsError(paths[0]??".",cause),try:()=>paths.find((relative)=>escapesRepository(root,relative)!==undefined)});var applyMigration=(root,plan)=>gen2(function*apply2(){const moved=[];const skipped=[];for(const move2 of plan.moves){const outside=yield*escaping(root,[move2.from,move2.to]);if(outside===undefined){yield*moveDirectory(root,move2.from,move2.to);moved.push(move2)}else{skipped.push({path:outside,reason:notFollowed})}}const keepArchive=moved.length<plan.moves.length;const deleted=[];for(const relative of plan.deletions){const outside=yield*escaping(root,[relative]);if(outside!==undefined){skipped.push({path:outside,reason:notFollowed})}else if(keepArchive&&relative===archivePath){skipped.push({path:relative,reason:"holds a Project Skill that was not moved; move it into .agents/skills manually"})}else{deleted.push(...yield*remove4(root,relative))}}return{deleted:deleted.toSorted(),migrated:true,movedProjectSkills:moved,settingsRewritten:plan.settingsRewritten,skipped:skipped.toSorted((left,right)=>left.path.localeCompare(right.path))}});var finalizeMigration=(root)=>remove4(root,legacyManifestPath);import{execFileSync,spawn as spawn2}from"node:child_process";import{createHash as createHash3}from"node:crypto";import{once}from"node:events";import{chmodSync as chmodSync2,existsSync as existsSync13,lstatSync as lstatSync4,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync5,readFileSync as readFileSync14,readlinkSync as readlinkSync3,rmdirSync as rmdirSync2,rmSync as rmSync3,symlinkSync,unlinkSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path24 from"node:path";var effectForEach2=forEach2;var managedLintRunnerPath=".agents/scripts/managed-lint-runner.mjs";var errorDetail3=(cause)=>cause instanceof Error?cause.message:String(cause);var attempt2=(relative,run6)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:errorDetail3(cause),path:relative}),try:run6});var lstat3=(absolute)=>lstatSync4(absolute,{throwIfNoEntry:false});var readBytes=(root,relative)=>{const absolute=confined(root,relative);return lstat3(absolute)?.isFile()===true?new Uint8Array(readFileSync14(absolute)):undefined};var sameBytes2=(left,right)=>left.length===right.length&&left.every((byte,index)=>byte===right[index]);var decoder2=new TextDecoder;var sha256Hex=(bytes)=>createHash3("sha256").update(bytes).digest("hex");var removeEmptyParents=(root,absolute)=>{let directory3=path24.dirname(absolute);while(directory3!==root&&isInside(root,directory3)&&readdirSync5(directory3).length===0){rmdirSync2(directory3);directory3=path24.dirname(directory3)}};var fileMode=(effect2)=>effect2.executable?493:420;var writeFile3=(root,effect2)=>{writeFileAtomic(confined(root,effect2.path),effect2.content,fileMode(effect2))};var executableMatches=(root,effect2)=>{const mode=lstat3(confined(root,effect2.path))?.mode??0;return Math.floor(mode/64)%2===1===effect2.executable};var repositoryReader=(root,overlay)=>(relative)=>{let bytes;try{bytes=readBytes(root,relative)}catch{return new Map().get(relative)}const content=bytes??overlay.get(path24.posix.normalize(relative));return content===undefined?content:decoder2.decode(content)};var withStagedSettings=(settings,use)=>acquireUseRelease2(attempt2(settingsPath,()=>{const staging=mkdtempSync(path24.join(tmpdir2(),"hi-settings-"));if(settings!==undefined){writeFileAtomic(path24.join(staging,settingsPath),settings)}return staging}),use,(staging)=>sync2(()=>{rmSync3(staging,{force:true,recursive:true})}));var writeSettings=(root,settings)=>attempt2(settingsPath,()=>{const current2=readBytes(root,settingsPath);if(current2===undefined||decoder2.decode(current2)!==settings){writeFileAtomic(confined(root,settingsPath),settings)}});var dependencyInstallCommand=(root)=>dependencyInstallationCommand(root)??["npm",["install","--ignore-scripts"]];var allowedPostInstallCommands=["effect-tsgo patch --no-typescript --oxlint"];var postInstallEnvironment=(root,directory3=".")=>{const kept=["HOME","TMPDIR","SystemRoot","PATHEXT"].flatMap((name2)=>{const value3=process.env[name2];return value3===undefined?[]:[[name2,value3]]});return{...Object.fromEntries(kept),PATH:[...new Set([path24.join(root,directory3,"node_modules",".bin"),path24.join(root,"node_modules",".bin")]),process.env.PATH??""].join(path24.delimiter)}};var defaultRunPostInstall=async(root,command,directory3)=>{const[executable="",...args2]=command.split(" ");const child=spawn2(executable,args2,{cwd:path24.join(root,directory3),env:postInstallEnvironment(root,directory3),shell:process.platform==="win32",stdio:"ignore"});try{const closed=await once(child,"close");return closed[0]===0?{detail:command,ok:true}:{detail:`${command} exited ${String(closed[0])}`,ok:false}}catch(error2){return{detail:`${command}: ${errorDetail3(error2)}`,ok:false}}};var postInstallDirectories=(root,workspaces,command)=>{const[executable=""]=command.split(" ");const found=[".",...workspaces].filter((directory3,index,all4)=>all4.indexOf(directory3)===index&&existsSync13(path24.join(root,directory3,"node_modules",".bin",executable)));return found.length===0?["."]:found};var runPostInstallCommands=(options3,items,install2,workspaces)=>{const commands=[...new Set(items.flatMap((item)=>item.meta.hi.postInstall??[]))];const allowed=commands.filter((command)=>allowedPostInstallCommands.includes(command));const skipped=commands.filter((command)=>!allowed.includes(command)).map((command)=>`skipped post-install command outside the CLI allowlist: ${command}`);const withSkipped=(result3)=>skipped.length===0?result3:{...result3,detail:[...result3.detail===undefined?[]:[result3.detail],...skipped].join("; ")};if(install2.outcome==="failed"||allowed.length===0){return succeed6(withSkipped(install2))}const run6=options3.runPostInstall??defaultRunPostInstall;return promise2(async()=>{for(const command of allowed){for(const directory3 of postInstallDirectories(options3.root,workspaces,command)){const result3=await run6(options3.root,command,directory3);if(!result3.ok){return withSkipped({detail:directory3==="."?result3.detail:`${directory3}: ${result3.detail}`,outcome:"failed"})}}}return withSkipped(install2)})};var defaultRunDependencyInstall=async(root)=>{const[command,args2]=dependencyInstallCommand(root);const display=[command,...args2].join(" ");const child=spawn2(command,args2,{cwd:root,stdio:"ignore"});try{const closed=await once(child,"close");return closed[0]===0?{detail:display,ok:true}:{detail:`${display} exited ${String(closed[0])}`,ok:false}}catch(error2){return{detail:`${display}: ${errorDetail3(error2)}`,ok:false}}};var hasUninstalledDependency=(root,recorded)=>Object.entries(recorded).some(([workspace,names])=>names.some((name2)=>{let directory3=path24.resolve(root,workspace);while(!existsSync13(path24.join(directory3,"node_modules",name2,"package.json"))){if(directory3===path24.resolve(root)){return true}directory3=path24.dirname(directory3)}return false}));var installDependencies=(options3,previous,plan)=>{const changed=plan.writes.length>0||canonicalJson(previous?.dependencies??{})!==canonicalJson(plan.recorded)||hasUninstalledDependency(options3.root,plan.recorded);if(!changed){return succeed6({outcome:"skipped"})}const run6=options3.runDependencyInstall??defaultRunDependencyInstall;return promise2(async()=>await run6(options3.root)).pipe(map6((result3)=>({detail:result3.detail,outcome:result3.ok?"ran":"failed"})))};var prepareScript=(manifest)=>typeof manifest==="object"&&manifest!==null&&("scripts"in manifest)&&typeof manifest.scripts==="object"&&manifest.scripts!==null&&("prepare"in manifest.scripts)?manifest.scripts.prepare:undefined;var wirePrepareScript=(root,activation)=>{const bytes=readBytes(root,"package.json");if(activation===undefined||bytes===undefined){return[]}const content=decoder2.decode(bytes);const prepare=prepareScript(JSON.parse(content));if(typeof prepare==="string"&&prepare.includes(activateGitHooksCommand)){return[]}const row={artifact:"merge",item:activation.item,path:"package.json"};if(prepare!==undefined){return[{...row,action:"kept",detail:`scripts.prepare kept; append: && ${activateGitHooksCommand}`}]}writeFileAtomic(confined(root,"package.json"),applyMerges({content,format:"json",target:"package.json",values:[{scripts:{prepare:activateGitHooksCommand}}]}));return[{...row,action:"merged",detail:`scripts.prepare: ${activateGitHooksCommand}`}]};var defaultRunHookActivation=async(root)=>{const child=spawn2("node",[activateGitHooksPath],{cwd:root,stdio:["ignore","pipe","pipe"]});let output="";const collect=(chunk)=>{output+=chunk.toString()};child.stdout.on("data",collect);child.stderr.on("data",collect);try{const closed=await once(child,"close");return closed[0]===0?{detail:output.trim(),ok:true}:{detail:`${activateGitHooksCommand} exited ${String(closed[0])}: ${output.trim()}`,ok:false}}catch(error2){return{detail:`${activateGitHooksCommand}: ${errorDetail3(error2)}`,ok:false}}};var activateHooks=(options3,activation,optedOut)=>{if(activation===undefined||optedOut){return succeed6({})}const run6=options3.runHookActivation??defaultRunHookActivation;return promise2(async()=>await run6(options3.root)).pipe(map6((result3)=>({hookActivation:{detail:result3.detail,outcome:result3.ok?"ran":"failed"}})))};var activationFailed=(report)=>report.hookActivation?.outcome==="failed";var gitOutput=(root,args2)=>{try{return execFileSync("git",args2,{cwd:root,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}};var optOutCommitGate=(root,item)=>{const optOut=(row)=>({...row,detail:`${row.detail??""}; Commit Gate Opt-Out`,item});const rows=[];const script=readBytes(root,managedHookScriptPath);if(script!==undefined){const managed=sha256Hex(script)===managedHookScriptDigest;if(managed){const absolute=confined(root,managedHookScriptPath);unlinkSync(absolute);removeEmptyParents(root,absolute)}rows.push(optOut({action:managed?"removed":"kept",artifact:"copied",detail:managed?"Managed Hook Script":"not the Managed Hook Script",path:managedHookScriptPath}))}const hooksPath=gitOutput(root,["config","--local","--get","core.hooksPath"]);if(hooksPath===undefined){return rows}if(hooksPath!==managedHooksPath){rows.push(optOut({action:"kept",detail:`core.hooksPath ${hooksPath} is not ${managedHooksPath}`,path:".git/config"}));return rows}execFileSync("git",["config","--local","--unset","core.hooksPath"],{cwd:root,stdio:"ignore"});rows.push(optOut({action:"removed",detail:`core.hooksPath ${managedHooksPath}`,path:".git/config"}));const oldHook=path24.resolve(root,gitOutput(root,["rev-parse","--git-common-dir"])??".git","hooks","pre-commit");if(existsSync13(oldHook)){rows.push(optOut({action:"kept",detail:"old hook, not deleted; Git runs it again now that core.hooksPath is unset",path:path24.relative(root,oldHook)}))}return rows};var wireHooks=(root,activation,optedOut)=>{if(!optedOut){return wirePrepareScript(root,activation)}return activation===undefined?[]:optOutCommitGate(root,activation.item)};var defaultRunLint=async(root)=>{const child=spawn2("node",[managedLintRunnerPath,"--root",root],{cwd:root,stdio:"ignore"});try{const closed=await once(child,"close");return typeof closed[0]==="number"?closed[0]:2}catch{return 2}};var lintOutcome=(code)=>{if(code===0){return"passed"}return code===1?"findings":"failed"};var runManagedLint=(options3,intent)=>{if(intent.softwareScopes.length===0||!existsSync13(path24.join(options3.root,managedLintRunnerPath))){return succeed6("skipped")}const run6=options3.runLint??defaultRunLint;return promise2(async()=>await run6(options3.root)).pipe(map6((code)=>lintOutcome(code)))};var semanticReadsStep=(options3,intent,items,wikiRoot)=>syncSemanticReads({env:options3.commandEnvironment??{},override:intent.typescript?.compilerProjects,root:options3.root,run:options3.runCommand,runtime:items.find((item)=>item.name===typegraphRuntimeItem)?.meta.hi.toolRuntime,wikiRoot});var manifestLoader=(root,overlay,load)=>async()=>{const planned=overlay.get(subagentManifestPath);if(existsSync13(path24.join(root,subagentManifestPath))||planned===undefined){return await load(root)}const staging=mkdtempSync(path24.join(tmpdir2(),"hi-subagents-"));try{writeFileAtomic(path24.join(staging,subagentManifestPath),planned);return await load(staging)}finally{rmSync3(staging,{force:true,recursive:true})}};var materializeEffect=(items,context3,options3)=>tryPromise2({catch:(cause)=>new RegistryIntegrityError({detail:errorDetail3(cause),url:options3.client.baseUrl}),try:async()=>await materialize(items,context3,options3.materializeOptions)});var fetchItems2=(client,catalog,names)=>effectForEach2(names,(name2)=>client.fetchItem(catalog,name2),{concurrency:8});var copiedOnly=(item)=>{const{harnessAdapters:_adapters,...meta}=item.meta.hi;const files=(item.files??[]).filter((file5)=>(meta.files?.[file5.path]?.artifact??"copied")==="copied");return{...item,files,meta:{hi:meta}}};var installedCopiedBytes=(options3,record2,context3)=>gen2(function*installedBytes(){const catalog=yield*options3.client.fetchCatalog(record2.baseline);const available=new Set(catalog.items.map((entry)=>entry.name));const items=yield*fetchItems2(options3.client,catalog,record2.items.filter((name2)=>available.has(name2)));const installed=yield*materializeEffect(items.map(copiedOnly),{...context3,items,shape:record2.shape},options3);return new Map(installed.effects.flatMap((effect2)=>effect2._tag==="File"?[[effect2.path,effect2.content]]:[]))}).pipe(option2);var settingsWithPacks=(root,packs)=>attempt2(settingsPath,()=>{const document=JSON.parse(decoder2.decode(readBytes(root,settingsPath)));return`${JSON.stringify({...typeof document==="object"?document:{},packs},null,2)}
|
|
350
|
-
`});var selectIntent=(options3,staged,previous,detected)=>gen2(function*select2(){if(options3.intent!==undefined||staged!==undefined){const intent2=options3.intent??(yield*withStagedSettings(staged,readProjectIntent));return{adopted:[],intent:intent2,settings:staged}}const intent=yield*readProjectIntent(options3.root);const known=previous?.detectedPacks??detected;const adopted=detected.filter((id)=>!known.includes(id)&&!intent.packs.includes(id));if(adopted.length===0){return{adopted,intent,settings:undefined}}const packs=[...intent.packs,...adopted].toSorted();return{adopted,intent:{...intent,packs},settings:yield*settingsWithPacks(options3.root,packs)}});var absentAuthored=(root,effects)=>new Map(effects.flatMap((effect2)=>effect2._tag==="File"&&effect2.artifact==="authored"&&lstat3(confined(root,effect2.path))===undefined?[[effect2.path,effect2.content]]:[]));var planWithOverlay=(options3,base)=>gen2(function*planInstall(){const load=options3.loadSubagentManifest??loadSubagentManifest;const readCommittedFile=committedFileReader(options3.root);const contextWith3=(overlay2)=>({...base,loadSubagentManifest:manifestLoader(options3.root,overlay2,load),readCommittedFile,readRepositoryFile:repositoryReader(options3.root,overlay2)});const first=yield*materializeEffect(base.items,contextWith3(new Map),options3);const overlay=yield*attempt2(".",()=>absentAuthored(options3.root,first.effects));if(overlay.size===0){return{context:contextWith3(overlay),materialized:first}}const context3=contextWith3(overlay);return{context:context3,materialized:yield*materializeEffect(base.items,context3,options3)}});var splitPlan=(effects)=>({dependencies:effects.filter((effect2)=>effect2._tag==="Dependency"),files:effects.filter((effect2)=>effect2._tag==="File"),links:effects.filter((effect2)=>effect2._tag==="Symlink"),merges:effects.filter((effect2)=>effect2._tag==="Merge")});var firstInvalidMergeTarget=(root,plan,previous)=>gen2(function*validateTargets(){const targets=new Map(plan.merges.map((merge6)=>[merge6.target,merge6.format]));const workspaces=[...plan.dependencies.map((dependency)=>dependency.workspace),...Object.keys(previous?.dependencies??{})];for(const workspace of workspaces){targets.set(workspacePackageJson(workspace),"json")}for(const[target,format4]of targets){const invalid2=yield*option2(flip2(validateMergeTarget(root,target,format4)));if(isSome2(invalid2)){return invalid2}}return none2()});var copiedChange=(input,effect2,local)=>{if(input.previous===undefined){const digest2=input.legacyDigests?.get(effect2.path);return{localEdit:digest2!==undefined&&sha256Hex(local)!==digest2,upstreamChanged:digest2===undefined||sha256Hex(effect2.content)!==digest2}}const installed=input.installed?.get(effect2.path);return{localEdit:input.previous.paths[effect2.path]?.artifact==="copied"&&(installed===undefined||!sameNormalized(installed,local)),upstreamChanged:installed===undefined||!sameNormalized(installed,effect2.content)}};var decideCopied=(input,effect2,local)=>{const{localEdit,upstreamChanged}=copiedChange(input,effect2,local);if(!localEdit||sameNormalized(local,effect2.content)){return{action:"written",conflict:false,write:true}}if(input.yes){return{action:"overwritten-local-edit",conflict:false,write:true}}return{action:"kept",conflict:upstreamChanged,detail:upstreamChanged?"conflict: local edit and upstream change; run hi update --yes to overwrite":"local edit; run hi update --yes to restore the Baseline version",write:false}};var applyCopied=(input,effect2)=>{const local=readBytes(input.root,effect2.path);if(local!==undefined&&sameBytes2(local,effect2.content)){if(executableMatches(input.root,effect2)){return{action:"skipped",conflict:false,write:false}}chmodSync2(confined(input.root,effect2.path),fileMode(effect2));return{action:"written",conflict:false,write:false}}const decision=local===undefined?{action:"written",conflict:false,write:true}:decideCopied(input,effect2,local);if(decision.write){writeFile3(input.root,effect2)}return decision};var applyFile=(input,effect2)=>{const{root}=input;if(effect2.artifact==="copied"){return applyCopied(input,effect2)}if(effect2.artifact==="authored"){if(lstat3(confined(root,effect2.path))!==undefined){return{action:"kept",conflict:false,write:false}}writeFile3(root,effect2);return{action:"created",conflict:false,write:true}}const local=readBytes(root,effect2.path);if(local!==undefined&&sameBytes2(local,effect2.content)&&executableMatches(root,effect2)){return{action:"skipped",conflict:false,write:false}}writeFile3(root,effect2);return{action:"written",conflict:false,write:true}};var fileRow=(effect2,decision)=>({action:decision.action,artifact:effect2.artifact,...decision.detail===undefined?{}:{detail:decision.detail},item:effect2.item,path:effect2.path});var applyMergeTarget=(root,merges)=>{const[first]=merges;const target=first?.target??"";const bytes=readBytes(root,target);const content=bytes===undefined?bytes:decoder2.decode(bytes);const next=applyMerges({content,format:first?.format??"json",target,values:merges.map((merge6)=>merge6.value)});const item=[...new Set(merges.map((merge6)=>merge6.item))].join(",");if(next===content){return{action:"skipped",artifact:"merge",item,path:target}}writeFileAtomic(confined(root,target),next);return{action:"merged",artifact:"merge",item,path:target}};var isEditedCopy=(input,relative)=>{const installed=input.installed?.get(relative);const local=readBytes(input.root,relative);return local!==undefined&&(installed===undefined||!sameNormalized(installed,local))};var applyLink=(input,effect2)=>{const{root}=input;const recorded=input.previous?.paths[effect2.path]?.artifact;try{const absolute=confined(root,effect2.path);if(!isInside(root,path24.resolve(path24.dirname(absolute),effect2.target))){return{failure:"link target is outside the repository",linked:false}}const existing=lstat3(absolute);if(existing?.isSymbolicLink()===true){if(readlinkSync3(absolute)===effect2.target){return{linked:false}}unlinkSync(absolute)}else if(existing?.isDirectory()===true&&readdirSync5(absolute).length===0){rmdirSync2(absolute)}else if(existing?.isFile()===true&&(recorded==="copied"||recorded==="built")){if(recorded==="copied"&&!input.yes&&isEditedCopy(input,effect2.path)){return{failure:"local edit of a Copied file the Baseline now links; run hi update --yes to replace it",linked:false}}unlinkSync(absolute)}else if(existing!==undefined){return{failure:"path exists and is not a symlink",linked:false}}mkdirSync3(path24.dirname(absolute),{recursive:true});symlinkSync(effect2.target,absolute);return{linked:true}}catch(error2){return{failure:errorDetail3(error2),linked:false}}};var applyStale=(input,stalePath,recorded)=>{const absolute=confined(input.root,stalePath);const existing=lstat3(absolute);const base={artifact:recorded.artifact,item:recorded.item,path:stalePath};if(existing===undefined){return[]}if(recorded.artifact==="authored"){return[{...base,action:"stale-reported"}]}const removable=recorded.artifact==="symlink"?existing.isSymbolicLink():existing.isFile();if(!removable){return[]}if(recorded.artifact==="copied"&&!input.yes&&isEditedCopy(input,stalePath)){return[{...base,action:"stale-reported",detail:"local edit; no longer in the Baseline. Delete it, or run hi update --yes to remove it"}]}unlinkSync(absolute);removeEmptyParents(input.root,absolute);return[{...base,action:"removed"}]};var refusedReport=(options3,previous,refusal)=>({dependencyInstall:"skipped",failedLinks:[],lint:"skipped",migration:notMigrated,mode:options3.mode,...previous===undefined?{}:{previous:previous.baseline},refusal,requiredTools:[],rows:[],status:"refused"});var applyFiles=(input,files,artifact)=>gen2(function*applyFileKind(){const rows=[];let conflicts=0;for(const effect2 of files.filter((file5)=>file5.artifact===artifact)){const decision=yield*attempt2(effect2.path,()=>applyFile(input,effect2));conflicts+=decision.conflict?1:0;rows.push(fileRow(effect2,decision))}return{conflicts,rows}});var applyLinks=(input,links)=>{const rows=[];const failedLinks=[];for(const effect2 of links){const result3=applyLink(input,effect2);const base={artifact:"symlink",item:effect2.item,path:effect2.path};if(result3.failure===undefined){rows.push({...base,action:result3.linked?"linked":"skipped",detail:`-> ${effect2.target}`})}else{failedLinks.push({path:effect2.path,reason:result3.failure,target:effect2.target});rows.push({...base,action:"link-failed",detail:`-> ${effect2.target}: ${result3.failure}`})}}return{failedLinks,rows}};var applyStalePaths=(input,planned)=>gen2(function*removeStale(){const rows=[];const stale=Object.entries(input.previous?.paths??{}).filter(([stalePath])=>!planned.has(stalePath)).toSorted(([left],[right])=>left.localeCompare(right));for(const[stalePath,recorded]of stale){rows.push(...yield*attempt2(stalePath,()=>applyStale(input,stalePath,recorded)))}return rows});var projectSkillMoveRow=(move2)=>({action:projectSkillMoveAction(move2),detail:`from ${move2.from}`,path:move2.to});var migrationRows=(migrated,deleted)=>[...deleted.map((deletedPath)=>({action:"migrated-deleted",path:deletedPath})),...migrated.skipped.map((skip)=>({action:"migrated-skipped",detail:skip.reason,path:skip.path})),...migrated.movedProjectSkills.map(projectSkillMoveRow)];var withKeptCopies=(planned,previous,kept)=>{const recordedPaths=new Map(planned);for(const keptPath of kept){const recorded=previous?.paths[keptPath];if(recorded?.artifact==="copied"){recordedPaths.set(keptPath,recorded)}}return recordedPaths};var runInstall=(options3)=>gen2(function*install2(){const{client,root,yes}=options3;const completed=(step)=>sync2(()=>options3.onStep?.(step));const rows=[];const previous=yield*readInstalledRecord(root);const catalog=yield*client.fetchLatestCatalog;if(!satisfiesVersionRange(options3.cliVersion,catalog.cliVersionRange)){return refusedReport(options3,previous,{_tag:"CliOutsideRange",baseline:catalog.version,cliVersion:options3.cliVersion,cliVersionRange:catalog.cliVersionRange})}yield*completed("STEP-001");const detected=proposePacks(yield*repositoryDetection(root),catalog);const migration=yield*planMigration(root,{detectShapePacks:detected,...options3.settings===undefined?{}:{settings:options3.settings}});const staged=migration?.settings??options3.settings;yield*completed("migration");const{adopted,intent,settings}=yield*selectIntent(options3,staged,previous,detected);const names=yield*resolveItemNames(catalog,intent);const items=yield*fetchItems2(client,catalog,names);yield*client.fetchCatalog(catalog.version).pipe(ignore2);yield*completed("STEP-002");const shape=yield*detectShape(root,intent.packs);const{context:context3,materialized}=yield*planWithOverlay(options3,{items,settings:intent,shape});const optedOut=intent.commitGate==="disabled";const plan=splitPlan(materialized.effects);const installed=previous===undefined||yes?none2():yield*installedCopiedBytes(options3,previous,context3);yield*completed("STEP-003");const invalid2=yield*firstInvalidMergeTarget(root,plan,previous);if(isSome2(invalid2)){return refusedReport(options3,previous,{_tag:"InvalidMergeTarget",detail:invalid2.value.detail,path:invalid2.value.path})}yield*completed("STEP-004");if(settings!==undefined){yield*writeSettings(root,settings)}const migrated=migration===undefined?notMigrated:yield*applyMigration(root,migration);const skillMoves=yield*attempt2(".agents/skills",()=>prepareProjectSkills({baselineOwned:new Set([...Object.keys(previous?.paths??{}),...migration?.previouslyManagedPaths??[]]),plannedFiles:new Map(plan.files.map((file5)=>[file5.path,file5.content])),root}));rows.push(...skillMoves.map(projectSkillMoveRow));yield*completed("project-skills");const fileInput={installed:getOrUndefined(installed),legacyDigests:migration?.managedDigests,previous,root,yes};const copied=yield*applyFiles(fileInput,plan.files,"copied");rows.push(...copied.rows);yield*completed("STEP-005");rows.push(...(yield*applyFiles(fileInput,plan.files,"built")).rows);yield*completed("STEP-006");rows.push(...(yield*applyFiles(fileInput,plan.files,"authored")).rows);yield*completed("STEP-007");for(const target of new Set(plan.merges.map((merge6)=>merge6.target))){const targetMerges=plan.merges.filter((merge6)=>merge6.target===target);rows.push(yield*attempt2(target,()=>applyMergeTarget(root,targetMerges)))}yield*completed("STEP-008");const linked=applyLinks(fileInput,plan.links);rows.push(...linked.rows);yield*completed("STEP-009");const dependencyPlan=yield*attempt2("package.json",()=>planDependencies({managedPaths:new Set([...plan.files.map((file5)=>file5.path),...Object.keys(previous?.paths??{})]),recorded:previous?.dependencies,required:plan.dependencies,root}));for(const write2 of dependencyPlan.writes){yield*attempt2(write2.path,()=>{writeFileAtomic(confined(root,write2.path),write2.content)})}rows.push(...dependencyPlan.rows);const activation=plan.files.find((file5)=>file5.path===activateGitHooksPath);rows.push(...yield*attempt2("package.json",()=>wireHooks(root,activation,optedOut)));const dependencyInstall=yield*runPostInstallCommands(options3,items,yield*installDependencies(options3,previous,dependencyPlan),shape.workspaces.map((workspace)=>workspace.path));const hookActivation=yield*activateHooks(options3,activation,optedOut);yield*completed("STEP-010");const planned=new Map([...plan.files.map((file5)=>[file5.path,{artifact:file5.artifact,item:file5.item}]),...plan.links.map((link4)=>[link4.path,{artifact:"symlink",item:link4.item}])]);const staleRows=yield*applyStalePaths(fileInput,planned);rows.push(...staleRows);const recordedPaths=withKeptCopies(planned,previous,[...staleRows.filter((row)=>row.action==="stale-reported").map((row)=>row.path),...linked.failedLinks.map((link4)=>link4.path)]);yield*completed("STEP-011");const finalized=migration===undefined?[]:yield*finalizeMigration(root);const migrationDeleted=[...migrated.deleted,...finalized].toSorted();rows.push(...migrationRows(migrated,migrationDeleted));yield*completed("finalize-migration");yield*writeInstalledRecord(root,{baseline:catalog.version,dependencies:dependencyPlan.recorded,detectedPacks:detected,failedLinks:linked.failedLinks,items:names,paths:Object.fromEntries(recordedPaths),schemaVersion:1,shape});yield*completed("STEP-012");const semanticReads=yield*semanticReadsStep(options3,intent,items,shape.wikiRoot);yield*completed("semantic-reads");const lint=yield*runManagedLint(options3,intent);yield*completed("STEP-013");const problems=copied.conflicts+linked.failedLinks.length;return{...adopted.length===0?{}:{adoptedPacks:adopted},...hookActivation,applied:catalog.version,dependencyInstall:dependencyInstall.outcome,...dependencyInstall.detail===undefined?{}:{dependencyInstallDetail:dependencyInstall.detail},failedLinks:linked.failedLinks,lint,migration:{...migrated,deleted:migrationDeleted},mode:options3.mode,...previous===undefined?{}:{previous:previous.baseline},requiredTools:materialized.requiredTools,rows,semanticReads,status:problems>0||dependencyInstall.outcome==="failed"||activationFailed(hookActivation)?"partial":"applied"}});var sorted3=(values)=>[...new Set(values)].toSorted();var refused=(catalog,cliVersion,previous)=>({dependencyInstall:"skipped",failedLinks:[],lint:"skipped",migration:notMigrated,mode:"init",...previous===undefined?{}:{previous},refusal:{_tag:"CliOutsideRange",baseline:catalog.version,cliVersion,cliVersionRange:catalog.cliVersionRange},requiredTools:[],rows:[],status:"refused"});var requiredToolsFor=(requiredTools,repositoryManager)=>sorted3([...requiredTools.filter((tool)=>!providerCliTools.includes(tool)),...isRepositoryManager(repositoryManager)?requiredToolsForRepositoryManager(repositoryManager):[]]);var defaultProviders=(existing,inferredManager)=>{const repositoryManager=existing?.repositoryManager??inferredManager;const backlogProvider=existing?.backlogProvider??(isBacklogProvider(repositoryManager)?repositoryManager:undefined);const assetProviderSlug=existing?.assetProviderSlug??(isAssetProvider(backlogProvider)?backlogProvider:undefined);return{...assetProviderSlug===undefined?{}:{assetProviderSlug},...backlogProvider===undefined?{}:{backlogProvider},...repositoryManager===undefined?{}:{repositoryManager}}};var keptIntent=(existing)=>({...existing?.backlogProjectUrl===undefined?{}:{backlogProjectUrl:existing.backlogProjectUrl},...existing?.commitGate===undefined?{}:{commitGate:existing.commitGate},...existing?.registry===undefined?{}:{registry:existing.registry}});var defaultIntent=(existing,proposed,inferredManager)=>{const providers=defaultProviders(existing,inferredManager);return{...keptIntent(existing),...providers,lintDisabledAssets:sorted3(existing?.lint?.disabledAssets??[]),lintExclude:sorted3(existing?.lint?.exclude??[]),packs:sorted3(existing?.packs??proposed.packs),requiredTools:requiredToolsFor(existing?.requiredTools??[],providers.repositoryManager),softwareScopes:sorted3(existing?.lint?.scopes??proposed.softwareScopes)}};var packChoices=(catalog)=>catalog.items.flatMap((entry)=>{const{pack}=entry.meta.hi;return entry.meta.hi.kind==="pack"&&pack!==undefined&&entry.name!==corePackName?[{category:pack.category,id:entry.name.replace(/^pack-/u,""),...entry.description===undefined?{}:{description:entry.description}}]:[]});var proposeInit=(root,catalog)=>gen2(function*propose(){const existing=yield*readSettingsDocument(root);const detection=yield*detectRepository(root).pipe(mapError3((cause)=>new InstallerFilesystemError({detail:cause.message,path:"."})));const shape=yield*detectShape(root,[]);const defaults2=defaultIntent(existing,{packs:proposePacks(detection,catalog),softwareScopes:proposeSoftwareScopes(shape)},inferRepositoryManager(root));const proposal={catalog,defaults:defaults2,packs:packChoices(catalog),workspaces:sorted3([...shape.workspaces.map((workspace)=>workspace.path),...defaults2.softwareScopes])};return proposal});var readSettingsText=(root)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:settingsPath}),try:()=>{const absolute=path25.join(root,settingsPath);return existsSync14(absolute)?readFileSync15(absolute,"utf-8"):undefined}});var initSettings=(root,intent)=>gen2(function*render(){const current2=yield*readSettingsText(root);return yield*withStagedSettings(current2,(staging)=>writeInitSettings(staging,intent).pipe(andThen2(readSettingsText(staging)),map6((text3)=>text3??"")))});var unavailableReport=(mode,error2)=>({detail:`${error2.detail} (${error2.url})`,mode,status:"unavailable"});var runInit=(options3)=>gen2(function*init(){const{client,cliVersion,root}=options3;const catalog=yield*client.fetchLatestCatalog;if(!satisfiesVersionRange(cliVersion,catalog.cliVersionRange)){const previous=yield*readInstalledRecord(root);return refused(catalog,cliVersion,previous?.baseline)}const proposal=yield*proposeInit(root,catalog);const selected=yield*options3.confirm(proposal);const settings=yield*initSettings(root,{...selected,requiredTools:requiredToolsFor(selected.requiredTools,selected.repositoryManager)});const result3=yield*runInstall({cliVersion,client,mode:"init",root,settings,yes:options3.yes,...options3.commandEnvironment===undefined?{}:{commandEnvironment:options3.commandEnvironment},...options3.runCommand===undefined?{}:{runCommand:options3.runCommand},...options3.runDependencyInstall===undefined?{}:{runDependencyInstall:options3.runDependencyInstall},...options3.runHookActivation===undefined?{}:{runHookActivation:options3.runHookActivation},...options3.runLint===undefined?{}:{runLint:options3.runLint},...options3.runPostInstall===undefined?{}:{runPostInstall:options3.runPostInstall}});return result3}).pipe(catchIf2((error2)=>is2(RegistryUnavailable)(error2),(error2)=>succeed6(unavailableReport("init",error2))));import{createInterface as createInterface2}from"node:readline/promises";import{stdin as input,stdout as output}from"node:process";var makePromptInteraction=({createReadline,input})=>{const initialRawMode=input.isRaw===true;const initiallyPaused=input.isPaused?.()===true;const readline2=createReadline();const restoreInput=()=>{if(input.isTTY===true&&input.isRaw!==initialRawMode){input.setRawMode(initialRawMode)}if(initiallyPaused){input.pause()}else{input.resume()}};return{close:()=>{readline2.close();restoreInput()},readLine:async(question)=>{if(input.isTTY===true&&input.isRaw===true){input.setRawMode(false)}input.resume();readline2.resume();try{return await readline2.question(question)}finally{restoreInput()}},runSelection:(effect2)=>sync2(()=>readline2.pause()).pipe(andThen2(effect2),ensuring2(sync2(()=>{readline2.resume();restoreInput()})))}};var localMultiSelect=(options3)=>exports_Prompt.run(exports_Prompt.multiSelect({choices:options3.choices,maxPerPage:options3.maxPerPage??10,message:options3.message,selectAll:options3.selectAll??"Select all",selectNone:options3.selectNone??"Clear all"})).pipe(map6((values)=>values.toSorted()));var localSingleSelect=(options3)=>exports_Prompt.run(exports_Prompt.select({choices:options3.choices.map((choice4)=>({...choice4,selected:choice4.value===options3.defaultValue})),maxPerPage:options3.maxPerPage??10,message:options3.message}));var CliPrompt=Service("@punks/cli/ui/CliPrompt");var PromptLive=acquireRelease2(sync2(()=>makePromptInteraction({createReadline:()=>createInterface2({input,output}),input})),(interaction)=>sync2(interaction.close)).pipe(map6((interaction)=>({multiSelect:({message,choices,selectAll,selectNone})=>interaction.runSelection(localMultiSelect({choices,message,...selectAll===undefined||selectAll===""?{}:{selectAll},...selectNone===undefined||selectNone===""?{}:{selectNone}})).pipe(map6((values)=>values.toSorted()),mapError3((cause)=>new CliPromptError({cause,message:"Failed to read checklist input."}))),readLine:(question)=>tryPromise2({catch:(cause)=>new CliPromptError({cause,message:"Failed to read CLI input."}),try:async()=>await interaction.readLine(question)}),singleSelect:({message,choices,defaultValue})=>interaction.runSelection(localSingleSelect({choices,message,...defaultValue===undefined||defaultValue===""?{}:{defaultValue}})).pipe(mapError3((cause)=>new CliPromptError({cause,message:"Failed to read selection input."}))),writeLine:(line)=>callback2((resume)=>{output.write(`${line}
|
|
349
|
+
`;var planSettings=(root,fallbackPacks,pending)=>gen2(function*rewrite(){if(yield*isSymlink(root,settingsPath)){return yield*new InstallerFilesystemError({detail:"Project settings must be a regular file, not a symlink",path:settingsPath})}const before=pending??(yield*readText(root,settingsPath));const parsed=before===undefined?{}:parseJson2(before);if(!isRecord8(parsed)){return yield*new InstallerFilesystemError({detail:"Project settings are not a JSON object; fix the file and rerun hi update",path:settingsPath})}const{baselineVersion:_baseline,cliVersion:_cli,...intent}=parsed;const packs=[...new Set(stringArray(intent.packs)??fallbackPacks)].toSorted();const settings=canonicalJson2({...intent,packs});return{settings,settingsRewritten:settings!==before}});var listDirectories=(root,relative)=>tryPromise2({catch:(cause)=>fsError(relative,cause),try:async()=>{try{const entries=await readdir(path23.join(root,relative),{withFileTypes:true});return entries.filter((entry)=>entry.isDirectory()&&!entry.name.startsWith(".hi-")).map((entry)=>entry.name).toSorted()}catch(error2){const code=errorCode(error2);if(code==="ENOENT"||code==="ENOTDIR"){return[]}throw error2}}});var managedSkillIds=(managedPaths)=>new Set([...managedPaths].flatMap((managed)=>{const[home,skills,id]=managed.split("/");return home!==undefined&&skillHomes.has(home)&&skills==="skills"&&id?[id]:[]}));var moveDirectory=(root,from,to)=>tryPromise2({catch:(cause)=>fsError(to,cause),try:async()=>{const source=confined(root,from);const target=confined(root,to);await mkdir2(path23.dirname(target),{recursive:true});try{await rename3(source,target)}catch(error2){if(errorCode(error2)!=="EXDEV"){throw error2}await cp2(source,target,{errorOnExist:true,force:false,recursive:true,verbatimSymlinks:true});await rm2(source,{force:true,recursive:true})}}});var sameContent=(root,left,right)=>try_3({catch:(cause)=>fsError(left,cause),try:()=>{try{return sameTree(path23.join(root,left),path23.join(root,right))}catch(error2){if(errorCode(error2)==="ENOENT"){return false}throw error2}}});var placeArchivedSkill=(root,home,id,claimed)=>gen2(function*place(){const from=`${archivePath}/${home}/skills/${id}`;const candidates=[`${projectSkillsPath}/${id}`,`${projectSkillsPath}/[DEPRECATED] ${id}`,`${projectSkillsPath}/[DEPRECATED] ${id} (${home.replace(/^\./u,"")})`];for(const to of candidates){const claimedFrom=claimed.get(to);if(claimedFrom===undefined&&!(yield*exists(root,to))){claimed.set(to,from);return[{from,to}]}if(yield*sameContent(root,from,claimedFrom??to)){return[]}}return yield*new InstallerFilesystemError({detail:`Every Project Skill name for "${id}" holds different content; move ${from} manually and rerun hi update`,path:from})});var planProjectSkillMoves=(root,managedPaths)=>gen2(function*planMoves(){const baselineIds=managedSkillIds(managedPaths);const claimed=new Map;const moves=[];for(const home of yield*listDirectories(root,archivePath)){for(const id of yield*listDirectories(root,`${archivePath}/${home}/skills`)){if(!baselineIds.has(id)){moves.push(...yield*placeArchivedSkill(root,home,id,claimed))}}}return moves});var isLegacyOpenCodePlugin=(root)=>gen2(function*check2(){if(yield*isSymlink(root,legacyOpenCodePlugin)){return true}return yield*sameContent(root,legacyOpenCodePlugin,legacyHook)});var remove4=(root,relative)=>tryPromise2({catch:(cause)=>fsError(relative,cause),try:async()=>{const absolute=confined(root,relative);let stats;try{stats=await lstat2(absolute)}catch(error2){if(errorCode(error2)==="ENOENT"){return[]}throw error2}const isDirectory2=stats.isDirectory();await rm2(absolute,{force:true,recursive:isDirectory2});return[isDirectory2?`${relative}/`:relative]}});var planMigration=(root,input)=>gen2(function*plan(){const legacy=(yield*exists(root,legacyManifestPath))&&!(yield*exists(root,installedRecordPath));if(legacy){const manifest=yield*readLegacyManifest(root);const settings=yield*planSettings(root,manifest.finalPacks??input.detectShapePacks,input.settings);const conditional=(yield*isLegacyOpenCodePlugin(root))?[legacyOpenCodePlugin]:[];const migration={...settings,deletions:[...retiredPaths,...conditional,archivePath],managedDigests:manifest.managedDigests,moves:yield*planProjectSkillMoves(root,manifest.managedPaths),previouslyManagedPaths:manifest.managedPaths};return some2(migration)}return none2()}).pipe(map6(getOrUndefined));var notFollowed="resolves outside the repository; not followed";var escaping=(root,paths)=>try_3({catch:(cause)=>fsError(paths[0]??".",cause),try:()=>paths.find((relative)=>escapesRepository(root,relative)!==undefined)});var applyMigration=(root,plan)=>gen2(function*apply2(){const moved=[];const skipped=[];for(const move2 of plan.moves){const outside=yield*escaping(root,[move2.from,move2.to]);if(outside===undefined){yield*moveDirectory(root,move2.from,move2.to);moved.push(move2)}else{skipped.push({path:outside,reason:notFollowed})}}const keepArchive=moved.length<plan.moves.length;const deleted=[];for(const relative of plan.deletions){const outside=yield*escaping(root,[relative]);if(outside!==undefined){skipped.push({path:outside,reason:notFollowed})}else if(keepArchive&&relative===archivePath){skipped.push({path:relative,reason:"holds a Project Skill that was not moved; move it into .agents/skills manually"})}else{deleted.push(...yield*remove4(root,relative))}}return{deleted:deleted.toSorted(),migrated:true,movedProjectSkills:moved,settingsRewritten:plan.settingsRewritten,skipped:skipped.toSorted((left,right)=>left.path.localeCompare(right.path))}});var finalizeMigration=(root)=>remove4(root,legacyManifestPath);import{execFileSync,spawn as spawn2}from"node:child_process";import{createHash as createHash3}from"node:crypto";import{once}from"node:events";import{chmodSync as chmodSync2,existsSync as existsSync13,lstatSync as lstatSync4,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync5,readFileSync as readFileSync14,readlinkSync as readlinkSync3,rmdirSync as rmdirSync2,rmSync as rmSync3,symlinkSync,unlinkSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path24 from"node:path";var effectForEach2=forEach2;var managedLintRunnerPath=".agents/scripts/managed-lint-runner.mjs";var errorDetail3=(cause)=>cause instanceof Error?cause.message:String(cause);var attempt2=(relative,run6)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:errorDetail3(cause),path:relative}),try:run6});var lstat3=(absolute)=>lstatSync4(absolute,{throwIfNoEntry:false});var readBytes=(root,relative)=>{const absolute=confined(root,relative);return lstat3(absolute)?.isFile()===true?new Uint8Array(readFileSync14(absolute)):undefined};var sameBytes2=(left,right)=>left.length===right.length&&left.every((byte,index)=>byte===right[index]);var decoder2=new TextDecoder;var sha256Hex=(bytes)=>createHash3("sha256").update(bytes).digest("hex");var removeEmptyParents=(root,absolute)=>{let directory3=path24.dirname(absolute);while(directory3!==root&&isInside(root,directory3)&&readdirSync5(directory3).length===0){rmdirSync2(directory3);directory3=path24.dirname(directory3)}};var fileMode=(effect2)=>effect2.executable?493:420;var writeFile3=(root,effect2)=>{writeFileAtomic(confined(root,effect2.path),effect2.content,fileMode(effect2))};var executableMatches=(root,effect2)=>{const mode=lstat3(confined(root,effect2.path))?.mode??0;return Math.floor(mode/64)%2===1===effect2.executable};var repositoryReader=(root,overlay)=>(relative)=>{let bytes;try{bytes=readBytes(root,relative)}catch{return new Map().get(relative)}const content=bytes??overlay.get(path24.posix.normalize(relative));return content===undefined?content:decoder2.decode(content)};var withStagedSettings=(settings,use)=>acquireUseRelease2(attempt2(settingsPath,()=>{const staging=mkdtempSync(path24.join(tmpdir2(),"hi-settings-"));if(settings!==undefined){writeFileAtomic(path24.join(staging,settingsPath),settings)}return staging}),use,(staging)=>sync2(()=>{rmSync3(staging,{force:true,recursive:true})}));var writeSettings=(root,settings)=>attempt2(settingsPath,()=>{const current2=readBytes(root,settingsPath);if(current2===undefined||decoder2.decode(current2)!==settings){writeFileAtomic(confined(root,settingsPath),settings)}});var dependencyInstallCommand=(root)=>dependencyInstallationCommand(root)??["npm",["install","--ignore-scripts"]];var defaultRunDependencyInstall=async(root)=>{const[command,args2]=dependencyInstallCommand(root);const display=[command,...args2].join(" ");const child=spawn2(command,args2,{cwd:root,stdio:"ignore"});try{const closed=await once(child,"close");return closed[0]===0?{detail:display,ok:true}:{detail:`${display} exited ${String(closed[0])}`,ok:false}}catch(error2){return{detail:`${display}: ${errorDetail3(error2)}`,ok:false}}};var hasUninstalledDependency=(root,recorded)=>Object.entries(recorded).some(([workspace,names])=>names.some((name2)=>{let directory3=path24.resolve(root,workspace);while(!existsSync13(path24.join(directory3,"node_modules",name2,"package.json"))){if(directory3===path24.resolve(root)){return true}directory3=path24.dirname(directory3)}return false}));var installDependencies=(options3,previous,plan)=>{const changed=plan.writes.length>0||canonicalJson(previous?.dependencies??{})!==canonicalJson(plan.recorded)||hasUninstalledDependency(options3.root,plan.recorded);if(!changed){return succeed6({outcome:"skipped"})}const run6=options3.runDependencyInstall??defaultRunDependencyInstall;return promise2(async()=>await run6(options3.root)).pipe(map6((result3)=>({detail:result3.detail,outcome:result3.ok?"ran":"failed"})))};var prepareScript=(manifest)=>typeof manifest==="object"&&manifest!==null&&("scripts"in manifest)&&typeof manifest.scripts==="object"&&manifest.scripts!==null&&("prepare"in manifest.scripts)?manifest.scripts.prepare:undefined;var wirePrepareScript=(root,activation)=>{const bytes=readBytes(root,"package.json");if(activation===undefined||bytes===undefined){return[]}const content=decoder2.decode(bytes);const prepare=prepareScript(JSON.parse(content));if(typeof prepare==="string"&&prepare.includes(activateGitHooksCommand)){return[]}const row={artifact:"merge",item:activation.item,path:"package.json"};if(prepare!==undefined){return[{...row,action:"kept",detail:`scripts.prepare kept; append: && ${activateGitHooksCommand}`}]}writeFileAtomic(confined(root,"package.json"),applyMerges({content,format:"json",target:"package.json",values:[{scripts:{prepare:activateGitHooksCommand}}]}));return[{...row,action:"merged",detail:`scripts.prepare: ${activateGitHooksCommand}`}]};var defaultRunHookActivation=async(root)=>{const child=spawn2("node",[activateGitHooksPath],{cwd:root,stdio:["ignore","pipe","pipe"]});let output="";const collect=(chunk)=>{output+=chunk.toString()};child.stdout.on("data",collect);child.stderr.on("data",collect);try{const closed=await once(child,"close");return closed[0]===0?{detail:output.trim(),ok:true}:{detail:`${activateGitHooksCommand} exited ${String(closed[0])}: ${output.trim()}`,ok:false}}catch(error2){return{detail:`${activateGitHooksCommand}: ${errorDetail3(error2)}`,ok:false}}};var activateHooks=(options3,activation,optedOut)=>{if(activation===undefined||optedOut){return succeed6({})}const run6=options3.runHookActivation??defaultRunHookActivation;return promise2(async()=>await run6(options3.root)).pipe(map6((result3)=>({hookActivation:{detail:result3.detail,outcome:result3.ok?"ran":"failed"}})))};var activationFailed=(report)=>report.hookActivation?.outcome==="failed";var gitOutput=(root,args2)=>{try{return execFileSync("git",args2,{cwd:root,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}};var optOutCommitGate=(root,item)=>{const optOut=(row)=>({...row,detail:`${row.detail??""}; Commit Gate Opt-Out`,item});const rows=[];const script=readBytes(root,managedHookScriptPath);if(script!==undefined){const managed=sha256Hex(script)===managedHookScriptDigest;if(managed){const absolute=confined(root,managedHookScriptPath);unlinkSync(absolute);removeEmptyParents(root,absolute)}rows.push(optOut({action:managed?"removed":"kept",artifact:"copied",detail:managed?"Managed Hook Script":"not the Managed Hook Script",path:managedHookScriptPath}))}const hooksPath=gitOutput(root,["config","--local","--get","core.hooksPath"]);if(hooksPath===undefined){return rows}if(hooksPath!==managedHooksPath){rows.push(optOut({action:"kept",detail:`core.hooksPath ${hooksPath} is not ${managedHooksPath}`,path:".git/config"}));return rows}execFileSync("git",["config","--local","--unset","core.hooksPath"],{cwd:root,stdio:"ignore"});rows.push(optOut({action:"removed",detail:`core.hooksPath ${managedHooksPath}`,path:".git/config"}));const oldHook=path24.resolve(root,gitOutput(root,["rev-parse","--git-common-dir"])??".git","hooks","pre-commit");if(existsSync13(oldHook)){rows.push(optOut({action:"kept",detail:"old hook, not deleted; Git runs it again now that core.hooksPath is unset",path:path24.relative(root,oldHook)}))}return rows};var wireHooks=(root,activation,optedOut)=>{if(!optedOut){return wirePrepareScript(root,activation)}return activation===undefined?[]:optOutCommitGate(root,activation.item)};var defaultRunLint=async(root)=>{const child=spawn2("node",[managedLintRunnerPath,"--root",root],{cwd:root,stdio:"ignore"});try{const closed=await once(child,"close");return typeof closed[0]==="number"?closed[0]:2}catch{return 2}};var lintOutcome=(code)=>{if(code===0){return"passed"}return code===1?"findings":"failed"};var runManagedLint=(options3,intent)=>{if(intent.softwareScopes.length===0||!existsSync13(path24.join(options3.root,managedLintRunnerPath))){return succeed6("skipped")}const run6=options3.runLint??defaultRunLint;return promise2(async()=>await run6(options3.root)).pipe(map6((code)=>lintOutcome(code)))};var semanticReadsStep=(options3,intent,items,wikiRoot)=>syncSemanticReads({env:options3.commandEnvironment??{},override:intent.typescript?.compilerProjects,root:options3.root,run:options3.runCommand,runtime:items.find((item)=>item.name===typegraphRuntimeItem)?.meta.hi.toolRuntime,wikiRoot});var manifestLoader=(root,overlay,load)=>async()=>{const planned=overlay.get(subagentManifestPath);if(existsSync13(path24.join(root,subagentManifestPath))||planned===undefined){return await load(root)}const staging=mkdtempSync(path24.join(tmpdir2(),"hi-subagents-"));try{writeFileAtomic(path24.join(staging,subagentManifestPath),planned);return await load(staging)}finally{rmSync3(staging,{force:true,recursive:true})}};var materializeEffect=(items,context3,options3)=>tryPromise2({catch:(cause)=>new RegistryIntegrityError({detail:errorDetail3(cause),url:options3.client.baseUrl}),try:async()=>await materialize(items,context3,options3.materializeOptions)});var fetchItems2=(client,catalog,names)=>effectForEach2(names,(name2)=>client.fetchItem(catalog,name2),{concurrency:8});var copiedOnly=(item)=>{const{harnessAdapters:_adapters,...meta}=item.meta.hi;const files=(item.files??[]).filter((file5)=>(meta.files?.[file5.path]?.artifact??"copied")==="copied");return{...item,files,meta:{hi:meta}}};var installedCopiedBytes=(options3,record2,context3)=>gen2(function*installedBytes(){const catalog=yield*options3.client.fetchCatalog(record2.baseline);const available=new Set(catalog.items.map((entry)=>entry.name));const items=yield*fetchItems2(options3.client,catalog,record2.items.filter((name2)=>available.has(name2)));const installed=yield*materializeEffect(items.map(copiedOnly),{...context3,items,shape:record2.shape},options3);return new Map(installed.effects.flatMap((effect2)=>effect2._tag==="File"?[[effect2.path,effect2.content]]:[]))}).pipe(option2);var settingsWithPacks=(root,packs)=>attempt2(settingsPath,()=>{const document=JSON.parse(decoder2.decode(readBytes(root,settingsPath)));return`${JSON.stringify({...typeof document==="object"?document:{},packs},null,2)}
|
|
350
|
+
`});var selectIntent=(options3,staged,previous,detected)=>gen2(function*select2(){if(options3.intent!==undefined||staged!==undefined){const intent2=options3.intent??(yield*withStagedSettings(staged,readProjectIntent));return{adopted:[],intent:intent2,settings:staged}}const intent=yield*readProjectIntent(options3.root);const known=previous?.detectedPacks??detected;const adopted=detected.filter((id)=>!known.includes(id)&&!intent.packs.includes(id));if(adopted.length===0){return{adopted,intent,settings:undefined}}const packs=[...intent.packs,...adopted].toSorted();return{adopted,intent:{...intent,packs},settings:yield*settingsWithPacks(options3.root,packs)}});var absentAuthored=(root,effects)=>new Map(effects.flatMap((effect2)=>effect2._tag==="File"&&effect2.artifact==="authored"&&lstat3(confined(root,effect2.path))===undefined?[[effect2.path,effect2.content]]:[]));var planWithOverlay=(options3,base)=>gen2(function*planInstall(){const load=options3.loadSubagentManifest??loadSubagentManifest;const readCommittedFile=committedFileReader(options3.root);const contextWith3=(overlay2)=>({...base,loadSubagentManifest:manifestLoader(options3.root,overlay2,load),readCommittedFile,readRepositoryFile:repositoryReader(options3.root,overlay2)});const first=yield*materializeEffect(base.items,contextWith3(new Map),options3);const overlay=yield*attempt2(".",()=>absentAuthored(options3.root,first.effects));if(overlay.size===0){return{context:contextWith3(overlay),materialized:first}}const context3=contextWith3(overlay);return{context:context3,materialized:yield*materializeEffect(base.items,context3,options3)}});var splitPlan=(effects)=>({dependencies:effects.filter((effect2)=>effect2._tag==="Dependency"),files:effects.filter((effect2)=>effect2._tag==="File"),links:effects.filter((effect2)=>effect2._tag==="Symlink"),merges:effects.filter((effect2)=>effect2._tag==="Merge")});var firstInvalidMergeTarget=(root,plan,previous)=>gen2(function*validateTargets(){const targets=new Map(plan.merges.map((merge6)=>[merge6.target,merge6.format]));const workspaces=[...plan.dependencies.map((dependency)=>dependency.workspace),...Object.keys(previous?.dependencies??{})];for(const workspace of workspaces){targets.set(workspacePackageJson(workspace),"json")}for(const[target,format4]of targets){const invalid2=yield*option2(flip2(validateMergeTarget(root,target,format4)));if(isSome2(invalid2)){return invalid2}}return none2()});var copiedChange=(input,effect2,local)=>{if(input.previous===undefined){const digest2=input.legacyDigests?.get(effect2.path);return{localEdit:digest2!==undefined&&sha256Hex(local)!==digest2,upstreamChanged:digest2===undefined||sha256Hex(effect2.content)!==digest2}}const installed=input.installed?.get(effect2.path);return{localEdit:input.previous.paths[effect2.path]?.artifact==="copied"&&(installed===undefined||!sameNormalized(installed,local)),upstreamChanged:installed===undefined||!sameNormalized(installed,effect2.content)}};var decideCopied=(input,effect2,local)=>{const{localEdit,upstreamChanged}=copiedChange(input,effect2,local);if(!localEdit||sameNormalized(local,effect2.content)){return{action:"written",conflict:false,write:true}}if(input.yes){return{action:"overwritten-local-edit",conflict:false,write:true}}return{action:"kept",conflict:upstreamChanged,detail:upstreamChanged?"conflict: local edit and upstream change; run hi update --yes to overwrite":"local edit; run hi update --yes to restore the Baseline version",write:false}};var applyCopied=(input,effect2)=>{const local=readBytes(input.root,effect2.path);if(local!==undefined&&sameBytes2(local,effect2.content)){if(executableMatches(input.root,effect2)){return{action:"skipped",conflict:false,write:false}}chmodSync2(confined(input.root,effect2.path),fileMode(effect2));return{action:"written",conflict:false,write:false}}const decision=local===undefined?{action:"written",conflict:false,write:true}:decideCopied(input,effect2,local);if(decision.write){writeFile3(input.root,effect2)}return decision};var applyFile=(input,effect2)=>{const{root}=input;if(effect2.artifact==="copied"){return applyCopied(input,effect2)}if(effect2.artifact==="authored"){if(lstat3(confined(root,effect2.path))!==undefined){return{action:"kept",conflict:false,write:false}}writeFile3(root,effect2);return{action:"created",conflict:false,write:true}}const local=readBytes(root,effect2.path);if(local!==undefined&&sameBytes2(local,effect2.content)&&executableMatches(root,effect2)){return{action:"skipped",conflict:false,write:false}}writeFile3(root,effect2);return{action:"written",conflict:false,write:true}};var fileRow=(effect2,decision)=>({action:decision.action,artifact:effect2.artifact,...decision.detail===undefined?{}:{detail:decision.detail},item:effect2.item,path:effect2.path});var applyMergeTarget=(root,merges)=>{const[first]=merges;const target=first?.target??"";const bytes=readBytes(root,target);const content=bytes===undefined?bytes:decoder2.decode(bytes);const next=applyMerges({content,format:first?.format??"json",target,values:merges.map((merge6)=>merge6.value)});const item=[...new Set(merges.map((merge6)=>merge6.item))].join(",");if(next===content){return{action:"skipped",artifact:"merge",item,path:target}}writeFileAtomic(confined(root,target),next);return{action:"merged",artifact:"merge",item,path:target}};var isEditedCopy=(input,relative)=>{const installed=input.installed?.get(relative);const local=readBytes(input.root,relative);return local!==undefined&&(installed===undefined||!sameNormalized(installed,local))};var applyLink=(input,effect2)=>{const{root}=input;const recorded=input.previous?.paths[effect2.path]?.artifact;try{const absolute=confined(root,effect2.path);if(!isInside(root,path24.resolve(path24.dirname(absolute),effect2.target))){return{failure:"link target is outside the repository",linked:false}}const existing=lstat3(absolute);if(existing?.isSymbolicLink()===true){if(readlinkSync3(absolute)===effect2.target){return{linked:false}}unlinkSync(absolute)}else if(existing?.isDirectory()===true&&readdirSync5(absolute).length===0){rmdirSync2(absolute)}else if(existing?.isFile()===true&&(recorded==="copied"||recorded==="built")){if(recorded==="copied"&&!input.yes&&isEditedCopy(input,effect2.path)){return{failure:"local edit of a Copied file the Baseline now links; run hi update --yes to replace it",linked:false}}unlinkSync(absolute)}else if(existing!==undefined){return{failure:"path exists and is not a symlink",linked:false}}mkdirSync3(path24.dirname(absolute),{recursive:true});symlinkSync(effect2.target,absolute);return{linked:true}}catch(error2){return{failure:errorDetail3(error2),linked:false}}};var applyStale=(input,stalePath,recorded)=>{const absolute=confined(input.root,stalePath);const existing=lstat3(absolute);const base={artifact:recorded.artifact,item:recorded.item,path:stalePath};if(existing===undefined){return[]}if(recorded.artifact==="authored"){return[{...base,action:"stale-reported"}]}const removable=recorded.artifact==="symlink"?existing.isSymbolicLink():existing.isFile();if(!removable){return[]}if(recorded.artifact==="copied"&&!input.yes&&isEditedCopy(input,stalePath)){return[{...base,action:"stale-reported",detail:"local edit; no longer in the Baseline. Delete it, or run hi update --yes to remove it"}]}unlinkSync(absolute);removeEmptyParents(input.root,absolute);return[{...base,action:"removed"}]};var refusedReport=(options3,previous,refusal)=>({dependencyInstall:"skipped",failedLinks:[],lint:"skipped",migration:notMigrated,mode:options3.mode,...previous===undefined?{}:{previous:previous.baseline},refusal,requiredTools:[],rows:[],status:"refused"});var applyFiles=(input,files,artifact)=>gen2(function*applyFileKind(){const rows=[];let conflicts=0;for(const effect2 of files.filter((file5)=>file5.artifact===artifact)){const decision=yield*attempt2(effect2.path,()=>applyFile(input,effect2));conflicts+=decision.conflict?1:0;rows.push(fileRow(effect2,decision))}return{conflicts,rows}});var applyLinks=(input,links)=>{const rows=[];const failedLinks=[];for(const effect2 of links){const result3=applyLink(input,effect2);const base={artifact:"symlink",item:effect2.item,path:effect2.path};if(result3.failure===undefined){rows.push({...base,action:result3.linked?"linked":"skipped",detail:`-> ${effect2.target}`})}else{failedLinks.push({path:effect2.path,reason:result3.failure,target:effect2.target});rows.push({...base,action:"link-failed",detail:`-> ${effect2.target}: ${result3.failure}`})}}return{failedLinks,rows}};var applyStalePaths=(input,planned)=>gen2(function*removeStale(){const rows=[];const stale=Object.entries(input.previous?.paths??{}).filter(([stalePath])=>!planned.has(stalePath)).toSorted(([left],[right])=>left.localeCompare(right));for(const[stalePath,recorded]of stale){rows.push(...yield*attempt2(stalePath,()=>applyStale(input,stalePath,recorded)))}return rows});var projectSkillMoveRow=(move2)=>({action:projectSkillMoveAction(move2),detail:`from ${move2.from}`,path:move2.to});var migrationRows=(migrated,deleted)=>[...deleted.map((deletedPath)=>({action:"migrated-deleted",path:deletedPath})),...migrated.skipped.map((skip)=>({action:"migrated-skipped",detail:skip.reason,path:skip.path})),...migrated.movedProjectSkills.map(projectSkillMoveRow)];var withKeptCopies=(planned,previous,kept)=>{const recordedPaths=new Map(planned);for(const keptPath of kept){const recorded=previous?.paths[keptPath];if(recorded?.artifact==="copied"){recordedPaths.set(keptPath,recorded)}}return recordedPaths};var runInstall=(options3)=>gen2(function*install2(){const{client,root,yes}=options3;const completed=(step)=>sync2(()=>options3.onStep?.(step));const rows=[];const previous=yield*readInstalledRecord(root);const catalog=yield*client.fetchLatestCatalog;if(!satisfiesVersionRange(options3.cliVersion,catalog.cliVersionRange)){return refusedReport(options3,previous,{_tag:"CliOutsideRange",baseline:catalog.version,cliVersion:options3.cliVersion,cliVersionRange:catalog.cliVersionRange})}yield*completed("STEP-001");const detected=proposePacks(yield*repositoryDetection(root),catalog);const migration=yield*planMigration(root,{detectShapePacks:detected,...options3.settings===undefined?{}:{settings:options3.settings}});const staged=migration?.settings??options3.settings;yield*completed("migration");const{adopted,intent,settings}=yield*selectIntent(options3,staged,previous,detected);const names=yield*resolveItemNames(catalog,intent);const items=yield*fetchItems2(client,catalog,names);yield*client.fetchCatalog(catalog.version).pipe(ignore2);yield*completed("STEP-002");const shape=yield*detectShape(root,intent.packs);const{context:context3,materialized}=yield*planWithOverlay(options3,{items,settings:intent,shape});const optedOut=intent.commitGate==="disabled";const plan=splitPlan(materialized.effects);const installed=previous===undefined||yes?none2():yield*installedCopiedBytes(options3,previous,context3);yield*completed("STEP-003");const invalid2=yield*firstInvalidMergeTarget(root,plan,previous);if(isSome2(invalid2)){return refusedReport(options3,previous,{_tag:"InvalidMergeTarget",detail:invalid2.value.detail,path:invalid2.value.path})}yield*completed("STEP-004");if(settings!==undefined){yield*writeSettings(root,settings)}const migrated=migration===undefined?notMigrated:yield*applyMigration(root,migration);const skillMoves=yield*attempt2(".agents/skills",()=>prepareProjectSkills({baselineOwned:new Set([...Object.keys(previous?.paths??{}),...migration?.previouslyManagedPaths??[]]),plannedFiles:new Map(plan.files.map((file5)=>[file5.path,file5.content])),root}));rows.push(...skillMoves.map(projectSkillMoveRow));yield*completed("project-skills");const fileInput={installed:getOrUndefined(installed),legacyDigests:migration?.managedDigests,previous,root,yes};const copied=yield*applyFiles(fileInput,plan.files,"copied");rows.push(...copied.rows);yield*completed("STEP-005");rows.push(...(yield*applyFiles(fileInput,plan.files,"built")).rows);yield*completed("STEP-006");rows.push(...(yield*applyFiles(fileInput,plan.files,"authored")).rows);yield*completed("STEP-007");for(const target of new Set(plan.merges.map((merge6)=>merge6.target))){const targetMerges=plan.merges.filter((merge6)=>merge6.target===target);rows.push(yield*attempt2(target,()=>applyMergeTarget(root,targetMerges)))}yield*completed("STEP-008");const linked=applyLinks(fileInput,plan.links);rows.push(...linked.rows);yield*completed("STEP-009");const dependencyPlan=yield*attempt2("package.json",()=>planDependencies({managedPaths:new Set([...plan.files.map((file5)=>file5.path),...Object.keys(previous?.paths??{})]),recorded:previous?.dependencies,required:plan.dependencies,root}));for(const write2 of dependencyPlan.writes){yield*attempt2(write2.path,()=>{writeFileAtomic(confined(root,write2.path),write2.content)})}rows.push(...dependencyPlan.rows);const activation=plan.files.find((file5)=>file5.path===activateGitHooksPath);rows.push(...yield*attempt2("package.json",()=>wireHooks(root,activation,optedOut)));const dependencyInstall=yield*installDependencies(options3,previous,dependencyPlan);const hookActivation=yield*activateHooks(options3,activation,optedOut);yield*completed("STEP-010");const planned=new Map([...plan.files.map((file5)=>[file5.path,{artifact:file5.artifact,item:file5.item}]),...plan.links.map((link4)=>[link4.path,{artifact:"symlink",item:link4.item}])]);const staleRows=yield*applyStalePaths(fileInput,planned);rows.push(...staleRows);const recordedPaths=withKeptCopies(planned,previous,[...staleRows.filter((row)=>row.action==="stale-reported").map((row)=>row.path),...linked.failedLinks.map((link4)=>link4.path)]);yield*completed("STEP-011");const finalized=migration===undefined?[]:yield*finalizeMigration(root);const migrationDeleted=[...migrated.deleted,...finalized].toSorted();rows.push(...migrationRows(migrated,migrationDeleted));yield*completed("finalize-migration");yield*writeInstalledRecord(root,{baseline:catalog.version,dependencies:dependencyPlan.recorded,detectedPacks:detected,failedLinks:linked.failedLinks,items:names,paths:Object.fromEntries(recordedPaths),schemaVersion:1,shape});yield*completed("STEP-012");const semanticReads=yield*semanticReadsStep(options3,intent,items,shape.wikiRoot);yield*completed("semantic-reads");const lint=yield*runManagedLint(options3,intent);yield*completed("STEP-013");const problems=copied.conflicts+linked.failedLinks.length;return{...adopted.length===0?{}:{adoptedPacks:adopted},...hookActivation,applied:catalog.version,dependencyInstall:dependencyInstall.outcome,...dependencyInstall.detail===undefined?{}:{dependencyInstallDetail:dependencyInstall.detail},failedLinks:linked.failedLinks,lint,migration:{...migrated,deleted:migrationDeleted},mode:options3.mode,...previous===undefined?{}:{previous:previous.baseline},requiredTools:materialized.requiredTools,rows,semanticReads,status:problems>0||dependencyInstall.outcome==="failed"||activationFailed(hookActivation)?"partial":"applied"}});var sorted3=(values)=>[...new Set(values)].toSorted();var refused=(catalog,cliVersion,previous)=>({dependencyInstall:"skipped",failedLinks:[],lint:"skipped",migration:notMigrated,mode:"init",...previous===undefined?{}:{previous},refusal:{_tag:"CliOutsideRange",baseline:catalog.version,cliVersion,cliVersionRange:catalog.cliVersionRange},requiredTools:[],rows:[],status:"refused"});var requiredToolsFor=(requiredTools,repositoryManager)=>sorted3([...requiredTools.filter((tool)=>!providerCliTools.includes(tool)),...isRepositoryManager(repositoryManager)?requiredToolsForRepositoryManager(repositoryManager):[]]);var defaultProviders=(existing,inferredManager)=>{const repositoryManager=existing?.repositoryManager??inferredManager;const backlogProvider=existing?.backlogProvider??(isBacklogProvider(repositoryManager)?repositoryManager:undefined);const assetProviderSlug=existing?.assetProviderSlug??(isAssetProvider(backlogProvider)?backlogProvider:undefined);return{...assetProviderSlug===undefined?{}:{assetProviderSlug},...backlogProvider===undefined?{}:{backlogProvider},...repositoryManager===undefined?{}:{repositoryManager}}};var keptIntent=(existing)=>({...existing?.backlogProjectUrl===undefined?{}:{backlogProjectUrl:existing.backlogProjectUrl},...existing?.commitGate===undefined?{}:{commitGate:existing.commitGate},...existing?.registry===undefined?{}:{registry:existing.registry}});var defaultIntent=(existing,proposed,inferredManager)=>{const providers=defaultProviders(existing,inferredManager);return{...keptIntent(existing),...providers,lintDisabledAssets:sorted3(existing?.lint?.disabledAssets??[]),lintExclude:sorted3(existing?.lint?.exclude??[]),packs:sorted3(existing?.packs??proposed.packs),requiredTools:requiredToolsFor(existing?.requiredTools??[],providers.repositoryManager),softwareScopes:sorted3(existing?.lint?.scopes??proposed.softwareScopes)}};var packChoices=(catalog)=>catalog.items.flatMap((entry)=>{const{pack}=entry.meta.hi;return entry.meta.hi.kind==="pack"&&pack!==undefined&&entry.name!==corePackName?[{category:pack.category,id:entry.name.replace(/^pack-/u,""),...entry.description===undefined?{}:{description:entry.description}}]:[]});var proposeInit=(root,catalog)=>gen2(function*propose(){const existing=yield*readSettingsDocument(root);const detection=yield*detectRepository(root).pipe(mapError3((cause)=>new InstallerFilesystemError({detail:cause.message,path:"."})));const shape=yield*detectShape(root,[]);const defaults2=defaultIntent(existing,{packs:proposePacks(detection,catalog),softwareScopes:proposeSoftwareScopes(shape)},inferRepositoryManager(root));const proposal={catalog,defaults:defaults2,packs:packChoices(catalog),workspaces:sorted3([...shape.workspaces.map((workspace)=>workspace.path),...defaults2.softwareScopes])};return proposal});var readSettingsText=(root)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:settingsPath}),try:()=>{const absolute=path25.join(root,settingsPath);return existsSync14(absolute)?readFileSync15(absolute,"utf-8"):undefined}});var initSettings=(root,intent)=>gen2(function*render(){const current2=yield*readSettingsText(root);return yield*withStagedSettings(current2,(staging)=>writeInitSettings(staging,intent).pipe(andThen2(readSettingsText(staging)),map6((text3)=>text3??"")))});var unavailableReport=(mode,error2)=>({detail:`${error2.detail} (${error2.url})`,mode,status:"unavailable"});var runInit=(options3)=>gen2(function*init(){const{client,cliVersion,root}=options3;const catalog=yield*client.fetchLatestCatalog;if(!satisfiesVersionRange(cliVersion,catalog.cliVersionRange)){const previous=yield*readInstalledRecord(root);return refused(catalog,cliVersion,previous?.baseline)}const proposal=yield*proposeInit(root,catalog);const selected=yield*options3.confirm(proposal);const settings=yield*initSettings(root,{...selected,requiredTools:requiredToolsFor(selected.requiredTools,selected.repositoryManager)});const result3=yield*runInstall({cliVersion,client,mode:"init",root,settings,yes:options3.yes,...options3.commandEnvironment===undefined?{}:{commandEnvironment:options3.commandEnvironment},...options3.runCommand===undefined?{}:{runCommand:options3.runCommand},...options3.runDependencyInstall===undefined?{}:{runDependencyInstall:options3.runDependencyInstall},...options3.runHookActivation===undefined?{}:{runHookActivation:options3.runHookActivation},...options3.runLint===undefined?{}:{runLint:options3.runLint}});return result3}).pipe(catchIf2((error2)=>is2(RegistryUnavailable)(error2),(error2)=>succeed6(unavailableReport("init",error2))));import{createInterface as createInterface2}from"node:readline/promises";import{stdin as input,stdout as output}from"node:process";var makePromptInteraction=({createReadline,input})=>{const initialRawMode=input.isRaw===true;const initiallyPaused=input.isPaused?.()===true;const readline2=createReadline();const restoreInput=()=>{if(input.isTTY===true&&input.isRaw!==initialRawMode){input.setRawMode(initialRawMode)}if(initiallyPaused){input.pause()}else{input.resume()}};return{close:()=>{readline2.close();restoreInput()},readLine:async(question)=>{if(input.isTTY===true&&input.isRaw===true){input.setRawMode(false)}input.resume();readline2.resume();try{return await readline2.question(question)}finally{restoreInput()}},runSelection:(effect2)=>sync2(()=>readline2.pause()).pipe(andThen2(effect2),ensuring2(sync2(()=>{readline2.resume();restoreInput()})))}};var localMultiSelect=(options3)=>exports_Prompt.run(exports_Prompt.multiSelect({choices:options3.choices,maxPerPage:options3.maxPerPage??10,message:options3.message,selectAll:options3.selectAll??"Select all",selectNone:options3.selectNone??"Clear all"})).pipe(map6((values)=>values.toSorted()));var localSingleSelect=(options3)=>exports_Prompt.run(exports_Prompt.select({choices:options3.choices.map((choice4)=>({...choice4,selected:choice4.value===options3.defaultValue})),maxPerPage:options3.maxPerPage??10,message:options3.message}));var CliPrompt=Service("@punks/cli/ui/CliPrompt");var PromptLive=acquireRelease2(sync2(()=>makePromptInteraction({createReadline:()=>createInterface2({input,output}),input})),(interaction)=>sync2(interaction.close)).pipe(map6((interaction)=>({multiSelect:({message,choices,selectAll,selectNone})=>interaction.runSelection(localMultiSelect({choices,message,...selectAll===undefined||selectAll===""?{}:{selectAll},...selectNone===undefined||selectNone===""?{}:{selectNone}})).pipe(map6((values)=>values.toSorted()),mapError3((cause)=>new CliPromptError({cause,message:"Failed to read checklist input."}))),readLine:(question)=>tryPromise2({catch:(cause)=>new CliPromptError({cause,message:"Failed to read CLI input."}),try:async()=>await interaction.readLine(question)}),singleSelect:({message,choices,defaultValue})=>interaction.runSelection(localSingleSelect({choices,message,...defaultValue===undefined||defaultValue===""?{}:{defaultValue}})).pipe(mapError3((cause)=>new CliPromptError({cause,message:"Failed to read selection input."}))),writeLine:(line)=>callback2((resume)=>{output.write(`${line}
|
|
351
351
|
`,()=>{resume(void_3)})})})));var makeCliPromptLayer=(promptEffect=PromptLive)=>effect(CliPrompt,gen2(function*makeLazyPrompt(){const scope3=yield*scope2;const cachedPrompt=yield*cached2(provide(promptEffect,scope3));return{multiSelect:(options3)=>cachedPrompt.pipe(flatMap3((prompt)=>prompt.multiSelect(options3))),readLine:(question)=>cachedPrompt.pipe(flatMap3((prompt)=>prompt.readLine(question))),singleSelect:(options3)=>cachedPrompt.pipe(flatMap3((prompt)=>prompt.singleSelect(options3))),writeLine:(line)=>cachedPrompt.pipe(flatMap3((prompt)=>prompt.writeLine(line)))}}));var cliPromptLayer=makeCliPromptLayer();var backlogProviderChoices=[{title:"GitHub Projects and Issues",value:"github"},{title:"Linear",value:"linear"},{title:"Azure DevOps",value:"azure-devops"},{title:"monday.com",value:"monday"}];var assetChoices=[...backlogProviderChoices,{title:"GitLab",value:"gitlab"},{title:"Bitbucket",value:"bitbucket"}];var repositoryChoices=[{title:"GitHub",value:"github"},{title:"GitLab",value:"gitlab"},{title:"Azure DevOps",value:"azure-devops"},{title:"Bitbucket",value:"bitbucket"}];var commitGateChoices=[{title:"Enabled",value:"enabled"},{title:"Disabled",value:"disabled"}];var invalid2=(message)=>({_tag:"Invalid",message});var validateBacklogProjectUrl=(input2,backlogProvider)=>{const value3=input2.trim();if(value3===""){return{_tag:"Valid",value:undefined}}let url;try{url=new URL(value3)}catch{return invalid2("Backlog project URL must be an absolute HTTP(S) URL. Rerun `hi init`.")}if(url.protocol!=="http:"&&url.protocol!=="https:"){return invalid2("Backlog project URL must be an absolute HTTP(S) URL. Rerun `hi init`.")}if(backlogProvider!=="linear"){return{_tag:"Valid",value:value3}}const segments=url.pathname.split("/").filter(Boolean);if(url.hostname==="linear.app"&&segments[1]==="project"){return invalid2("A legacy Linear Project URL cannot identify the backlog root. Enter the root Initiative URL when you rerun `hi init`.")}if(url.hostname!=="linear.app"||segments[1]!=="initiative"||segments.length<3){return invalid2("A Linear backlog destination must be a root Initiative URL. Rerun `hi init`.")}return{_tag:"Valid",value:value3}};var selectOne=(prompt,options3)=>prompt.singleSelect({choices:options3.choices,defaultValue:options3.defaultValue,message:options3.message}).pipe(filterOrFail2(options3.is,(value3)=>new CliPromptError({message:`Invalid selection: ${value3}.`})));var isCommitGatePolicy=(value3)=>value3==="enabled"||value3==="disabled";var promptInitSelection=(prompt,proposal)=>gen2(function*confirmInitSelection(){const{defaults:defaults2}=proposal;const packs=yield*prompt.multiSelect({choices:proposal.packs.map((pack)=>({...pack.description===undefined?{}:{description:pack.description},selected:defaults2.packs.includes(pack.id),title:pack.id,value:pack.id})),message:"Select Packs (detected and default Packs are preselected)"});const softwareScopes=yield*prompt.multiSelect({choices:proposal.workspaces.map((workspace)=>({selected:defaults2.softwareScopes.includes(workspace),title:workspace,value:workspace})),message:"Select Software Scopes (managed lint runs inside each)"});const repositoryManager=yield*selectOne(prompt,{choices:repositoryChoices,defaultValue:defaults2.repositoryManager??"github",is:isRepositoryManager,message:"Select repository manager"});const backlogProvider=yield*selectOne(prompt,{choices:backlogProviderChoices,defaultValue:defaults2.backlogProvider??(isBacklogProvider(repositoryManager)?repositoryManager:"github"),is:isBacklogProvider,message:"Select backlog provider"});const assetProviderSlug=yield*selectOne(prompt,{choices:assetChoices,defaultValue:defaults2.assetProviderSlug??backlogProvider,is:isAssetProvider,message:"Select asset provider"});const commitGate=yield*selectOne(prompt,{choices:commitGateChoices,defaultValue:defaults2.commitGate??"enabled",is:isCommitGatePolicy,message:"Select Commit Gate policy"});const currentUrl=defaults2.backlogProvider===backlogProvider?defaults2.backlogProjectUrl:undefined;const answer=yield*prompt.readLine(`Backlog project URL (empty for none${currentUrl===undefined?"":`; current: ${currentUrl}`}): `);const backlogProjectUrl=validateBacklogProjectUrl(answer,backlogProvider);if(backlogProjectUrl._tag==="Invalid"){return yield*new CliPromptError({message:backlogProjectUrl.message})}const{backlogProjectUrl:_previousUrl,softwareScopes:_previousScopes,packs:_previousPacks,...kept}=defaults2;return{...kept,assetProviderSlug,backlogProvider,...backlogProjectUrl.value===undefined?{}:{backlogProjectUrl:backlogProjectUrl.value},commitGate,packs,repositoryManager,softwareScopes}});var initCommandMetadata=declareCommandMetadata({examples:[{command:"hi init",summary:"Confirm the proposed Packs and Software Scopes, then install."},{command:"hi init --yes",summary:"Accept the proposal without prompts."}],group:"commands",interaction:"optional",name:"init",options:[{name:"yes",summary:"Accept the proposed selection without prompts and overwrite locally edited Copied Artifacts."},{name:"json",summary:"Print the machine-readable install report to stdout."}],outputModes:["interactive","plain","json"],summary:"Detect the repository, confirm Packs and Software Scopes, and install the latest Baseline."});var yesOption=exports_Flag.boolean(metadataOptionName(initCommandMetadata,"yes")).pipe(withOptionMetadata(initCommandMetadata,"yes"));var jsonOption3=exports_Flag.boolean(metadataOptionName(initCommandMetadata,"json")).pipe(withOptionMetadata(initCommandMetadata,"json"));var acceptProposal=(proposal)=>succeed6(proposal.defaults);var initCommand=exports_Command.make(initCommandMetadata.name,{json:jsonOption3,yes:yesOption},({yes})=>gen2(function*runInitCommand(){const{commandEnvironment:commandEnvironment2}=yield*CliRuntimeConfig;const outputMode=yield*SelectedOutputMode;const root=process.cwd();const client=registryClientFor(root);const interactive=outputMode==="interactive"&&!yes;const prompt=yield*CliPrompt;const result3=yield*lifecycleFailure(runInit({cliVersion:version2,client,confirm:interactive?(proposal)=>promptInitSelection(prompt,proposal):acceptProposal,commandEnvironment:commandEnvironment2,root,yes}));yield*publishDocument({exitCode:installExitCode(result3),human:withRegistryNotice({client,human:formatInstallHuman(result3)}),json:result3})})).pipe(withCommandMetadata(initCommandMetadata));import path27 from"node:path";import{createHash as createHash4}from"node:crypto";import{execFileSync as execFileSync2}from"node:child_process";import{accessSync as accessSync2,constants as constants3,existsSync as existsSync15,readFileSync as readFileSync16,realpathSync as realpathSync3}from"node:fs";import path26 from"node:path";var digest2=(content)=>createHash4("sha256").update(content).digest("hex");var read2=(filePath)=>{try{return existsSync15(filePath)?readFileSync16(filePath,"utf-8"):null}catch{return null}};var indent=(line)=>line.length-line.trimStart().length;var managedLintCommand=(config)=>{const lines2=config.split(`
|
|
352
352
|
`);const preCommit=lines2.findIndex((line)=>line.trim()==="pre-commit:");if(preCommit===-1){return null}const preIndent=indent(lines2[preCommit]);const preCommitEnd=lines2.findIndex((line,index)=>index>preCommit&&line.trim()!==""&&indent(line)<=preIndent);const preCommitLimit=preCommitEnd===-1?lines2.length:preCommitEnd;const commands=lines2.findIndex((line,index)=>index>preCommit&&index<preCommitLimit&&line.trim()==="commands:"&&indent(line)>preIndent);if(commands===-1){return null}const commandsIndent=indent(lines2[commands]);const end2=lines2.findIndex((line,index)=>index>commands&&line.trim()!==""&&indent(line)<=commandsIndent);const limit=end2===-1?lines2.length:end2;const lint=lines2.findIndex((line,index)=>index>commands&&index<limit&&line.trim()==="lint:"&&indent(line)>commandsIndent);if(lint===-1){return null}const lintIndent=indent(lines2[lint]);const lintEnd=lines2.findIndex((line,index)=>index>lint&&line.trim()!==""&&!line.trimStart().startsWith("#")&&indent(line)<=lintIndent);const lintLimit=lintEnd===-1?limit:Math.min(limit,lintEnd);const lintFields=lines2.slice(lint+1,lintLimit).filter((line)=>line.trim()!==""&&!line.trimStart().startsWith("#"));const fieldIndent=lintFields[0]===undefined?undefined:indent(lintFields[0]);const run6=lintFields.find((line)=>line.trimStart().startsWith("run:")&&indent(line)===fieldIndent);return run6?.slice(run6.indexOf(":")+1).trim()===managedCommitGateCommand?managedCommitGateCommand:null};var isRecord9=(value3)=>typeof value3==="object"&&value3!==null;var isConfinedRelativePath=(relativePath)=>relativePath===""||relativePath!==".."&&!relativePath.startsWith(`..${path26.sep}`)&&!path26.isAbsolute(relativePath);var confinedPackageDirectory=({candidate,rootDirectory})=>{try{const canonicalRoot=realpathSync3(rootDirectory);const packageDirectory=path26.resolve(rootDirectory,candidate);const canonicalPackageDirectory=realpathSync3(packageDirectory);const canonicalManifest=realpathSync3(path26.join(packageDirectory,"package.json"));const directoryRelative=path26.relative(canonicalRoot,canonicalPackageDirectory);const manifestRelative=path26.relative(canonicalRoot,canonicalManifest);return isConfinedRelativePath(directoryRelative)&&isConfinedRelativePath(manifestRelative)?packageDirectory:null}catch{return null}};var commitGatePackageDirectory=(rootDirectory)=>{const resolvedRoot=path26.resolve(rootDirectory);const rootPackageDirectory=confinedPackageDirectory({candidate:".",rootDirectory});if(rootPackageDirectory!==null){return rootPackageDirectory}const contracts=read2(path26.join(rootDirectory,".devpunks","commit-gate-contracts.json"));if(contracts===null){return resolvedRoot}try{const parsed=JSON.parse(contracts);if(!Array.isArray(parsed)){return resolvedRoot}for(const contract of parsed){if(!isRecord9(contract)||typeof contract.path!=="string"){continue}const packageDirectory=confinedPackageDirectory({candidate:contract.path,rootDirectory});if(packageDirectory!==null){return packageDirectory}}return resolvedRoot}catch{return resolvedRoot}};var packageDeclaration=(rootDirectory)=>{const packageJson=read2(path26.join(rootDirectory,"package.json"));if(packageJson===null){return null}try{const parsed=JSON.parse(packageJson);if(!isRecord9(parsed)){return null}const dependencies=isRecord9(parsed.dependencies)?parsed.dependencies:undefined;const devDependencies=isRecord9(parsed.devDependencies)?parsed.devDependencies:undefined;const declaration=devDependencies?.lefthook??dependencies?.lefthook;return typeof declaration==="string"?declaration:null}catch{return null}};var packageLockResolution=(rootDirectory)=>{for(const fileName of["package-lock.json","npm-shrinkwrap.json"]){const lockfile=read2(path26.join(rootDirectory,fileName));if(lockfile===null){continue}try{const parsed=JSON.parse(lockfile);if(!isRecord9(parsed)){continue}const packages=isRecord9(parsed.packages)?parsed.packages:undefined;const dependencies=isRecord9(parsed.dependencies)?parsed.dependencies:undefined;const rawEntry=packages?.["node_modules/lefthook"]??dependencies?.lefthook;if(isRecord9(rawEntry)){return{integrity:typeof rawEntry.integrity==="string"?rawEntry.integrity:null,version:typeof rawEntry.version==="string"?rawEntry.version:null}}}catch{return{integrity:null,version:null}}}return{integrity:null,version:null}};var bunLockResolution=(rootDirectory)=>{const lockfile=read2(path26.join(rootDirectory,"bun.lock"));if(lockfile===null){return{integrity:null,version:null}}const entry=/^\s*"lefthook":\s*\[\s*"lefthook@(?<version>[^"]+)"[^\n]*?(?<integrity>sha512-[^"]+)"/mu.exec(lockfile);return{integrity:entry?.groups?.integrity??null,version:entry?.groups?.version??null}};var textLockResolution=(rootDirectory)=>{for(const fileName of["pnpm-lock.yaml","yarn.lock"]){const lockfile=read2(path26.join(rootDirectory,fileName));if(lockfile===null){continue}const match8=/lefthook[^\n]*\n(?:[^\n]*\n)*?\s+version:\s*["']?(?<version>[^"'\s]+)|lefthook[^\n]*:\s*\n\s+version\s+["'](?<yarnVersion>[^"']+)["']/mu.exec(lockfile);if(match8!==null){return{integrity:null,version:match8.groups?.version??match8.groups?.yarnVersion??null}}return{integrity:null,version:"unknown"}}if(existsSync15(path26.join(rootDirectory,"bun.lockb"))){return{integrity:null,version:"unknown"}}return{integrity:null,version:null}};var installedResolution=(rootDirectory)=>{const packageJson=read2(path26.join(rootDirectory,"node_modules","lefthook","package.json"));if(packageJson===null){return{integrity:null,version:null}}try{const parsed=JSON.parse(packageJson);return{integrity:null,version:isRecord9(parsed)&&typeof parsed.version==="string"?parsed.version:null}}catch{return{integrity:null,version:null}}};class CommitGateProbeFailure extends TaggedErrorClass()("@punks/cli/commit-gate/ProbeFailure",{cause:Unknown2}){}var probeCommand=(executable,args2,rootDirectory)=>runSync2(try_3({catch:(cause)=>new CommitGateProbeFailure({cause}),try:()=>{if(path26.isAbsolute(executable)){accessSync2(executable,constants3.X_OK)}return execFileSync2(executable,args2,{cwd:rootDirectory,encoding:"utf-8",maxBuffer:64*1024,stdio:["ignore","pipe","ignore"],timeout:5000}).trim()}}).pipe(match6({onFailure:()=>null,onSuccess:(output2)=>output2})));var isExecutable=(file5)=>runSync2(try_3({catch:(cause)=>new CommitGateProbeFailure({cause}),try:()=>{accessSync2(file5,constants3.X_OK);return true}}).pipe(match6({onFailure:()=>false,onSuccess:(value3)=>value3})));var observedDependencyVersion=(rootDirectory)=>{const declaration=packageDeclaration(rootDirectory);if(declaration===null||declaration!==lefthookVersion){return declaration}const lockResolutions=[packageLockResolution(rootDirectory),bunLockResolution(rootDirectory),textLockResolution(rootDirectory)];const resolutions=[...lockResolutions,installedResolution(rootDirectory)];const resolvedVersion=resolutions.find(({version:version4})=>version4!==null&&version4!==lefthookVersion)?.version;if(resolvedVersion!==undefined){return resolvedVersion}if(!lockResolutions.some(({version:version4})=>version4===lefthookVersion)){return`${lefthookVersion}#lock-unverified`}const integrityDrift=resolutions.some(({integrity})=>integrity!==null&&integrity!==lefthookIntegrity);if(integrityDrift){return`${lefthookVersion}#integrity-drift`}if(installedResolution(rootDirectory).version!==lefthookVersion){return`${lefthookVersion}#not-installed`}const executable=path26.join(rootDirectory,"node_modules",".bin","lefthook");const output2=probeCommand(executable,["--version"],rootDirectory);const version3=output2?.match(/^(?:lefthook version v?|v)?(?<version>\d+\.\d+\.\d+)(?: [a-f0-9]{40})?$/u)?.groups?.version;return version3??`${lefthookVersion}#execution-unverified`};var hookPaths=(rootDirectory)=>{const gitPath=(args2,fallback)=>path26.resolve(rootDirectory,probeCommand("git",args2,rootDirectory)??fallback);return{active:gitPath(["rev-parse","--git-path","hooks/pre-commit"],".git/hooks/pre-commit"),default:path26.join(gitPath(["rev-parse","--git-common-dir"],".git"),"hooks","pre-commit")}};var isLefthookHook=(hook)=>hook.includes("call_lefthook");var hookStateOf=(hooksPath,hook)=>{if(hooksPath===null){return hook===null||isLefthookHook(hook)?"inactive":"other"}return hooksPath===managedHooksPath&&hook!==null&&digest2(hook)===managedHookScriptDigest?"managed":"other"};var observeCommitGate=(rootDirectory)=>{const packageDirectory=commitGatePackageDirectory(rootDirectory);const config=read2(path26.join(rootDirectory,"lefthook.yml"))??read2(path26.join(rootDirectory,"lefthook.yaml"));const hooksPath=probeCommand("git",["config","--get","core.hooksPath"],rootDirectory);const paths=hookPaths(rootDirectory);const hook=read2(paths.active);const lintCommand=config===null?null:managedLintCommand(config);return{configHash:config===null?null:digest2(config),dependencyVersion:observedDependencyVersion(packageDirectory),hookHash:hook!==null&&isExecutable(paths.active)?digest2(hook):null,hookState:hookStateOf(hooksPath,hook),inertHook:hooksPath!==null&&paths.default!==paths.active&&existsSync15(paths.default)?path26.relative(rootDirectory,paths.default):null,lintCommandHash:lintCommand===null?null:digest2(lintCommand)}};var commitGateVerifyCommandMetadata=declareCommandMetadata({examples:[{command:"hi commit-gate verify",summary:"Verify the installed Commit Gate."}],group:"commands",interaction:"none",name:"verify",options:[{name:"repo-root",summary:"Repository root. Defaults to the current directory."}],outputModes:["interactive","plain","json"],summary:"Verify the installed Commit Gate against live repository state. Writes nothing."});var repoRootOption=exports_Flag.string(metadataOptionName(commitGateVerifyCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(commitGateVerifyCommandMetadata,"repo-root"));var runCommitGateVerify=({rootDirectory})=>gen2(function*verifyInstalledCommitGate(){const settings=yield*readSettingsDocument(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:`Commit Gate verification cannot read Project settings: ${cause.detail}`,recoveryCommand:"hi init"})));const verification=verifyCommitGate({observed:observeCommitGate(rootDirectory),...settings?.commitGate===undefined?{}:{policy:settings.commitGate}});if(verification._tag==="Unresolved"){return yield*new CliValidationError({message:verification.reason,recoveryCommand:verification.recoveryCommand??"hi commit-gate verify"})}return{changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"success",warnings:verification.inertHook===undefined?[]:[{code:"commit-gate-inert-hook",subject:`${verification.inertHook} is inert while core.hooksPath is ${managedHooksPath}; not deleted`}]}});var commitGateVerifyCommand=exports_Command.make(commitGateVerifyCommandMetadata.name,{"repo-root":repoRootOption},({"repo-root":repoRoot})=>captureCommandResult(runCommitGateVerify({rootDirectory:path27.resolve(repoRoot)}))).pipe(withCommandMetadata(commitGateVerifyCommandMetadata));var commitGateCommandMetadata=declareCommandMetadata({examples:[{command:"hi commit-gate verify",summary:"Verify the installed Commit Gate."}],group:"commands",interaction:"none",name:"commit-gate",options:[],outputModes:["interactive","plain","json"],summary:"Inspect and verify the installed Commit Gate."});var commitGateCommand=exports_Command.make(commitGateCommandMetadata.name,{},()=>succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]})).pipe(withCommandMetadata(commitGateCommandMetadata),exports_Command.withSubcommands([commitGateVerifyCommand]));class InvalidMigrationRetry extends TaggedErrorClass()("InvalidMigrationRetry",{message:String4}){}class InvalidMutationRetry extends TaggedErrorClass()("InvalidMutationRetry",{message:String4}){}var SkillsCliScope=Literals(["project","global"]);var skillsCliFailureFields={message:String4,operation:Literals(["resolve","list","install","remove"]),scope:SkillsCliScope};class SkillsCliExit extends TaggedErrorClass()("SkillsCliExit",{...skillsCliFailureFields,exitCode:Finite,stderr:String4}){}class SkillsCliMalformedOutput extends TaggedErrorClass()("SkillsCliMalformedOutput",{...skillsCliFailureFields,stdout:String4}){}class SkillsCliTimeout extends TaggedErrorClass()("SkillsCliTimeout",{...skillsCliFailureFields,timeoutMs:Finite}){}class SkillsCliUnavailable extends TaggedErrorClass()("SkillsCliUnavailable",{...skillsCliFailureFields,executable:String4}){}class SkillsCliUnsupportedVersion extends TaggedErrorClass()("SkillsCliUnsupportedVersion",{...skillsCliFailureFields,minimumVersion:String4,version:String4}){}var verifiedInstalledSkillSchema=Struct({agents:ArraySchema(String4),cliCompatibility:Struct({maximumExclusive:String4,minimum:String4}),name:String4,path:String4,revision:String4,scope:SkillsCliScope,source:String4,version:String4});var SkillsCliVerificationFailureReason=Literals(["unsafe-path","missing","unreadable","malformed","identity-mismatch"]);class SkillsCliVerificationFailure extends TaggedErrorClass()("SkillsCliVerificationFailure",{...skillsCliFailureFields,reason:SkillsCliVerificationFailureReason,skillName:String4,skillPath:String4,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}var SkillsCli=Service("@punks/cli/features/operator-skill/SkillsCli");var OperatorSkillOperations=Service("@punks/cli/features/operator-skill/OperatorSkillOperations");var runOperatorSkillApplication=fn2("OperatorSkill.run")(function*runOperatorSkillApplication2(action2,targetSelection){const operations=yield*OperatorSkillOperations;return yield*operations.run(action2,targetSelection)});var isWithinCanonicalPath=(candidate,root)=>candidate===root||candidate.startsWith(root.endsWith("/")?root:`${root}/`)||candidate.startsWith(root.endsWith("\\")?root:`${root}\\`);var installedOperatorSkillCopyIdentity=(copy2)=>("version"in copy2)?JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"","verified",copy2.version,copy2.source,copy2.revision,copy2.compatibility,[...copy2.boundAgents].toSorted()]):JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"",copy2.verification,copy2.path,[...copy2.boundAgents].toSorted()]);var compareText=(left,right)=>left<right?-1:Number(left>right);var compareCopyIdentity=(left,right)=>{const leftIdentity=installedOperatorSkillCopyIdentity(left);const rightIdentity=installedOperatorSkillCopyIdentity(right);return compareText(leftIdentity,rightIdentity)};var sortCopies=(copies)=>copies.toSorted(compareCopyIdentity);var failureIdentity=(failure)=>JSON.stringify([failure.scope,failure.scope==="project-local"?failure.projectRoot:"",failure.reason,failure.message]);var resolveInstalledOperatorSkillState=(input2)=>{const failures=[];const copies=[];for(const inspection of input2.inspections){if(inspection._tag==="DetectionFailed"){failures.push(inspection);continue}if(inspection.scope==="global"){copies.push(...inspection.copies.map((copy2)=>({...copy2,boundAgents:[...copy2.boundAgents].toSorted()})));continue}for(const copy2 of inspection.copies){if(copy2.projectRoot!==inspection.projectRoot){failures.push({_tag:"DetectionFailed",message:`Project-local copy root ${copy2.projectRoot} does not match inspection root ${inspection.projectRoot}`,projectRoot:inspection.projectRoot,reason:"ProjectRootMismatch",scope:"project-local"});continue}copies.push({...copy2,boundAgents:[...copy2.boundAgents].toSorted(),projectRoot:inspection.projectRoot})}}const detected=sortCopies(copies);const incompatible=sortCopies(copies.filter((copy2)=>("compatibility"in copy2)&©2.compatibility==="incompatible"));if(failures.length>0){return{_tag:"DetectionFailed",detected,failures:failures.toSorted((left,right)=>compareText(failureIdentity(left),failureIdentity(right))),incompatible}}const candidates=detected.filter((copy2)=>copy2.scope==="global"||isWithinCanonicalPath(input2.cwd,copy2.projectRoot)).toSorted((left,right)=>Number(left.scope==="global")-Number(right.scope==="global"));const[effective]=candidates;if(effective===undefined){return{_tag:"Absent",detected,incompatible}}const topCandidates=candidates.filter((copy2)=>copy2.scope===effective.scope);if(topCandidates.some((copy2)=>installedOperatorSkillCopyIdentity(copy2)!==installedOperatorSkillCopyIdentity(effective))){return{_tag:"Ambiguous",candidates:topCandidates.toSorted(compareCopyIdentity),incompatible,shadowed:sortCopies(candidates.slice(topCandidates.length))}}if(!("version"in effective)){return{_tag:"Outdated",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}}return{_tag:"Resolved",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}};var operatorSkillScopeCwd=(scope3,input2)=>scope3==="global"?input2.cwd:input2.projectRoot;var parseSemanticVersion=(value3)=>{const match8=/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value3);const groups=match8?.groups;const prerelease2=groups?.prerelease?.split(".");if(groups===undefined||prerelease2?.some((identifier2)=>/^\d+$/u.test(identifier2)&&!/^(?:0|[1-9]\d*)$/u.test(identifier2))===true){return}return{core:[groups.major,groups.minor,groups.patch],prerelease:prerelease2}};var compareIdentifiers2=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var compareNumericIdentifiers=(left,right)=>left.length-right.length||compareIdentifiers2(left,right);var comparePrerelease=(left,right)=>{if(left===undefined||right===undefined){if(left===right){return 0}return left===undefined?1:-1}const length=Math.max(left.length,right.length);for(let index=0;index<length;index+=1){const leftIdentifier=left[index];const rightIdentifier=right[index];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}if(leftIdentifier===rightIdentifier){continue}const leftIsNumeric=/^\d+$/u.test(leftIdentifier);const rightIsNumeric=/^\d+$/u.test(rightIdentifier);if(leftIsNumeric&&rightIsNumeric){return compareNumericIdentifiers(leftIdentifier,rightIdentifier)}if(leftIsNumeric!==rightIsNumeric){return leftIsNumeric?-1:1}return compareIdentifiers2(leftIdentifier,rightIdentifier)}return 0};var compareSemanticVersions=(left,right)=>{const parsedLeft=parseSemanticVersion(left);const parsedRight=parseSemanticVersion(right);if(parsedLeft===undefined||parsedRight===undefined){return}for(let index=0;index<parsedLeft.core.length;index+=1){const compared=compareNumericIdentifiers(parsedLeft.core[index],parsedRight.core[index]);if(compared!==0){return compared}}return comparePrerelease(parsedLeft.prerelease,parsedRight.prerelease)};var satisfiesSemanticVersionRange=(version3,minimum,maximumExclusive)=>{const comparedToMinimum=compareSemanticVersions(version3,minimum);const comparedToMaximum=compareSemanticVersions(version3,maximumExclusive);return comparedToMinimum!==undefined&&comparedToMaximum!==undefined&&comparedToMinimum>=0&&comparedToMaximum<0};var compatibilityFor=(activeCliVersion,skill)=>satisfiesSemanticVersionRange(activeCliVersion,skill.cliCompatibility.minimum,skill.cliCompatibility.maximumExclusive)?"compatible":"incompatible";var isVerified=(skill)=>("version"in skill);var mapGlobalCopy=(activeCliVersion,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),revision:skill.revision,scope:"global",source:skill.source,version:skill.version});var mapProjectCopy=(activeCliVersion,projectRoot,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),projectRoot,revision:skill.revision,scope:"project-local",source:skill.source,version:skill.version});var inspectListedSkills=(scope3,input2,skills)=>{const outdatedOperatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&("verification"in skill)&&skill.verification==="outdated");const operatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&isVerified(skill));const legacySkills=skills.filter((skill)=>skill.name==="dp-cli");if(scope3==="global"){return{_tag:"Inspected",copies:[...operatorSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),...outdatedOperatorSkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:"global",verification:"outdated"}))],legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:scope3})),scope:scope3}}return{_tag:"Inspected",copies:[...operatorSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),...outdatedOperatorSkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:"project-local",verification:"outdated"}))],legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:scope3})),projectRoot:input2.projectRoot,scope:scope3}};var failedInspection=(scope3,input2,failure)=>{const verifiedSkills=failure._tag==="SkillsCliVerificationFailure"?failure.verifiedSkills:[];if(scope3==="global"){return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),failure,legacy:[],scope:scope3}}return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),failure,legacy:[],projectRoot:input2.projectRoot,scope:scope3}};var installedInspections=(inspections)=>inspections.flatMap((inspection)=>{const detected=inspection.scope==="global"?{_tag:"Detected",copies:inspection.copies,scope:"global"}:{_tag:"Detected",copies:inspection.copies,projectRoot:inspection.projectRoot,scope:"project-local"};if(inspection._tag==="Inspected"){return[detected]}const failure=inspection.scope==="global"?{_tag:"DetectionFailed",message:inspection.failure.message,reason:"ListingFailed",scope:"global"}:{_tag:"DetectionFailed",message:inspection.failure.message,projectRoot:inspection.projectRoot,reason:"ListingFailed",scope:"project-local"};return inspection.copies.length===0?[failure]:[detected,failure]});var collectLegacyCopies=(inspections)=>{const copies=[];for(const inspection of inspections){copies.push(...inspection.legacy)}return copies};var resolveOperatorSkillTargetForOperation=fn2("OperatorSkillLifecycle.resolveTarget")(function*resolveOperatorSkillTargetForOperation2(input2){const skillsCli=yield*SkillsCli;const resolution=yield*result2(skillsCli.resolveTarget({activeCliVersion:input2.activeCliVersion,cwd:input2.cwd,scope:"global",targetSelection:input2.targetSelection}));return isFailure2(resolution)?{_tag:"UpstreamResolutionFailed",failure:resolution.failure}:resolution.success});var inspectResolvedOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.inspectResolved")(function*inspectResolvedOperatorSkillLifecycle2(input2,resolution){if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",resolution}}const skillsCli=yield*SkillsCli;const[globalResult,projectResult]=yield*all2([result2(skillsCli.list({cwd:operatorSkillScopeCwd("global",input2),scope:"global",target:resolution.target,targetSelection:input2.targetSelection})),result2(skillsCli.list({cwd:operatorSkillScopeCwd("project-local",input2),scope:"project",target:resolution.target,targetSelection:input2.targetSelection}))],{concurrency:"unbounded"});const inspections=[isFailure2(globalResult)?failedInspection("global",input2,globalResult.failure):inspectListedSkills("global",input2,globalResult.success),isFailure2(projectResult)?failedInspection("project-local",input2,projectResult.failure):inspectListedSkills("project-local",input2,projectResult.success)];const installed=resolveInstalledOperatorSkillState({cwd:input2.cwd,inspections:installedInspections(inspections)});return{_tag:"Inspected",inspections,installed,legacy:collectLegacyCopies(inspections),target:resolution.target}});var inspectOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.status")(function*inspectOperatorSkillLifecycle2(input2,resolution){if(resolution!==undefined){return yield*inspectResolvedOperatorSkillLifecycle(input2,resolution)}return yield*scoped2(resolveOperatorSkillTargetForOperation(input2).pipe(flatMap3((resolved)=>inspectResolvedOperatorSkillLifecycle(input2,resolved))))});var retryFor=(operation,scope3,input2,target)=>Object.freeze({input:Object.freeze({...input2}),operation,scope:scope3,target});var inspectionFor=(status,scope3)=>status.inspections.find((inspection)=>inspection.scope===scope3);var copyMatchesTarget=(copy2,target)=>("version"in copy2)&©2.version===target.version&©2.source===target.source&©2.revision===target.revision&©2.compatibility==="compatible";var copyAppliesToScope=(copy2,input2)=>copy2.scope==="global"||copy2.projectRoot===input2.projectRoot;var targetCopy=(inspection,input2,target)=>inspection.copies.find((copy2)=>copyMatchesTarget(copy2,target)&©AppliesToScope(copy2,input2));var hasCompetingCopyIdentity=(inspection,copy2,input2)=>inspection.copies.some((candidate)=>copyAppliesToScope(candidate,input2)&&installedOperatorSkillCopyIdentity(candidate)!==installedOperatorSkillCopyIdentity(copy2));var verifyOperatorSkillScope=(scope3,input2,target,verification)=>{if(verification._tag==="TargetResolutionFailed"){return{_tag:"Unverified",reason:"TargetResolutionFailed",scope:scope3,verification}}const inspection=inspectionFor(verification,scope3);if(inspection?._tag==="InspectionFailed"){return{_tag:"Unverified",failure:inspection.failure,reason:"InspectionFailed",scope:scope3,verification}}if(inspection!==undefined){const copy2=targetCopy(inspection,input2,target);if(copy2!==undefined){if(hasCompetingCopyIdentity(inspection,copy2,input2)){return{_tag:"Unverified",reason:"CompetingCopyObserved",scope:scope3,verification}}return{_tag:"Verified",copy:copy2,scope:scope3,verification}}}return{_tag:"Unverified",reason:"TargetNotObserved",scope:scope3,verification}};var ensureAndVerifyOperatorSkillScope=fn2("OperatorSkillLifecycle.ensureAndVerifyScope")(function*ensureAndVerifyOperatorSkillScope2(scope3,input2,resolvedTarget){const skillsCli=yield*SkillsCli;const write2=yield*result2(skillsCli.install({cwd:operatorSkillScopeCwd(scope3,input2),resolvedTarget,scope:scope3==="global"?"global":"project",targetSelection:input2.targetSelection}));if(isFailure2(write2)){return{_tag:"Failed",failure:write2.failure,scope:scope3}}const verification=yield*inspectOperatorSkillLifecycle(input2,resolvedTarget);return verifyOperatorSkillScope(scope3,input2,resolvedTarget.target,verification)});var mutationActionFor=(operation,input2,target,result3)=>{const retry5=retryFor(operation,result3.scope,input2,target);if(result3._tag==="Failed"){return{_tag:"Failed",failure:result3.failure,operation,phase:"write",retry:retry5,scope:result3.scope}}if(result3._tag==="Unverified"){return{...result3,operation,retry:retry5}}return{...result3,operation}};var inspectionDetectedOperatorSkill=(inspection)=>inspection.copies.length>0||inspection._tag==="InspectionFailed"&&inspection.failure._tag==="SkillsCliVerificationFailure"&&inspection.failure.skillName==="hi-cli";var inspectionScopeIsUnknown=(inspection)=>inspection._tag==="InspectionFailed"&&!inspectionDetectedOperatorSkill(inspection);var alreadyVerifiedScope=(operation,scope3,before,input2)=>{const inspection=inspectionFor(before,scope3);if(inspection?._tag!=="Inspected"){return}const copy2=targetCopy(inspection,input2,before.target);if(copy2===undefined||hasCompetingCopyIdentity(inspection,copy2,input2)){return}return{_tag:"AlreadyVerified",copy:copy2,operation,scope:scope3,verification:before}};var unknownScopeFailures=(operation,before,input2)=>before.inspections.flatMap((inspection)=>inspectionScopeIsUnknown(inspection)&&(operation==="update"||inspection.scope==="global")?[{_tag:"Failed",failure:inspection.failure,operation,phase:"inspection",retry:retryFor(operation,inspection.scope,input2,before.target),scope:inspection.scope}]:[]);var scopesToMutate=(operation,before)=>{if(operation==="install"){const globalIsUnknown=before.inspections.some((inspection)=>inspection.scope==="global"&&inspectionScopeIsUnknown(inspection));return globalIsUnknown?[]:["global"]}return before.inspections.filter(inspectionDetectedOperatorSkill).map((inspection)=>inspection.scope)};var mutateOperatorSkill=fn2("OperatorSkillLifecycle.mutate")(function*mutateOperatorSkill2(operation,input2,resolvedTarget){const before=yield*inspectOperatorSkillLifecycle(input2,resolvedTarget);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation,reload:{_tag:"NotRequired"}}}const candidateScopes=scopesToMutate(operation,before);const alreadyVerified=candidateScopes.flatMap((scope3)=>{const action2=alreadyVerifiedScope(operation,scope3,before,input2);return action2===undefined?[]:[action2]});const verifiedScopes=new Set(alreadyVerified.map((action2)=>action2.scope));const actions=[...unknownScopeFailures(operation,before,input2),...alreadyVerified];let wrote=false;const scopes=candidateScopes.filter((scope3)=>!verifiedScopes.has(scope3));for(const scope3 of scopes){const ensured=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,resolvedTarget);wrote||=ensured._tag!=="Failed";actions.push(mutationActionFor(operation,input2,before.target,ensured))}return{_tag:"Completed",actions,before,operation,reload:wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"},target:before.target}});var installOperatorSkill=fn2("OperatorSkillLifecycle.install")(function*installOperatorSkill2(input2,operationTarget){return yield*scoped2(gen2(function*runInstall2(){const resolution=operationTarget??(yield*resolveOperatorSkillTargetForOperation(input2));if(resolution._tag!=="Resolved"){const before={_tag:"TargetResolutionFailed",resolution};return{_tag:"TargetResolutionFailed",actions:[],before,operation:"install",reload:{_tag:"NotRequired"}}}return yield*mutateOperatorSkill("install",input2,resolution)}))});var updateOperatorSkill=fn2("OperatorSkillLifecycle.update")(function*updateOperatorSkill2(input2,operationTarget){return yield*scoped2(gen2(function*runUpdate(){const resolution=operationTarget??(yield*resolveOperatorSkillTargetForOperation(input2));if(resolution._tag!=="Resolved"){const before={_tag:"TargetResolutionFailed",resolution};return{_tag:"TargetResolutionFailed",actions:[],before,operation:"update",reload:{_tag:"NotRequired"}}}return yield*mutateOperatorSkill("update",input2,resolution)}))});var migrationRetry=(scope3,input2,target,phase,affectedScopes)=>Object.freeze({affectedScopes:Object.freeze([...affectedScopes]),input:Object.freeze({...input2}),operation:"migrate",phase,scope:scope3,target});var affectedScopes=(before,input2)=>["global","project-local"].filter((scope3)=>(scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot))&&before.inspections.some((inspection)=>inspection.scope===scope3&&inspection.legacy.length>0));var scopeApplies=(scope3,input2)=>scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot);var recoverableScopes=(input2,scopes)=>["global","project-local"].filter((scope3)=>scopes.includes(scope3)&&scopeApplies(scope3,input2));var targetIdentity=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var legacyIdentity=(copy2)=>JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"",copy2.path,[...copy2.boundAgents].toSorted()]);var inspectedLegacyCopiesFor=(status,scope3)=>{if(status._tag!=="Inspected"){return}const inspection=status.inspections.find((candidate)=>candidate.scope===scope3);return inspection?._tag==="Inspected"?inspection.legacy:undefined};var legacyCopiesFor=(status,scope3)=>inspectedLegacyCopiesFor(status,scope3)??[];var legacyCopiesMatch=(left,right)=>JSON.stringify(left.map(legacyIdentity).toSorted())===JSON.stringify(right.map(legacyIdentity).toSorted());var replacementAction=(result3,input2,target,scopes,wrote=true)=>{const retry5=migrationRetry(result3.scope,input2,target,"replacement",scopes);if(result3._tag==="Failed"){return{_tag:"ReplacementFailed",failure:result3.failure,retry:retry5,scope:result3.scope}}if(result3._tag==="Unverified"){return{_tag:"ReplacementUnverified",...result3.failure===undefined?{}:{failure:result3.failure},reason:result3.reason,retry:retry5,scope:result3.scope,verification:result3.verification}}return{_tag:"ReplacementVerified",copy:result3.copy,scope:result3.scope,verification:result3.verification,wrote}};var reloadGuidance=(wrote)=>wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"};var verifyBarrierCopy=(scope3,input2,target,verification,expected)=>{const observed=verifyOperatorSkillScope(scope3,input2,target,verification);if(observed._tag!=="Verified"){return observed}if(expected===undefined||installedOperatorSkillCopyIdentity(observed.copy)!==installedOperatorSkillCopyIdentity(expected)){return{_tag:"Unverified",reason:"ReplacementChanged",scope:scope3,verification}}return observed};var legacyRemovalReason=(reason)=>{if(reason==="InspectionFailed"){return"InspectionFailed"}return reason==="ReplacementChanged"?"ReplacementChanged":"ReplacementNotVerified"};var validateAffectedBarriers=(input2)=>(()=>{let blockingLoss;return input2.scopes.flatMap((scope3,scopeIndex)=>{const pending=scopeIndex>input2.afterIndex;const checked=verifyBarrierCopy(scope3,input2.migrationInput,input2.target,input2.verification,input2.barrierCopies.get(scope3));if(checked._tag==="Verified"){if(!pending||blockingLoss===undefined||input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:blockingLoss.reason,barrierScope:blockingLoss.scope,...blockingLoss.failure===undefined?{}:{failure:blockingLoss.failure},reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}if(pending&&input2.refusedScopes.has(scope3)){return[]}const failure="failure"in checked&&checked.failure!==undefined?{failure:checked.failure}:{};if(pending){input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:checked.reason,barrierScope:scope3,...failure,reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}blockingLoss={reason:checked.reason,scope:scope3,...failure};if(input2.lostBarrierScopes.has(scope3)){return[]}input2.lostBarrierScopes.add(scope3);return[{_tag:"RemovalBarrierLost",afterScope:input2.afterScope,barrierReason:checked.reason,...failure,phase:input2.phase,position:scopeIndex===input2.afterIndex?"current":"prior",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]})})();var validatePeerLegacySnapshots=(input2)=>input2.scopes.flatMap((scope3,scopeIndex)=>{if(scopeIndex===input2.afterIndex){return[]}const observed=inspectedLegacyCopiesFor(input2.verification,scope3);if(observed===undefined){return[]}if(legacyCopiesMatch(input2.legacySnapshots.get(scope3)??[],observed)){return[]}const retry5=migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes);if(scopeIndex>input2.afterIndex){if(input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",legacyReason:"LegacyChanged",reason:"LegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]}if(input2.reportedScopes.has(scope3)){return[]}input2.reportedScopes.add(scope3);return[{_tag:"LegacyRemovalUnverified",reason:"LegacyChangedAfterRemoval",retry:retry5,scope:scope3,verification:input2.verification}]});var handleFailedLegacyRemoval=fn2("OperatorSkillLifecycle.handleFailedLegacyRemoval")(function*handleFailedLegacyRemoval2(context3,failure){const{legacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target}=context3;const actions=[{_tag:"LegacyRemovalFailed",failure,retry:retry5,scope:scope3}];let wrote=false;const verification=yield*inspectOperatorSkillLifecycle(input2,context3.resolvedTarget);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const legacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(legacyCopies.get(scope3)??[],observedLegacy);if(legacyChanged){wrote=true;actions.push({_tag:"LegacyRemovalUnverified",reason:"LegacyChangedAfterFailure",retry:retry5,scope:scope3,verification})}const peerLegacyActions=validatePeerLegacySnapshots({afterIndex:scopeIndex,legacySnapshots:legacyCopies,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,verification});wrote||=peerLegacyActions.length>0;actions.push(...peerLegacyActions);const barrierActions=validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-failed",refusedScopes,scopes,target,verification});wrote||=barrierActions.some((action2)=>action2.barrierReason!=="InspectionFailed"&&action2.barrierReason!=="TargetResolutionFailed");actions.push(...barrierActions);if(observedLegacy!==undefined){legacyCopies.set(scope3,observedLegacy)}return{actions,wrote}});var handleSuccessfulLegacyRemoval=fn2("OperatorSkillLifecycle.handleSuccessfulLegacyRemoval")(function*handleSuccessfulLegacyRemoval2(context3){const{legacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target}=context3;const verification=yield*inspectOperatorSkillLifecycle(input2,context3.resolvedTarget);let currentAction;if(verification._tag==="TargetResolutionFailed"){currentAction={_tag:"LegacyRemovalUnverified",reason:"ReplacementNotVerified",retry:retry5,scope:scope3,verification}}else{const inspection=verification.inspections.find((candidate)=>candidate.scope===scope3);if(inspection!==undefined&&inspection.legacy.length>0){currentAction={_tag:"LegacyRemovalUnverified",reason:"LegacyStillPresent",retry:retry5,scope:scope3,verification}}else{const replacementCheck=verifyBarrierCopy(scope3,input2,target,verification,barrierCopies.get(scope3));currentAction=replacementCheck._tag==="Verified"?{_tag:"LegacyRemoved",scope:scope3,verification}:{_tag:"LegacyRemovalUnverified",..."failure"in replacementCheck&&replacementCheck.failure!==undefined?{failure:replacementCheck.failure}:{},reason:legacyRemovalReason(replacementCheck.reason),retry:retry5,scope:scope3,verification}}}const actions=[currentAction,...validatePeerLegacySnapshots({afterIndex:scopeIndex,legacySnapshots:legacyCopies,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,verification})];const observedCurrentLegacy=inspectedLegacyCopiesFor(verification,scope3);if(observedCurrentLegacy!==undefined){legacyCopies.set(scope3,observedCurrentLegacy)}actions.push(...validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-succeeded",refusedScopes,scopes,target,verification}));return actions});var prepareMigration=(before,input2,recoveryScopes,recoveryPhase)=>{const observedScopes=affectedScopes(before,input2);const recoveryScopeLimit=recoveryScopes===undefined?undefined:recoverableScopes(input2,recoveryScopes);let scopes=observedScopes;if(recoveryScopeLimit!==undefined){scopes=recoveryPhase==="preflight"?observedScopes.filter((scope3)=>recoveryScopeLimit.includes(scope3)):recoveryScopeLimit}const retryScopes=recoveryScopeLimit??recoverableScopes(input2,[...scopes,...before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"?[inspection.scope]:[])]);const preflightFailures=before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopeLimit===undefined||recoveryScopeLimit.includes(inspection.scope))?[{_tag:"PreflightFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,before.target,"preflight",retryScopes),scope:inspection.scope}]:[]);return{preflightFailures,scopes}};var ensureReplacementBarriers=fn2("OperatorSkillLifecycle.ensureReplacementBarriers")(function*ensureReplacementBarriers2(scopes,input2,before,resolvedTarget){const actions=[];let wrote=false;let barrierFailed=false;for(const scope3 of scopes){const existing=verifyOperatorSkillScope(scope3,input2,before.target,before);if(existing._tag==="Verified"){actions.push({_tag:"ReplacementVerified",copy:existing.copy,scope:scope3,verification:existing.verification,wrote:false});continue}const replacement=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,resolvedTarget);wrote||=replacement._tag!=="Failed";barrierFailed||=replacement._tag!=="Verified";actions.push(replacementAction(replacement,input2,before.target,scopes))}return{actions,barrierFailed,wrote}});var inspectReplacementBarrier=fn2("OperatorSkillLifecycle.inspectReplacementBarrier")(function*inspectReplacementBarrier2(scopes,input2,target,resolvedTarget,recoveryScopes){const status=yield*inspectOperatorSkillLifecycle(input2,resolvedTarget);const failedInspections=status._tag==="Inspected"?status.inspections.filter((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopes===undefined||scopes.includes(inspection.scope))):[];const failedScopes=new Set(failedInspections.map((inspection)=>inspection.scope));const verifications=scopes.flatMap((scope3)=>{if(failedScopes.has(scope3)){return[]}const verification=verifyOperatorSkillScope(scope3,input2,target,status);return[{scope:scope3,verification}]});const actions=[...failedInspections.map((inspection)=>({_tag:"BarrierInspectionFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,target,"barrier",scopes),scope:inspection.scope})),...verifications.flatMap(({scope:scope3,verification})=>verification._tag==="Unverified"?[{_tag:"BarrierUnverified",...verification.failure===undefined?{}:{failure:verification.failure},reason:verification.reason,retry:migrationRetry(scope3,input2,target,"barrier",scopes),scope:scope3,verification:verification.verification}]:[])];return{actions,status,verifications}});var migrateLegacyOperatorSkillPolicy=fn2("OperatorSkillLifecycle.migratePolicy")(function*migrateLegacyOperatorSkillPolicy2(input2,recoveryScopes,expectedTarget,recoveryPhase,operationTarget){const resolution=operationTarget??(yield*resolveOperatorSkillTargetForOperation(input2));const before=yield*inspectOperatorSkillLifecycle(input2,resolution);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,reload:{_tag:"NotRequired"}}}if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",actions:[],before:{_tag:"TargetResolutionFailed",resolution},reload:{_tag:"NotRequired"}}}if(expectedTarget!==undefined&&targetIdentity(expectedTarget)!==targetIdentity(before.target)){return{_tag:"RetryTargetChanged",actions:[],expected:expectedTarget,observed:before.target,reload:{_tag:"NotRequired"}}}const{preflightFailures,scopes}=prepareMigration(before,input2,recoveryScopes,recoveryPhase);if(preflightFailures.length>0){return{_tag:"Refused",actions:preflightFailures,before,reason:"PreflightUnknown",reload:{_tag:"NotRequired"},target:before.target}}if(scopes.length===0){return{_tag:"Completed",actions:[],before,reload:{_tag:"NotRequired"},target:before.target}}const replacement=yield*ensureReplacementBarriers(scopes,input2,before,resolution);const actions=[...replacement.actions];let{wrote}=replacement;if(replacement.barrierFailed){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrier=yield*inspectReplacementBarrier(scopes,input2,before.target,resolution,recoveryScopes);const finalBarrier=barrier.status;const finalVerifications=barrier.verifications;actions.push(...barrier.actions);if(barrier.actions.length>0){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrierCopies=new Map(finalVerifications.flatMap(({scope:scope3,verification})=>verification._tag==="Verified"?[[scope3,verification.copy]]:[]));const legacyCopies=new Map(scopes.map((scope3)=>[scope3,legacyCopiesFor(finalBarrier,scope3)]));const skillsCli=yield*SkillsCli;const refusedScopes=new Set;const lostBarrierScopes=new Set;const reportedLegacyScopes=new Set;for(const scope3 of scopes){const replacementAgents=new Set(barrierCopies.get(scope3)?.boundAgents);const uncovered=(legacyCopies.get(scope3)??[]).some((copy2)=>copy2.boundAgents.some((agent)=>!replacementAgents.has(agent)));if(!uncovered){continue}refusedScopes.add(scope3);actions.push({_tag:"LegacyRemovalRefused",reason:"ReplacementCoverageIncomplete",retry:migrationRetry(scope3,input2,before.target,"removal",scopes),scope:scope3,verification:finalBarrier})}const removalScopes=scopes.filter((scope3)=>(legacyCopies.get(scope3)??[]).length>0);for(const scope3 of removalScopes){const scopeIndex=scopes.indexOf(scope3);if(refusedScopes.has(scope3)){continue}const remove5=yield*result2(skillsCli.remove({cwd:operatorSkillScopeCwd(scope3,input2),name:"dp-cli",scope:scope3==="global"?"global":"project",targetSelection:input2.targetSelection}));const retry5=migrationRetry(scope3,input2,before.target,"removal",scopes);const context3={barrierCopies,input:input2,legacyCopies,lostBarrierScopes,refusedScopes,reportedLegacyScopes,resolvedTarget:resolution,retry:retry5,scope:scope3,scopeIndex,scopes,target:before.target};if(isFailure2(remove5)){const failureResult=yield*handleFailedLegacyRemoval(context3,remove5.failure);wrote||=failureResult.wrote;actions.push(...failureResult.actions);continue}wrote=true;actions.push(...yield*handleSuccessfulLegacyRemoval(context3))}return{_tag:"Completed",actions,before,reload:reloadGuidance(wrote),target:before.target}});var migrateLegacyOperatorSkill=fn2("OperatorSkillLifecycle.migrate")(function*migrateLegacyOperatorSkill2(input2,operationTarget){return yield*scoped2(migrateLegacyOperatorSkillPolicy(input2,undefined,undefined,undefined,operationTarget))});var retryLegacyOperatorSkillMigration=fn2("OperatorSkillLifecycle.retryMigration")(function*retryLegacyOperatorSkillMigration2(retry5,currentInput,operationTarget){return yield*scoped2(migrateLegacyOperatorSkillPolicy({...retry5.input,activeCliVersion:currentInput.activeCliVersion,targetSelection:currentInput.targetSelection},retry5.affectedScopes,retry5.target,retry5.phase,operationTarget))});var migrationRetrySchema=Struct({affectedScopes:ArraySchema(Literals(["global","project-local"])),input:Struct({activeCliVersion:String4,cwd:String4,projectRoot:String4}),operation:Literal2("migrate"),phase:Literals(["barrier","preflight","removal","replacement"]),scope:Literals(["global","project-local"]),target:Struct({cliCompatibility:Struct({maximumExclusive:String4,minimum:String4}),contentManifest:ArraySchema(Struct({path:String4,sha256:String4})),revision:String4,source:String4,version:String4})});var mutationRetrySchema=Struct({input:Struct({activeCliVersion:String4,cwd:String4,projectRoot:String4}),operation:Literals(["install","update"]),scope:Literals(["global","project-local"]),target:migrationRetrySchema.fields.target});var encodeRetry=(retry5)=>{const{targetSelection:_targetSelection,...input2}=retry5.input;const json2=retry5.operation==="migrate"?encodeSync2(fromJsonString2(migrationRetrySchema))({...retry5,input:input2}):encodeSync2(fromJsonString2(mutationRetrySchema))({...retry5,input:input2});return Buffer.from(json2,"utf-8").toString("base64url")};var encodeMigrationRetry=(retry5)=>encodeRetry(retry5);var decodeMigrationRetry=(token)=>decodeEffect2(fromJsonString2(migrationRetrySchema))(Buffer.from(token,"base64url").toString("utf-8")).pipe(mapError3(()=>new InvalidMigrationRetry({message:"Migration retry token is invalid or stale."})),map6((decoded)=>({...decoded,input:{...decoded.input,targetSelection:"automatic"}})));var encodeMutationRetry=(retry5)=>encodeRetry(retry5);var decodeMutationRetry=(token)=>decodeEffect2(fromJsonString2(mutationRetrySchema))(Buffer.from(token,"base64url").toString("utf-8")).pipe(mapError3(()=>new InvalidMutationRetry({message:"Operator mutation retry token is invalid or stale."})),map6((decoded)=>({...decoded,input:{...decoded.input,targetSelection:"automatic"}})));var targetIdentity2=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var retryOperatorSkillMutation=(retry5,action2,currentInput,resolvedTarget)=>gen2(function*executeMutationRetry(){if(retry5.operation!==action2){return yield*new InvalidMutationRetry({message:`Operator mutation retry is for ${retry5.operation}, not ${action2}.`})}const retryInput={...retry5.input,activeCliVersion:currentInput.activeCliVersion,targetSelection:currentInput.targetSelection};const before=yield*inspectOperatorSkillLifecycle(retryInput,resolvedTarget);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation:retry5.operation,reload:{_tag:"NotRequired"}}}if(targetIdentity2(before.target)!==targetIdentity2(retry5.target)){return yield*new InvalidMutationRetry({message:"Operator mutation retry target changed; rerun the operator command."})}if(retry5.operation==="install"&&retry5.scope!=="global"){return yield*new InvalidMutationRetry({message:"Operator install retry scope changed; rerun the operator command."})}const inspection=inspectionFor(before,retry5.scope);if(inspection===undefined){return yield*new InvalidMutationRetry({message:"Operator mutation retry scope changed; rerun the operator command."})}if(inspectionScopeIsUnknown(inspection)){return{_tag:"Completed",actions:[{_tag:"Failed",failure:inspection.failure,operation:retry5.operation,phase:"inspection",retry:retry5,scope:retry5.scope}],before,operation:retry5.operation,reload:{_tag:"NotRequired"},target:retry5.target}}const updateIsAuthorized=retry5.operation==="update"&&inspectionDetectedOperatorSkill(inspection);const installIsAuthorized=retry5.operation==="install";if(!updateIsAuthorized&&!installIsAuthorized){return yield*new InvalidMutationRetry({message:"Operator mutation retry state changed; rerun the operator command."})}const result3=yield*ensureAndVerifyOperatorSkillScope(retry5.scope,retryInput,resolvedTarget);let mutationAction;if(result3._tag==="Failed"){mutationAction={...result3,operation:retry5.operation,phase:"write",retry:retry5}}else if(result3._tag==="Unverified"){mutationAction={...result3,operation:retry5.operation,retry:retry5}}else{mutationAction={...result3,operation:retry5.operation}}return{_tag:"Completed",actions:[mutationAction],before,operation:retry5.operation,reload:result3._tag==="Failed"?{_tag:"NotRequired"}:{_tag:"ReloadRequired",skill:"hi-cli"},target:retry5.target}});var executeOperatorAction=fn2("OperatorSkill.execute")(function*executeOperatorAction2(request){return yield*scoped2(gen2(function*executeResolvedOperatorAction(){const{action:action2,input:input2}=request;const resolution=yield*resolveOperatorSkillTargetForOperation(input2);if(action2==="status"){const lifecycle2=yield*inspectOperatorSkillLifecycle(input2,resolution);return{action:action2,lifecycle:lifecycle2}}if(action2==="install"||action2==="update"){if(request.mutationRetryToken!==undefined&&resolution._tag==="Resolved"){const lifecycle3=yield*decodeMutationRetry(request.mutationRetryToken).pipe(flatMap3((retry5)=>retryOperatorSkillMutation(retry5,action2,input2,resolution)));return{action:action2,lifecycle:lifecycle3}}const lifecycle2=yield*action2==="install"?installOperatorSkill(input2,resolution):updateOperatorSkill(input2,resolution);return{action:action2,lifecycle:lifecycle2}}const lifecycle=request.migrationRetryToken===undefined?yield*migrateLegacyOperatorSkill(input2,resolution):yield*decodeMigrationRetry(request.migrationRetryToken).pipe(flatMap3((retry5)=>retryLegacyOperatorSkillMigration(retry5,input2,resolution)));return{action:action2,lifecycle}}))});var[cliMajorText=""]=version2.split(".");var cliMajor=Number(cliMajorText);var operatorSkillCompatibilityPolicy=Object.freeze({maximumExclusive:`${cliMajor+1}.0.0`,minimum:`${cliMajor}.0.0`});var operatorSkillMetadataVersion="2.0.0";var immutableRevisionPattern=/^[0-9a-f]{40}$/u;var authoritativeSourceRoot="https://github.com/wearedevpunks/skills";var operatorSkillPath="skills/agnostic/cli/hi-cli";var targetIsIncomplete=(target)=>target.source.trim()===""||target.version.trim()===""||target.revision.trim()===""||target.cliCompatibility.minimum.trim()===""||target.cliCompatibility.maximumExclusive.trim()===""||target.contentManifest.length===0||target.contentManifest.some((entry)=>entry.path.trim()===""||entry.sha256.trim()==="");var validateTarget=(target)=>{if(targetIsIncomplete(target)){return"IncompleteIdentity"}if(!immutableRevisionPattern.test(target.revision)){return"MovingRevision"}const immutableSource=`${authoritativeSourceRoot}/tree/${target.revision}/${operatorSkillPath}`;if(target.source!==immutableSource){return target.source.startsWith(authoritativeSourceRoot)?"SourceRevisionMismatch":"NonAuthoritativeSource"}const version3=compareSemanticVersions(target.version,target.version);const rangeOrder=compareSemanticVersions(target.cliCompatibility.minimum,target.cliCompatibility.maximumExclusive);if(version3===undefined||rangeOrder===undefined||rangeOrder>=0){return"InvalidVersion"}return};var resolveOperatorSkillTarget=(input2)=>{if(compareSemanticVersions(input2.activeCliVersion,input2.activeCliVersion)===undefined){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}const compatibleIndexes=[];for(const[candidateIndex,candidate]of input2.candidates.entries()){const invalidReason=validateTarget(candidate);if(invalidReason!==undefined){return{_tag:"InvalidTarget",candidateIndex,reason:invalidReason}}if(satisfiesSemanticVersionRange(input2.activeCliVersion,candidate.cliCompatibility.minimum,candidate.cliCompatibility.maximumExclusive)){compatibleIndexes.push(candidateIndex)}}if(compatibleIndexes.length===0){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}if(compatibleIndexes.length>1){return{_tag:"AmbiguousCompatibleTargets",activeCliVersion:input2.activeCliVersion,candidateIndexes:compatibleIndexes}}return{_tag:"Resolved",target:input2.candidates[compatibleIndexes[0]]}};var operatorCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Inspect effective operator skill state."}],group:"commands",interaction:"none",name:"operator",options:[],outputModes:["interactive","plain","json"],summary:"Manage the Harness operator skill."});var operatorStatusCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Run operator status."}],group:"operator",interaction:"optional",name:"status",options:[],outputModes:["interactive","plain","json"],summary:"Show immutable hi-cli identity and effective installed state."});var operatorInstallCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator install",summary:"Run operator install."}],group:"operator",interaction:"optional",name:"install",options:[],outputModes:["interactive","plain","json"],summary:"Ensure and verify the global hi-cli operator skill."});var operatorUpdateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator update",summary:"Run operator update."}],group:"operator",interaction:"optional",name:"update",options:[],outputModes:["interactive","plain","json"],summary:"Update and verify every detected hi-cli scope."});var operatorMigrateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator migrate",summary:"Run operator migrate."}],group:"operator",interaction:"optional",name:"migrate",options:[],outputModes:["interactive","plain","json"],summary:"Verify replacements before removing legacy dp-cli copies."});var operatorActionMetadata=(action2)=>{switch(action2){case"status":{return operatorStatusCommandMetadata}case"install":{return operatorInstallCommandMetadata}case"update":{return operatorUpdateCommandMetadata}case"migrate":{return operatorMigrateCommandMetadata}default:{return action2}}};var publicOperatorFailure=(value3)=>{if(typeof value3!=="object"||value3===null){return value3}const failure={};for(const[key,nestedValue]of Object.entries(value3)){failure[key]=nestedValue}return Object.fromEntries(["_tag","exitCode","message","operation","reason","scope","skillName"].filter((key)=>failure[key]!==undefined).map((key)=>[key,failure[key]]))};var operatorFact=(value3)=>JSON.stringify(value3,(key,nestedValue)=>{if(key==="stderr"||key==="stack"||key==="cause"){const omittedValue=undefined;return omittedValue}return key==="failure"?publicOperatorFailure(nestedValue):nestedValue});var targetResolutionFailure=(resolution)=>{if(resolution._tag!=="UpstreamResolutionFailed"||resolution.failure===undefined){return{code:`operator-target-${resolution._tag}`,subject:operatorFact(resolution)}}const failureTag=typeof resolution.failure==="object"&&resolution.failure!==null&&"_tag"in resolution.failure?String(resolution.failure._tag):resolution._tag;return{code:`operator-target-${failureTag}`,subject:operatorFact(resolution.failure)}};var quoteShellArgument=(value3)=>`'${value3.replaceAll("'",`'"'"'`)}'`;var quotePowerShellLiteral=(value3)=>`'${value3.replaceAll("'","''")}'`;var windowsPowerShellCommand=(statements)=>`powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(statements.join("; "),"utf16le").toString("base64")}`;var mutationRetryCommand=(action2,platform)=>{const retry5=encodeMutationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MUTATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`& hi operator ${action2.retry.operation}`])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MUTATION_RETRY=${retry5} hi operator ${action2.retry.operation}`};var migrationRetryCommand=(action2,platform)=>{const retry5=encodeMigrationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MIGRATION_RETRY = ${quotePowerShellLiteral(retry5)}`,"& hi operator migrate"])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MIGRATION_RETRY=${retry5} hi operator migrate`};var publicTarget=(target)=>({cliCompatibility:target.cliCompatibility,revision:target.revision,source:target.source,version:target.version});var statusFromChangesAndIssues=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var operatorStatusOperationResult=(lifecycle)=>{if(lifecycle._tag==="TargetResolutionFailed"){const failure=targetResolutionFailure(lifecycle.resolution);return{changes:[],degradations:[],issues:[{action:"status",code:failure.code,kind:"handled-failure",subject:failure.subject}],nextActions:[{kind:"retry",subject:"operator:status"}],status:"failed",warnings:[]}}const changes=[{action:"operator-target",state:"completed",subject:operatorFact(publicTarget(lifecycle.target))},...lifecycle.inspections.map((inspection)=>({action:"operator-inspection",state:"completed",subject:operatorFact(inspection)})),{action:"operator-installed-state",state:"completed",subject:operatorFact(lifecycle.installed)},{action:"operator-legacy-copies",state:"completed",subject:operatorFact(lifecycle.legacy)}];let issues=[];if(lifecycle.installed._tag==="DetectionFailed"){issues=lifecycle.installed.failures.map((failure)=>({action:"status",code:"operator-detection-failed",errorMessage:failure.message,kind:"handled-failure",subject:operatorFact(failure)}))}else if(lifecycle.installed._tag==="Ambiguous"){issues=[{action:"status",code:"operator-installed-ambiguous",kind:"conflict",subject:operatorFact(lifecycle.installed.candidates)}]}let status="success";if(lifecycle.installed._tag==="Ambiguous"){status="conflict"}else if(lifecycle.installed._tag==="DetectionFailed"){status="failed"}let nextActions;if(lifecycle.installed._tag==="Outdated"){nextActions=[{kind:"run",subject:"hi operator update"}]}else if(issues.length===0){nextActions=[{kind:"none"}]}else{nextActions=[lifecycle.installed._tag==="Ambiguous"?{kind:"resolve",subject:"operator:status"}:{kind:"retry",subject:"operator:status"}]}return{changes,degradations:[],issues,nextActions,status,warnings:lifecycle.installed._tag==="Outdated"?[{code:"operator-installed-outdated",subject:operatorFact(lifecycle.installed.effective)}]:[]}};var publicVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicFailedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,phase:action2.phase,retry:action2.retry,scope:action2.scope});var publicAlreadyVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicUnverifiedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,reason:action2.reason,retry:action2.retry,scope:action2.scope});var operatorMutationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="TargetResolutionFailed"){const failure=targetResolutionFailure(lifecycle.before.resolution);return{changes:[],degradations:[],issues:[{action:lifecycle.operation,code:failure.code,kind:"handled-failure",subject:failure.subject}],nextActions:[{kind:"retry",subject:`operator:${lifecycle.operation}`}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="Verified");const failed=lifecycle.actions.filter((action2)=>action2._tag==="Failed");const alreadyVerified=lifecycle.actions.filter((action2)=>action2._tag==="AlreadyVerified");const unverified=lifecycle.actions.filter((action2)=>action2._tag==="Unverified");const retryActions=[...failed,...unverified];const changes=completed.map((action2)=>({action:action2.operation,state:"completed",subject:operatorFact(publicVerifiedMutationAction(action2))}));const noInstalledUpdate=lifecycle.operation==="update"&&lifecycle.actions.length===0;const issues=[...failed.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure.message,kind:"handled-failure",subject:operatorFact(publicFailedMutationAction(action2))})),...unverified.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure?.message,kind:"handled-failure",subject:operatorFact(publicUnverifiedMutationAction(action2))})),...noInstalledUpdate?[{action:"update",code:"operator-update-no-installed-scope",kind:"handled-failure",subject:operatorFact({before:lifecycle.before,target:publicTarget(lifecycle.target)})}]:[]];let nextActions=[{kind:"none"}];if(noInstalledUpdate){nextActions=[{kind:"run",subject:"hi operator install"}]}else if(retryActions.length>0){nextActions=retryActions.map((action2)=>({kind:"run",subject:mutationRetryCommand(action2,platform)}))}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[...alreadyVerified.map((action2)=>({code:`operator-${action2.operation}-${action2._tag}`,subject:operatorFact(publicAlreadyVerifiedMutationAction(action2))})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var migrationContext=(lifecycle)=>{if(lifecycle._tag==="RetryTargetChanged"){return{expected:publicTarget(lifecycle.expected),observed:publicTarget(lifecycle.observed),result:{_tag:lifecycle._tag}}}if(lifecycle._tag==="TargetResolutionFailed"){return{resolution:lifecycle.before.resolution,result:{_tag:lifecycle._tag}}}return{before:{inspections:lifecycle.before.inspections,installed:lifecycle.before.installed,legacy:lifecycle.before.legacy},result:{_tag:lifecycle._tag,...lifecycle._tag==="Refused"?{reason:lifecycle.reason}:{}},target:publicTarget(lifecycle.target)}};var migrationFailure=(action2)=>("failure"in action2)?action2.failure:undefined;var operatorMigrationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="RetryTargetChanged"){return{changes:[],degradations:[],issues:[{action:"migrate",code:"operator-migrate-RetryTargetChanged",kind:"conflict",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"conflict",warnings:[]}}if(lifecycle._tag==="TargetResolutionFailed"){const failure=targetResolutionFailure(lifecycle.before.resolution);return{changes:[],degradations:[],issues:[{action:"migrate",code:failure.code,kind:"handled-failure",subject:failure.subject}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="LegacyRemoved"||action2._tag==="ReplacementVerified"&&action2.wrote);const noOp=lifecycle.actions.filter((action2)=>action2._tag==="ReplacementVerified"&&!action2.wrote);const failed=lifecycle.actions.filter((action2)=>action2._tag!=="LegacyRemoved"&&action2._tag!=="ReplacementVerified");const context3=migrationContext(lifecycle);const changes=completed.map((action2)=>({action:"migrate",state:"completed",subject:operatorFact(action2)}));const issues=failed.map((action2)=>{const failure=migrationFailure(action2);return{action:"migrate",code:`operator-migrate-${action2._tag}`,...failure===undefined?{}:{errorMessage:failure.message},kind:"handled-failure",subject:operatorFact({action:action2,...context3})}});if(lifecycle._tag==="Refused"&&issues.length===0){issues.push({action:"migrate",code:"operator-migrate-Refused",kind:"handled-failure",subject:operatorFact(context3)})}let nextActions=[{kind:"none"}];if(failed.length>0){nextActions=failed.map((action2)=>({kind:"run",subject:migrationRetryCommand(action2,platform)}))}else if(issues.length>0){nextActions=[{kind:"retry",subject:"operator:migrate"}]}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[{code:"operator-migrate-context",subject:operatorFact(context3)},...noOp.map((action2)=>({code:"operator-migrate-ReplacementVerified",subject:operatorFact(action2)})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var executeOperatorCommand=(action2,operation=runOperatorSkillApplication,mode="plain")=>gen2(function*runOperatorCommand(){const result3=yield*operation(action2,mode==="interactive"?"prompt":"automatic");if(result3.action==="status"){return operatorStatusOperationResult(result3.lifecycle)}if(result3.action==="migrate"){return operatorMigrationOperationResult(result3.lifecycle)}return operatorMutationOperationResult(result3.lifecycle)}).pipe(catchTags2({InvalidMigrationRetry:(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:"unset HI_OPERATOR_MIGRATION_RETRY; hi operator migrate"})),InvalidMutationRetry:(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:`unset HI_OPERATOR_MUTATION_RETRY; hi operator ${action2}`}))}));var makeOperatorAction=(action2,operation=runOperatorSkillApplication)=>{const metadata=operatorActionMetadata(action2);return exports_Command.make(metadata.name,{},()=>gen2(function*runOperatorAction(){const mode=yield*SelectedOutputMode;return yield*captureCommandResult(executeOperatorCommand(action2,operation,mode))})).pipe(withCommandMetadata(metadata))};var operatorRootOperationResult={changes:[],degradations:[],issues:[],nextActions:[{kind:"run",subject:"hi operator status"},{kind:"run",subject:"hi operator install"},{kind:"run",subject:"hi operator update"},{kind:"run",subject:"hi operator migrate"}],status:"no-op",warnings:[{code:"operator-command-summary",subject:"Manage the Harness operator skill."}]};var operatorRootOperation=succeed6(operatorRootOperationResult);var operatorSubcommands=[makeOperatorAction("status"),makeOperatorAction("install"),makeOperatorAction("update"),makeOperatorAction("migrate")];var operatorCommandRoot=exports_Command.make(operatorCommandMetadata.name,{},()=>captureCommandResult(operatorRootOperation)).pipe(withCommandMetadata(operatorCommandMetadata));var operatorCommand=operatorCommandRoot.pipe(exports_Command.withSubcommands(operatorSubcommands));class ReportConfigurationUnavailable extends TaggedErrorClass()("@punks/cli/report-submission/ReportConfigurationUnavailable",{cause:Defect(),message:String4,operation:Literal2("resolve-control-plane-url")}){}class ReportSubmissionResponseInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionResponseInvalid",{cause:Defect(),message:String4,operation:Literal2("validate-submission-response")}){}class ReportInputInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportInputInvalid",{cause:Defect(),field:Literal2("body"),message:String4,operation:Literal2("validate-report-input")}){}class ReportSubmissionOperationFailure extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionOperationFailure",{cause:Defect(),message:String4,operation:Literals(["record-submitted","submit-report"])}){}var ReportSubmissionOperations=Service("@punks/cli/features/report-submission/ReportSubmissionOperations");var nonEmpty2=(value3)=>{const trimmed=value3.trim();if(trimmed.length===0){const cause=new Error("Missing body. Pass a non-empty value.");return fail6(new ReportInputInvalid({cause,field:"body",message:cause.message,operation:"validate-report-input"}))}return succeed6(trimmed)};var csvLabels=(value3)=>value3===undefined?[]:value3.split(",").map((label)=>label.trim()).filter((label)=>label.length>0);var buildHarnessReport=fn2("ReportSubmission.build")(function*buildReport({title,body,message,type,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels}){const operations=yield*ReportSubmissionOperations;const validBody=yield*nonEmpty2(body??message??[actual,expected,steps].filter(Boolean).join(`
|
|
353
353
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@punks/cli",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.6.0",
|
|
4
4
|
"description": "Harness Intelligence scaffolding CLI",
|
|
5
5
|
"homepage": "https://github.com/wearedevpunks/harness-intelligence/tree/main/apps/cli#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"@effect/eslint-plugin": "latest",
|
|
55
55
|
"@effect/platform-bun": "catalog:",
|
|
56
|
-
"@effect/tsgo": "0.
|
|
56
|
+
"@effect/tsgo": "0.63.0",
|
|
57
57
|
"@effect/vitest": "catalog:",
|
|
58
58
|
"@oxlint/plugins": "latest",
|
|
59
59
|
"@punks/contract": "workspace:*",
|
|
@@ -66,8 +66,8 @@
|
|
|
66
66
|
"eslint": "9.39.5",
|
|
67
67
|
"eslint-plugin-react-you-might-not-need-an-effect": "latest",
|
|
68
68
|
"oxfmt": "0.72.0",
|
|
69
|
-
"oxlint": "1.
|
|
70
|
-
"oxlint-tsgolint": "7.0.
|
|
69
|
+
"oxlint": "1.90.0",
|
|
70
|
+
"oxlint-tsgolint": "7.0.2005",
|
|
71
71
|
"typescript": "catalog:",
|
|
72
72
|
"ultracite": "7.12.4",
|
|
73
73
|
"vitest": "catalog:",
|