@punks/cli 6.2.0 → 6.2.1

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/AGENTS.md CHANGED
@@ -10,24 +10,13 @@ Use [Rule Registry](../../.agents/rules/index.md) as the exhaustive codebase-rul
10
10
 
11
11
  Read the installed skill on its exact invocation below; phase routing remains inherited from the root guidance.
12
12
 
13
- | Skill | Exact trigger |
14
- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
15
- | `autoreview` | When the task explicitly invokes `autoreview`, read `../../.agents/skills/autoreview/SKILL.md`. |
16
- | `codebase-design` | When the task explicitly invokes `codebase-design`, read `../../.agents/skills/codebase-design/SKILL.md`. |
17
- | `effect` | When the task explicitly invokes `effect`, read `../../.agents/skills/effect/SKILL.md`. |
18
- | `effect-backend-structure` | When the task explicitly invokes `effect-backend-structure`, read `../../.agents/skills/effect-backend-structure/SKILL.md`. |
19
- | `effect-recoverable-actions` | When the task explicitly invokes `effect-recoverable-actions`, read `../../.agents/skills/effect-recoverable-actions/SKILL.md`. |
20
- | `effect-service-design` | When the task explicitly invokes `effect-service-design`, read `../../.agents/skills/effect-service-design/SKILL.md`. |
21
- | `improve-codebase-architecture` | When the task explicitly invokes `improve-codebase-architecture`, read `../../.agents/skills/improve-codebase-architecture/SKILL.md`. |
22
- | `make-tsuite` | When the task explicitly invokes `make-tsuite`, read `../../.agents/skills/make-tsuite/SKILL.md`. |
23
- | `parallel-research` | When the task explicitly invokes `parallel-research`, read `../../.agents/skills/parallel-research/SKILL.md`. |
24
- | `prototype` | When the task explicitly invokes `prototype`, read `../../.agents/skills/prototype/SKILL.md`. |
25
- | `quality-types` | When the task explicitly invokes `quality-types`, read `../../.agents/skills/quality-types/SKILL.md`. |
26
- | `review` | When the task explicitly invokes `review`, read `../../.agents/skills/review/SKILL.md`. |
27
- | `simplify` | When the task explicitly invokes `simplify`, read `../../.agents/skills/simplify/SKILL.md`. |
28
- | `swarm-planner` | When the task explicitly invokes `swarm-planner`, read `../../.agents/skills/swarm-planner/SKILL.md`. |
29
- | `tdd` | When the task explicitly invokes `tdd`, read `../../.agents/skills/tdd/SKILL.md`. |
30
- | `turborepo` | When the task explicitly invokes `turborepo`, read `../../.agents/skills/turborepo/SKILL.md`. |
13
+ | Skill | Exact trigger |
14
+ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
15
+ | `effect` | When the task explicitly invokes `effect`, read `../../.agents/skills/effect/SKILL.md`. |
16
+ | `effect-backend-structure` | When the task explicitly invokes `effect-backend-structure`, read `../../.agents/skills/effect-backend-structure/SKILL.md`. |
17
+ | `effect-recoverable-actions` | When the task explicitly invokes `effect-recoverable-actions`, read `../../.agents/skills/effect-recoverable-actions/SKILL.md`. |
18
+ | `effect-service-design` | When the task explicitly invokes `effect-service-design`, read `../../.agents/skills/effect-service-design/SKILL.md`. |
19
+ | `quality-types` | When the task explicitly invokes `quality-types`, read `../../.agents/skills/quality-types/SKILL.md`. |
31
20
 
32
21
  ### Source and validation seams
33
22
 
package/dist/index.js CHANGED
@@ -312,7 +312,7 @@ try {
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
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 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=path8.join(root,settingsPath);return existsSync5(absolute)?decodeCheckSettings(readFileSync4(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 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={missingTools,status:"not-installed"};return notInstalled}const installed=record2.baseline;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,installed,latest,missingTools,status:latest===installed?"current":"update-available"}}),catch_2((error2)=>succeed6({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.semanticReads!==undefined){lines2.push(...semanticReadsLines(result3.semanticReads))}return lines2.join(`
315
- `)};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.2.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 isRecord2=(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(!isRecord2(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(!isRecord2(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(!isRecord2(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=(path9,declaration)=>({...declaration,path:path9});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 existsSync7,readFileSync as readFileSync6}from"node:fs";import path10 from"node:path";import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync6,readFileSync as readFileSync5,rmSync}from"node:fs";import{readFile as readFile3}from"node:fs/promises";import{homedir as homedir3}from"node:os";import path9 from"node:path";import{fileURLToPath as fileURLToPath2}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=()=>path9.join(process.env.XDG_CACHE_HOME??path9.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=path9.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(fileURLToPath2(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=path9.resolve(cacheRoot,...relative.split("/"));return absolute.startsWith(`${cacheRoot}${path9.sep}`)?absolute:undefined};const readCache=(relative)=>{const absolute=cachePath(relative);try{return absolute!==undefined&&existsSync6(absolute)?new Uint8Array(readFileSync5(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=path10.join(root,settingsPath);const parsed=existsSync7(absolute)?JSON.parse(readFileSync6(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).
315
+ `)};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.2.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 isRecord2=(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(!isRecord2(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(!isRecord2(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(!isRecord2(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=(path9,declaration)=>({...declaration,path:path9});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 existsSync7,readFileSync as readFileSync6}from"node:fs";import path10 from"node:path";import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync6,readFileSync as readFileSync5,rmSync}from"node:fs";import{readFile as readFile3}from"node:fs/promises";import{homedir as homedir3}from"node:os";import path9 from"node:path";import{fileURLToPath as fileURLToPath2}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=()=>path9.join(process.env.XDG_CACHE_HOME??path9.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=path9.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(fileURLToPath2(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=path9.resolve(cacheRoot,...relative.split("/"));return absolute.startsWith(`${cacheRoot}${path9.sep}`)?absolute:undefined};const readCache=(relative)=>{const absolute=cachePath(relative);try{return absolute!==undefined&&existsSync6(absolute)?new Uint8Array(readFileSync5(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=path10.join(root,settingsPath);const parsed=existsSync7(absolute)?JSON.parse(readFileSync6(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).
316
316
  ${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 npx lefthook install, then hi commit-gate verify.")}if(report.dependencyInstall==="failed"){lines2.push("The dependency install failed. Fix it, then rerun hi update.")}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(`
317
317
  `)}if(result3.status==="refused"){return[`${command}:`,...refusalLines(result3)].join(`
318
318
  `)}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(`
@@ -335,7 +335,7 @@ ${content.trim()}`}).join(`
335
335
  `)}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 name2=presetName(preset);return[name2,`${name2}LocalRules`,`${name2}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 name2=plugin===undefined?key:`${pluginAlias(plugin,scopePath)}${key.slice(plugin.name.length)}`;rules[name2]=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 name2=presetName(preset);return[`const ${name2}LocalRules = ${encodeTs(resolvableRules(overrides,new Set))} satisfies OxlintConfig["rules"];`,"",`const ${name2}WithLocalRules = {`,` ...${name2},`,` overrides: (${name2}.overrides ?? []).map((override) => ({`," ...override,"," rules: {"," ...override.rules,",` ...${name2}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(`
336
336
  `)};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 isRecord3(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 isRecord3(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(isRecord3(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(isRecord3(rules)?rules:{},managed.rules),aliases);const projectOverrides=(Array.isArray(overrides)?overrides:[]).map((override)=>{if(!isRecord3(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(isRecord3(categories)?categories:{},managed.categories);const projectSettings=withoutManaged(isRecord3(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=isRecord3(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(`
337
337
  `);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(`
338
- `)}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}`)),setup:spec.prepareCommands??[],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(([name2,version3])=>`${name2}@${version3}`))})};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)=>(path13)=>{const result3=spawnSync2("git",["show",`HEAD:./${path13}`],{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 path15 from"node:path";import{readdirSync as readdirSync2,statSync as statSync3}from"node:fs";import path14 from"node:path";import{existsSync as existsSync8,readFileSync as readFileSync7,readdirSync,statSync as statSync2}from"node:fs";import path13 from"node:path";class CliDetectionError extends TaggedErrorClass()("CliDetectionError",{cause:optional(Defect()),message:String4}){}var ignoredDirectoryNames=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","coverage","dist","docs","examples","build","node_modules","opensrc","scripts","skills","test-fixtures","tmp","worktrees",".venv","venv","__pycache__"]);var detectionOrder=["nextjs","react","tanstack-query","elysia","trpc","drizzle","better-auth","effect","turborepo"];var languageDetectionOrder=["python","typescript"];var installerTypeScriptFiles=new Set(["oxlint.config.ts","oxlint.local.ts"]);var sourceLanguageExtensions=[{language:"python",pattern:/\.py$/u},{language:"typescript",pattern:/\.(?:ts|tsx)$/u}];var conventionalWorkspaceRoots=["apps","packages","services","libs"];var wikiRootPaths=new Set(["app/wiki","apps/wiki","wiki"]);var pythonDependencyFiles=["Pipfile","poetry.lock","pyproject.toml","requirements.txt","uv.lock"];var detectedPythonPackages=["alembic","sqlalchemy"];var isRecord4=(value3)=>typeof value3==="object"&&value3!==null;var dependencyRecordSchema=Record(String4,String4);var packageJsonSchema=fromJsonString2(Struct({dependencies:optional(dependencyRecordSchema),devDependencies:optional(dependencyRecordSchema),name:optional(String4),optionalDependencies:optional(dependencyRecordSchema),packageManager:optional(String4),peerDependencies:optional(dependencyRecordSchema),workspaces:optional(Unknown2)}));var packageManagerFor=(rootDirectory,packageJson,inheritedDeclaration)=>{const declared=(packageJson.packageManager??inheritedDeclaration)?.split("@",1)[0];const candidates=[["bun","bun.lock"],["bun","bun.lockb"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"],["npm","package-lock.json"]];const match8=candidates.find(([manager,lockfile])=>(declared===manager||declared===undefined)&&existsSync8(path13.join(rootDirectory,lockfile)));if(match8===undefined){const supported=candidates.find(([manager])=>manager===declared);return supported===undefined?null:{packageManager:supported[0]}}return{lockfile:match8[1],packageManager:match8[0]}};var parsePackageJsonRecord=decodeUnknownSync(packageJsonSchema);var decodeWorkspacePackages=decodeUnknownSync(ArraySchema(String4));var collectPackageNames=(pkg)=>{const names=new Set;const addEntries=(record2)=>{if(!record2){return}for(const name2 of Object.keys(record2)){names.add(name2)}};addEntries(pkg.dependencies);addEntries(pkg.devDependencies);addEntries(pkg.peerDependencies);addEntries(pkg.optionalDependencies);return[...names].toSorted()};var normalizeRelativePath=(relativePath)=>relativePath.split(path13.sep).join("/");var isWikiRelativePath=(relativePath)=>{const normalized=normalizeRelativePath(relativePath);return[...wikiRootPaths].some((wikiRoot)=>normalized===wikiRoot||normalized.startsWith(`${wikiRoot}/`))};var nothingIgnored=()=>false;var processLayer2=layer3.pipe(provide2(mergeAll2(layer7,layer9)));var gitIgnoredPaths=(cwd)=>gen2(function*listGitIgnoredPaths(){const git2=yield*exports_ChildProcess.make("git",["ls-files","-z","--others","--ignored","--exclude-standard","--directory"],{cwd,stderr:"ignore",stdin:"ignore"});const[stdout,exitCode]=yield*all2([mkString(decodeText(git2.stdout)),git2.exitCode],{concurrency:"unbounded"});if(exitCode!==0){return nothingIgnored}const entries=stdout.split("\x00").filter((entry)=>entry.length>0);const files=new Set(entries.filter((entry)=>!entry.endsWith("/")));const directories=new Set(entries.filter((entry)=>entry.endsWith("/")).map((entry)=>entry.slice(0,-1)));const isIgnored=(relativePath)=>{const segments=normalizeRelativePath(relativePath).split("/");return files.has(segments.join("/"))||segments.some((_,index)=>directories.has(segments.slice(0,index+1).join("/")))};return isIgnored}).pipe(scoped2,provide4(processLayer2),orElseSucceed2(()=>nothingIgnored));var isWikiManifest=(manifest)=>isWikiRelativePath(manifest.relativePath);var packDetectionManifests=(manifests)=>manifests.filter((manifest)=>!isWikiManifest(manifest));var recursiveFindFiles=(cwd,filename,isIgnored)=>{const results=[];const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path13.join(directory3,entry.name);if(ignoredDirectoryNames.has(entry.name)||isIgnored(path13.relative(cwd,absolutePath))){continue}if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&entry.name===filename){results.push(absolutePath)}}};if(existsSync8(cwd)){visit2(cwd)}return results.toSorted()};var detectPythonPackages=(cwd,isIgnored)=>{const detected=new Set;for(const filename of pythonDependencyFiles){for(const dependencyFile of recursiveFindFiles(cwd,filename,isIgnored)){if(isWikiRelativePath(path13.relative(cwd,dependencyFile))){continue}const content=readFileSync7(dependencyFile,"utf-8");for(const packageName of detectedPythonPackages){const pattern=new RegExp(`(?:^|[\\s"'[,])${packageName}(?=$|[\\s"'\\[\\],=<>~!;])`,"imu");if(pattern.test(content)){detected.add(packageName)}}}}return[...detected].toSorted()};var discoverConventionalWorkspacePackageJsonPaths=(cwd)=>conventionalWorkspaceRoots.flatMap((rootDirectoryName)=>{const rootDirectory=path13.join(cwd,rootDirectoryName);if(!existsSync8(rootDirectory)){return[]}return readdirSync(rootDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path13.join(rootDirectory,entry.name,"package.json")).filter((manifestPath)=>existsSync8(manifestPath))});var discoverTopLevelPackageJsonPaths=(cwd)=>readdirSync(cwd,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path13.join(cwd,entry.name,"package.json")).filter((manifestPath)=>existsSync8(manifestPath));var readPackageJsonWorkspacePatterns=(pkg)=>{const{workspaces}=pkg;if(isArray(workspaces)){return decodeWorkspacePackages(workspaces)}if(isRecord4(workspaces)&&isArray(workspaces.packages)){return decodeWorkspacePackages(workspaces.packages)}return[]};var parsePnpmWorkspacePatterns=(content)=>{const patterns=[];let inPackagesSection=false;for(const rawLine of content.split(/\r?\n/u)){const line=rawLine.trim();if(line==="packages:"){inPackagesSection=true;continue}if(!inPackagesSection){continue}if(line.startsWith("- ")){const pattern=line.slice(2).trim().replaceAll(/^['"]|['"]$/gu,"");if(pattern.length>0){patterns.push(pattern)}continue}if(line.length>0&&!line.startsWith("#")){break}}return patterns};var readPnpmWorkspacePatterns=(cwd)=>{const workspacePath=path13.join(cwd,"pnpm-workspace.yaml");return existsSync8(workspacePath)?parsePnpmWorkspacePatterns(readFileSync7(workspacePath,"utf-8")):[]};var expandWorkspacePattern=(cwd,pattern)=>{if(pattern.endsWith("/*")){const baseDirectory=path13.join(cwd,pattern.slice(0,-2));if(!existsSync8(baseDirectory)){return[]}return readdirSync(baseDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path13.join(baseDirectory,entry.name,"package.json")).filter((manifestPath2)=>existsSync8(manifestPath2)).toSorted()}if(pattern.includes("*")){return[]}const manifestPath=path13.join(cwd,pattern,"package.json");return existsSync8(manifestPath)?[manifestPath]:[]};var discoverPackageJsonInputs=(cwd,isIgnored)=>{const rootPackageJsonPath=path13.join(cwd,"package.json");const recursivePackageJsonPaths=recursiveFindFiles(cwd,"package.json",isIgnored);if(!existsSync8(rootPackageJsonPath)){return{declaredWorkspacePaths:new Set,manifestPaths:recursivePackageJsonPaths,rootPackageJson:null}}const rootPackageJson=parsePackageJsonRecord(readFileSync7(rootPackageJsonPath,"utf-8"));const workspacePatterns=new Set([...readPackageJsonWorkspacePatterns(rootPackageJson),...readPnpmWorkspacePatterns(cwd)]);const workspacePackageJsonPaths=[...workspacePatterns].flatMap((pattern)=>expandWorkspacePattern(cwd,pattern));const conventionalWorkspacePackageJsonPaths=discoverConventionalWorkspacePackageJsonPaths(cwd);const topLevelPackageJsonPaths=discoverTopLevelPackageJsonPaths(cwd);return{declaredWorkspacePaths:new Set(recursivePackageJsonPaths.filter((manifestPath)=>{const relative=path13.relative(cwd,path13.dirname(manifestPath)).split(path13.sep).join("/");return relative!==""&&[...workspacePatterns].some((pattern)=>!pattern.startsWith("!")&&path13.matchesGlob(relative,pattern))&&![...workspacePatterns].some((pattern)=>pattern.startsWith("!")&&path13.matchesGlob(relative,pattern.slice(1)))})),manifestPaths:[...recursivePackageJsonPaths,...workspacePackageJsonPaths,...conventionalWorkspacePackageJsonPaths,...topLevelPackageJsonPaths].filter((value3,index,values)=>values.indexOf(value3)===index&&!isIgnored(path13.relative(cwd,value3))).toSorted(),rootPackageJson}};var detectTechnologies=(manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set;const hasPackage=(packageName)=>packageNames.has(packageName);const hasPackagePrefix=(prefix3)=>[...packageNames].some((packageName)=>packageName.startsWith(prefix3));if(hasPackage("next")){detected.add("nextjs");detected.add("react")}if(hasPackage("react")||hasPackage("react-dom")){detected.add("react")}if(hasPackage("@tanstack/react-query")||hasPackage("@tanstack/query-core")||hasPackage("@tanstack/react-query-devtools")||hasPackage("@tanstack/react-query-persist-client")||hasPackage("@tanstack/query-persist-client-core")){detected.add("tanstack-query")}if(hasPackage("elysia")){detected.add("elysia")}if(hasPackagePrefix("@trpc/")){detected.add("trpc")}if(hasPackage("drizzle-orm")||hasPackage("drizzle-kit")){detected.add("drizzle")}if(hasPackage("better-auth")){detected.add("better-auth")}if(hasPackage("effect")||hasPackagePrefix("@effect/")){detected.add("effect")}if(hasPackage("turbo")){detected.add("turborepo")}return detectionOrder.filter((technology)=>detected.has(technology))};var hasPackageTrigger=(packageNames,trigger)=>trigger.endsWith("/")?[...packageNames].some((packageName)=>packageName.startsWith(trigger)):packageNames.has(trigger);var isSourceDirectoryPath=(cwd,directory3)=>path13.relative(cwd,directory3)!=="";var detectSourceLanguages=(cwd,isIgnored)=>{const detected=new Set;const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path13.join(directory3,entry.name);const relativePath=path13.relative(cwd,absolutePath);if(ignoredDirectoryNames.has(entry.name)||isIgnored(relativePath)){continue}if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&isSourceDirectoryPath(cwd,directory3)&&!isWikiRelativePath(relativePath)){for(const{language,pattern}of sourceLanguageExtensions){if(pattern.test(entry.name)&&!entry.name.endsWith(".d.ts")&&!installerTypeScriptFiles.has(entry.name)){detected.add(language)}}}}};if(existsSync8(cwd)){visit2(cwd)}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectLanguages=(cwd,manifests,isIgnored)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set(detectSourceLanguages(cwd,isIgnored));if(hasPackageTrigger(packageNames,"typescript")){detected.add("typescript")}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectMonorepoSignals=(cwd,manifests,isIgnored)=>{const signals=[];for(const workspacePath of recursiveFindFiles(cwd,"pnpm-workspace.yaml",isIgnored)){signals.push({path:workspacePath,type:"pnpm-workspace"})}for(const turboConfigPath of recursiveFindFiles(cwd,"turbo.json",isIgnored)){signals.push({path:turboConfigPath,type:"turbo-config"})}for(const manifest of manifests){const pkg=parsePackageJsonRecord(readFileSync7(manifest.path,"utf-8"));const{workspaces}=pkg;const hasWorkspaces=isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages);if(hasWorkspaces){signals.push({path:manifest.path,type:"package-json-workspaces"})}}const workspaceManifests=manifests.filter((manifest)=>{const pkg=parsePackageJsonRecord(readFileSync7(manifest.path,"utf-8"));const{workspaces}=pkg;return!(isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages))});if(workspaceManifests.length>1){signals.push({path:cwd,type:"workspace-packages"})}return signals.filter((signal,index,allSignals)=>allSignals.findIndex((candidate)=>candidate.type===signal.type&&candidate.path===signal.path)===index)};var detectRepository=(cwd)=>flatMap3(gitIgnoredPaths(cwd),(isIgnored)=>try_3({catch:(cause)=>new CliDetectionError({cause,message:"Failed to detect repository shape."}),try:()=>{const root=statSync2(cwd,{throwIfNoEntry:false});if(root===undefined||!root.isDirectory()){throw new TypeError("Repository input must be an existing directory.")}const{declaredWorkspacePaths,manifestPaths,rootPackageJson}=discoverPackageJsonInputs(cwd,isIgnored);const rootDeclaration=rootPackageJson?.packageManager===undefined?undefined:packageManagerFor(cwd,rootPackageJson)?.packageManager;const manifests=manifestPaths.map((manifestPath)=>{const pkg=parsePackageJsonRecord(readFileSync7(manifestPath,"utf-8"));const packageManager=packageManagerFor(cwd,pkg,declaredWorkspacePaths.has(manifestPath)?rootDeclaration:undefined);return{dependencies:collectPackageNames(pkg),...packageManager,packageName:pkg.name??null,path:manifestPath,relativePath:path13.relative(cwd,manifestPath)||"package.json"}});const detectedLanguages=detectLanguages(cwd,manifests,isIgnored);const detectedPackages=detectPythonPackages(cwd,isIgnored);const detectedTechnologies=detectTechnologies(manifests);const monorepoSignals=detectMonorepoSignals(cwd,manifests,isIgnored);return{cwd,detectedLanguages,detectedPackages,detectedTechnologies,manifests,monorepo:monorepoSignals.length>0,monorepoSignals}}}));var wikiRoots=["apps/wiki","app/wiki","wiki"];var isDirectory=(absolute)=>{try{return statSync3(absolute).isDirectory()}catch{return false}};var isWikiPath=(relative)=>wikiRoots.some((wiki)=>relative===wiki||relative.startsWith(`${wiki}/`));var detectWikiRoot=(root)=>wikiRoots.find((wiki)=>isDirectory(path14.join(root,wiki)));var docsRoot="docs";var workspacePath=(manifest)=>{const directory3=path14.posix.dirname(manifest.relativePath.split(path14.sep).join("/"));return directory3===""?".":directory3};var sorted=(values)=>[...new Set(values)].toSorted();var typeScriptSourcePattern=/\.(?:ts|tsx|mts|cts)$/u;var declarationPattern=/\.d\.(?:ts|mts|cts)$/u;var tsconfigPattern2=/^tsconfig.*\.json$/u;var skippedScanDirectories=new Set(["build","dist","node_modules","opensrc"]);var maxScanDepth=8;var hasTypeScriptEvidence=(root,workspace,isIgnored)=>{const visit2=(directory3,depth)=>{let entries;try{entries=readdirSync2(directory3,{withFileTypes:true})}catch{return false}return entries.some((entry)=>{if(isIgnored(path14.relative(root,path14.join(directory3,entry.name)))){return false}if(entry.isDirectory()){return depth<maxScanDepth&&!entry.name.startsWith(".")&&!skippedScanDirectories.has(entry.name)&&visit2(path14.join(directory3,entry.name),depth+1)}return entry.isFile()&&(depth===0&&tsconfigPattern2.test(entry.name)||typeScriptSourcePattern.test(entry.name)&&!declarationPattern.test(entry.name)&&!installerTypeScriptFiles.has(entry.name))})};return visit2(path14.join(root,workspace),0)};var workspaceLanguages=(root,workspace,detected,isIgnored)=>sorted(detected.includes("typescript")||!hasTypeScriptEvidence(root,workspace,isIgnored)?detected:[...detected,"typescript"]);var detectionError=(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:"."});var repositoryDetection=(root)=>detectRepository(root).pipe(mapError3(detectionError));var detectShape=(root,packs)=>gen2(function*detectRecordedShape(){const detection=yield*detectRepository(root);const isIgnored=yield*gitIgnoredPaths(root);const wikiRoot=detectWikiRoot(root);const workspaces=[];for(const manifest of detection.manifests){const relative=workspacePath(manifest);if(wikiRoot!==undefined&&(relative===wikiRoot||relative.startsWith(`${wikiRoot}/`))){continue}const scoped4=relative==="."?detection:yield*detectRepository(path14.join(root,relative));workspaces.push({languages:workspaceLanguages(root,relative,scoped4.detectedLanguages,isIgnored),...manifest.packageName===null?{}:{name:manifest.packageName},path:relative,technologies:sorted(scoped4.detectedTechnologies)})}return{...isDirectory(path14.join(root,docsRoot))&&!isIgnored(docsRoot)?{docsRoot}:{},languages:sorted(detection.detectedLanguages),monorepo:detection.monorepo,packs:sorted(packs),technologies:sorted(detection.detectedTechnologies),...wikiRoot===undefined?{}:{wikiRoot},workspaces:workspaces.filter((workspace,index)=>workspaces.findIndex((other)=>other.path===workspace.path)===index).toSorted((left,right)=>left.path.localeCompare(right.path))}}).pipe(mapError3(detectionError));var backendWorkspaceSegments=new Set(["api","backend","server","services"]);var backendPackageSegments=new Set(["api","backend","server","service"]);var backendTechnologies=new Set(["better-auth","drizzle","elysia","trpc"]);var frontendTechnologies=new Set(["nextjs","react"]);var hasBackendWorkspaceName=(workspace)=>workspace.path.split("/").some((segment)=>backendWorkspaceSegments.has(segment))||(workspace.name??"").replace(/^@[^/]+\//u,"").split(/[^a-zA-Z0-9]+/u).some((segment)=>backendPackageSegments.has(segment.toLowerCase()));var surfaceSignals=(id,evidence)=>{if(id==="backend"){return[...evidence.technologies.filter((technology)=>backendTechnologies.has(technology)),...evidence.workspaces.filter(hasBackendWorkspaceName).map((workspace)=>workspace.path)]}return id==="frontend"?evidence.technologies.filter((technology)=>frontendTechnologies.has(technology)):[]};var surfaceApplies=(id,evidence)=>surfaceSignals(id,evidence).length>0;var packEvidence=(id,pack,detection)=>{const dependencies=detection.manifests.filter((manifest)=>!isWikiPath(manifest.relativePath.split(path14.sep).join("/"))).flatMap((manifest)=>manifest.dependencies);const packages=new Set(pack.category==="detected"?[...dependencies,...detection.detectedPackages??[]]:dependencies);const hasTrigger=(trigger)=>trigger.endsWith("/")?[...packages].some((name2)=>name2.startsWith(trigger)):packages.has(trigger);const technologies=detection.detectedTechnologies;const languages=detection.detectedLanguages;return sorted([...(pack.triggerPackages??[]).filter(hasTrigger).map((trigger)=>trigger.endsWith("/")?`${trigger}*`:trigger),...[id,...pack.technologies??[]].filter((technology)=>technologies.includes(technology)),...[id,...pack.languages??[]].filter((language)=>languages.includes(language)),...pack.category==="surface"?surfaceSignals(id,{technologies,workspaces:detection.manifests.map((manifest)=>({path:workspacePath(manifest),...manifest.packageName===null?{}:{name:manifest.packageName}}))}):[]])};var catalogPacks=(catalog)=>catalog.items.flatMap((entry)=>{const{kind,pack}=entry.meta.hi;return kind==="pack"&&pack!==undefined&&entry.name!==corePackName?[{id:entry.name.replace(/^pack-/u,""),pack}]:[]});var detectedPacks=(detection,catalog)=>catalogPacks(catalog).flatMap(({id,pack})=>{const evidence=pack.category==="default"?[]:packEvidence(id,pack,detection);return evidence.length===0?[]:[{evidence,id}]}).toSorted((left,right)=>left.id.localeCompare(right.id));var proposePacks=(detection,catalog)=>sorted([...catalogPacks(catalog).filter(({pack})=>pack.category==="default").map(({id})=>id),...detectedPacks(detection,catalog).map(({id})=>id)]);var proposeSoftwareScopes=(shape)=>shape.workspaces.filter((workspace)=>workspace.languages.includes("typescript")&&!isWikiPath(workspace.path)&&workspace.path!==shape.wikiRoot&&!(shape.monorepo&&workspace.path===".")).map((workspace)=>workspace.path);var promptSpecRoot=".devpunks/specs/prompts";var workflowEntrypoints=["business-finder","functional-finder","requirements-phase","design-phase","delivery-phase","debugging-phase","review-phase","docs-ingest-phase","parallel-research"];var isPhaseSkill=(skill)=>skill.endsWith("-phase")||skill==="business-finder"||skill==="functional-finder";var packPrefix="pack-";var skillPrefix="skill-";var installedPacks=(context3)=>context3.items.filter((item)=>item.meta.hi.kind==="pack"&&item.name.startsWith(packPrefix)).map((item)=>({id:item.name.slice(packPrefix.length),category:item.meta.hi.pack?.category,languages:item.meta.hi.pack?.languages??[],promptSurfaces:item.meta.hi.pack?.promptSurfaces,skills:(item.registryDependencies??[]).filter((name2)=>name2.startsWith(skillPrefix)).map((name2)=>name2.slice(skillPrefix.length)).toSorted(),technologies:item.meta.hi.pack?.technologies??[]})).toSorted((left,right)=>left.id.localeCompare(right.id));var intersects2=(left,right)=>left.some((value3)=>right.includes(value3));var workspacePromptSurface="workspace-prompt-spec";var packsForWorkspace=(packs,workspace)=>packs.filter((pack)=>{if(pack.category==="default"){return pack.promptSurfaces?.includes(workspacePromptSurface)??true}if(pack.category==="surface"){return surfaceApplies(pack.id,{technologies:workspace.technologies,workspaces:[workspace]})}return intersects2(pack.technologies,workspace.technologies)||intersects2(pack.languages,workspace.languages)});var sharedSpec={directory:".agents",spec:`${promptSpecRoot}/shared-agents.md`,target:".agents/AGENTS.md"};var rootSpec={directory:".",spec:`${promptSpecRoot}/root.md`,target:"AGENTS.md"};var docsSpec={directory:"docs",spec:`${promptSpecRoot}/docs.md`,target:"docs/AGENTS.md"};var docsPackId="docs";var workspaceSpec=(workspacePath2)=>({directory:workspacePath2,spec:`${promptSpecRoot}/${workspacePath2}/prompt.md`,target:`${workspacePath2}/AGENTS.md`});var nonRootWorkspaces=(context3)=>context3.shape.workspaces.filter((workspace)=>workspace.path!==".").toSorted((left,right)=>left.path.localeCompare(right.path));var authoredPromptSpecs=(context3)=>[rootSpec,...context3.settings.packs.includes(docsPackId)&&context3.shape.docsRoot!==undefined?[docsSpec]:[],...nonRootWorkspaces(context3).map((workspace)=>workspaceSpec(workspace.path))];var repositoryPath=(directory3,repositoryRelative)=>path15.posix.relative(directory3,repositoryRelative);var skillRows=(packs,directory3)=>[...new Set(packs.flatMap((pack)=>pack.skills))].filter((skill)=>!isPhaseSkill(skill)).toSorted().map((id)=>({id,path:repositoryPath(directory3,`.agents/skills/${id}/SKILL.md`)}));var promptSpecContext=(spec,packs)=>({packs:packs.map((pack)=>pack.id),skills:skillRows(packs,spec.directory),spec:spec.spec,target:spec.target,workspace:spec.directory});var scopedPromptSpecContext=(spec,packs)=>({...promptSpecContext(spec,packs),sourceGuide:repositoryPath(spec.directory,"opensrc/README.md")});var defaultPacks=(context3)=>installedPacks(context3).filter((pack)=>pack.category==="default");var pure=(build2)=>async(input)=>await Promise.resolve(build2(input));var rootBuilder=({context:context3})=>{const packs=installedPacks(context3);const skills=new Set(packs.flatMap((pack)=>pack.skills));return{...promptSpecContext(rootSpec,packs),entrypoints:workflowEntrypoints.filter((skill)=>skills.has(skill))}};var sharedBuilder=({context:context3})=>promptSpecContext(sharedSpec,defaultPacks(context3));var docsBuilder=({context:context3})=>scopedPromptSpecContext(docsSpec,defaultPacks(context3));var workspaceBuilder=({context:context3,scope:scope3})=>{if(scope3===undefined){throw new Error("prompt-spec-workspace requires a workspace expansion scope")}return scopedPromptSpecContext(workspaceSpec(scope3.path),packsForWorkspace(installedPacks(context3),scope3))};var inlineCodeList=(values)=>values.length===0?"(none)":values.map((value3)=>`\`${value3}\``).join(", ");var handoffBuilder=({context:context3})=>({monorepo:context3.shape.monorepo?"yes":"no",packs:installedPacks(context3).map((pack)=>({id:pack.id,skills:inlineCodeList(pack.skills)})),promptSpecs:authoredPromptSpecs(context3).map(({spec,target})=>({spec,target})),requiredTools:inlineCodeList(context3.settings.requiredTools.toSorted()),semanticReads:context3.settings.packs.includes("typescript"),softwareScopes:context3.settings.softwareScopes.toSorted(),workspaces:nonRootWorkspaces(context3).map((workspace)=>({path:workspace.path,technologies:inlineCodeList(workspace.technologies)}))});var promptsBuilders={"agent-handoff":pure(handoffBuilder),"prompt-spec-docs":pure(docsBuilder),"prompt-spec-root":pure(rootBuilder),"prompt-spec-shared":pure(sharedBuilder),"prompt-spec-workspace":pure(workspaceBuilder)};var sourceGuidesReadmeBuilder="source-guides-readme";var guidePrefix=itemNames.sourceGuide("");var readme=async({context:context3})=>await Promise.resolve({guides:context3.items.filter((item)=>item.meta.hi.kind==="source-guide"&&item.name.startsWith(guidePrefix)).map((item)=>{const id=item.name.slice(guidePrefix.length);return{id,title:item.title??id}}).toSorted((left,right)=>left.id<right.id?-1:1)});var sourceGuidesBuilders={[sourceGuidesReadmeBuilder]:readme};var builders={...commitGateBuilders,...lintBuilders,...promptsBuilders,...sourceGuidesBuilders};var tagPattern=/\{\{\s*(?<sigil>[#^/!]?)\s*(?<body>[^}]*?)\s*\}\}/gu;class TemplateError extends TaggedError2("TemplateError"){}var stripStandaloneLines=(source)=>source.replaceAll(/^[ \t]*(?<tag>\{\{\s*[#^/!][^}]*\}\})[ \t]*\r?\n/gmu,"$<tag>");var parse3=(source)=>{const root=[];const stack=[];let current=root;let cursor2=0;for(const match8 of stripStandaloneLines(source).matchAll(tagPattern)){const[whole,sigil="",body=""]=match8;const index=match8.index??0;const text3=stripStandaloneLines(source).slice(cursor2,index);if(text3.length>0){current.push({_tag:"Text",text:text3})}cursor2=index+whole.length;if(sigil==="!"){continue}if(sigil==="#"||sigil==="^"){const frame={children:[],inverted:sigil==="^",path:body};current.push({_tag:"Section",children:frame.children,inverted:frame.inverted,path:frame.path});stack.push(frame);current=frame.children;continue}if(sigil==="/"){const frame=stack.pop();if(frame===undefined||frame.path!==body){throw new TemplateError({message:`Unexpected closing tag {{/${body}}}`})}current=stack.at(-1)?.children??root;continue}const json2=body.startsWith("json ");current.push({_tag:"Value",json:json2,path:json2?body.slice(5).trim():body})}if(stack.length>0){throw new TemplateError({message:`Unclosed section {{#${stack.at(-1)?.path}}}`})}const rest=stripStandaloneLines(source).slice(cursor2);if(rest.length>0){root.push({_tag:"Text",text:rest})}return root};var isRecord5=(value3)=>value3!==null&&typeof value3==="object";var formatValue=(value3,json2)=>{if(json2){return JSON.stringify(value3??null,null,2)}if(value3===undefined||value3===null){return""}if(typeof value3==="string"){return value3}return typeof value3==="number"||typeof value3==="boolean"?`${value3}`:JSON.stringify(value3)};var lookup=(stack,path16)=>{if(path16==="."){return stack.at(-1)}const[head3="",...rest]=path16.split(".");for(let index=stack.length-1;index>=0;index-=1){const frame=stack[index];if(isRecord5(frame)&&head3 in frame){let value3=frame[head3];for(const key of rest){value3=isRecord5(value3)?value3[key]:undefined}return value3}}return};var isTruthy=(value3)=>Array.isArray(value3)?value3.length>0:Boolean(value3);var renderTokens=(tokens,stack)=>{let output="";for(const token of tokens){if(token._tag==="Text"){output+=token.text}else if(token._tag==="Value"){const value3=lookup(stack,token.path);output+=formatValue(value3,token.json)}else{const value3=lookup(stack,token.path);if(token.inverted){output+=isTruthy(value3)?"":renderTokens(token.children,stack)}else if(Array.isArray(value3)){for(const element of value3){output+=renderTokens(token.children,[...stack,element])}}else if(isTruthy(value3)){output+=renderTokens(token.children,[...stack,value3])}}}return output};var renderTemplate=(source,context3)=>renderTokens(parse3(source),[context3]);var encoder3=new TextEncoder;var toScope=(workspace)=>({...workspace,relRoot:path16.posix.relative(workspace.path,".")||".",slug:workspace.path==="."?"root":workspace.path.replaceAll("/","-")});var instances=(expansion,context3)=>{const{settings,shape}=context3;if(expansion==="softwareScopes"){return settings.softwareScopes.map((scope3)=>toScope(shape.workspaces.find((workspace)=>workspace.path===scope3)??{languages:[],path:scope3,technologies:[]}))}if(expansion==="workspaces"){return shape.workspaces.filter((workspace)=>workspace.path!==".").map(toScope)}return[undefined]};var templateContext=(context3,scope3)=>({items:context3.items,scope:scope3,settings:context3.settings,shape:context3.shape,workspace:scope3});var renderLocation=(template,values)=>{const rendered=renderTemplate(template,values).replace(/^~\//u,"");if(rendered.length===0||rendered.split("/").includes("")){return}const normalized=path16.posix.normalize(rendered);if(path16.posix.isAbsolute(normalized)||normalized===".."||normalized.startsWith("../")){throw new Error(`Registry location ${template} renders outside the repository: ${rendered}`)}return normalized};var renderLeaves=(value3,values)=>{if(typeof value3==="string"){return renderTemplate(value3,values)}if(Array.isArray(value3)){return value3.map((element)=>renderLeaves(element,values))}if(value3!==null&&typeof value3==="object"){return Object.fromEntries(Object.entries(value3).map(([key,element])=>[key,renderLeaves(element,values)]))}return value3};var matchesWhen=(when2,context3,scope3)=>{if(when2===undefined){return true}const packs=new Set(["core",...context3.settings.packs]);const technologies=new Set(scope3?.technologies??context3.shape.technologies);const languages=new Set(scope3?.languages??context3.shape.languages);return(when2.packs??[]).every((pack)=>packs.has(pack))&&(when2.technologies??[]).every((technology)=>technologies.has(technology))&&(when2.languages??[]).every((language)=>languages.has(language))};var fileEffects=async({builders:builders2,context:context3,file:file5,item})=>{const meta=item.meta.hi.files?.[file5.path]??{artifact:"copied"};const rendered=meta.artifact==="built"||meta.artifact==="authored"&&meta.template===true;const builder=meta.builder===undefined?undefined:builders2[meta.builder];if(rendered&&meta.builder!==undefined&&builder===undefined){throw new Error(`Registry Item ${item.name} names unknown builder ${meta.builder}`)}const targets=instances(meta.expand,context3).flatMap((scope3)=>{const values=templateContext(context3,scope3);const location2=renderLocation(file5.target,values);return location2===undefined||!matchesWhen(meta.when,context3,scope3)?[]:[{location:location2,scope:scope3,values}]});return await Promise.all(targets.map(async({location:location2,scope:scope3,values})=>{let content;if(rendered){const build2=await builder?.({context:context3,file:file5,item,scope:scope3});content=encoder3.encode(renderTemplate(file5.content,{...values,build:build2}))}else{content=meta.encoding==="base64"?new Uint8Array(Buffer.from(file5.content,"base64")):encoder3.encode(file5.content)}return{_tag:"File",artifact:meta.artifact,content,executable:meta.executable??false,item:item.name,path:location2}}))};var itemLinkMergeDependencyEffects=(item,context3)=>{const effects=[];const{merges=[],symlinks=[],workspaceDependencies=[]}=item.meta.hi;for(const link4 of symlinks){for(const scope3 of instances(link4.expand,context3)){const values=templateContext(context3,scope3);const location2=renderLocation(link4.path,values);const target=renderTemplate(link4.target,values);if(location2!==undefined&&target.length>0){effects.push({_tag:"Symlink",item:item.name,path:location2,target})}}}for(const merge6 of merges){for(const scope3 of instances(merge6.expand,context3)){const values=templateContext(context3,scope3);const target=renderLocation(merge6.target,values);if(target!==undefined){const value3=renderLeaves(merge6.value,values);effects.push({_tag:"Merge",format:merge6.format,item:item.name,target,value:value3})}}}for(const dependencies of workspaceDependencies){for(const scope3 of instances(dependencies.expand,context3)){if(!matchesWhen(dependencies.when,context3,scope3)){continue}const values=templateContext(context3,scope3);for(const[name2,version3]of Object.entries(dependencies.packages)){effects.push({_tag:"Dependency",item:item.name,name:name2,version:renderTemplate(version3,values),workspace:scope3?.path??"."})}}}return effects};var sortKey=(effect2)=>{if(effect2._tag==="Dependency"){return`${effect2.workspace}\x00dependency\x00${effect2.name}\x00${effect2.item}`}return effect2._tag==="Merge"?`${effect2.target}\x00merge\x00${effect2.item}`:`${effect2.path}\x00${effect2._tag}`};var materialize=async(items,context3,options3)=>{const builders2=options3?.builders??builders;const buildAgentFiles=options3?.buildHarnessAgentFiles??buildHarnessAgentFiles;const itemEffects=async(item)=>{const files=await Promise.all((item.files??[]).map(async(file5)=>await fileEffects({builders:builders2,context:context3,file:file5,item})));const manifest=item.meta.hi.harnessAdapters===true?await context3.loadSubagentManifest():undefined;const agentFiles=manifest===undefined?[]:buildAgentFiles({manifest,readRepositoryFile:context3.readRepositoryFile});return[...files.flat(),...itemLinkMergeDependencyEffects(item,context3),...agentFiles.map((agentFile)=>({_tag:"File",artifact:"built",content:encoder3.encode(agentFile.content),executable:false,item:item.name,path:agentFile.path}))]};const perItem=await Promise.all(items.map(itemEffects));const effects=perItem.flat();const locations=new Map;for(const effect2 of effects){if(effect2._tag==="File"||effect2._tag==="Symlink"){const owner=locations.get(effect2.path);if(owner!==undefined){throw new Error(`Registry Items ${owner} and ${effect2.item} both install ${effect2.path}`)}locations.set(effect2.path,effect2.item)}}const requiredTools=[...new Set(items.flatMap((item)=>item.meta.hi.requiredTools??[]))].toSorted();return{effects:effects.toSorted((left,right)=>sortKey(left).localeCompare(sortKey(right))),requiredTools}};var utf8=new TextDecoder("utf-8",{fatal:true});var decodeText2=(bytes)=>{if(bytes.includes(0)){return}try{return utf8.decode(bytes)}catch{return}};var normalizedKey=(bytes)=>{const text3=decodeText2(bytes);return text3===undefined?`binary:${Buffer.from(bytes).toString("base64")}`:`text:${text3.replaceAll(/\r\n?/gu,`
338
+ `)}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}`)),setup:spec.prepareCommands??[],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(([name2,version3])=>`${name2}@${version3}`))})};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)=>(path13)=>{const result3=spawnSync2("git",["show",`HEAD:./${path13}`],{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 path15 from"node:path";import{readdirSync as readdirSync2,statSync as statSync3}from"node:fs";import path14 from"node:path";import{existsSync as existsSync8,readFileSync as readFileSync7,readdirSync,statSync as statSync2}from"node:fs";import path13 from"node:path";class CliDetectionError extends TaggedErrorClass()("CliDetectionError",{cause:optional(Defect()),message:String4}){}var ignoredDirectoryNames=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","coverage","dist","docs","examples","build","node_modules","opensrc","scripts","skills","test-fixtures","tmp","worktrees",".venv","venv","__pycache__"]);var detectionOrder=["nextjs","react","tanstack-query","elysia","trpc","drizzle","better-auth","effect","turborepo"];var languageDetectionOrder=["python","typescript"];var installerTypeScriptFiles=new Set(["oxlint.config.ts","oxlint.local.ts"]);var sourceLanguageExtensions=[{language:"python",pattern:/\.py$/u},{language:"typescript",pattern:/\.(?:ts|tsx)$/u}];var conventionalWorkspaceRoots=["apps","packages","services","libs"];var wikiRootPaths=new Set(["app/wiki","apps/wiki","wiki"]);var pythonDependencyFiles=["Pipfile","poetry.lock","pyproject.toml","requirements.txt","uv.lock"];var detectedPythonPackages=["alembic","sqlalchemy"];var isRecord4=(value3)=>typeof value3==="object"&&value3!==null;var dependencyRecordSchema=Record(String4,String4);var packageJsonSchema=fromJsonString2(Struct({dependencies:optional(dependencyRecordSchema),devDependencies:optional(dependencyRecordSchema),name:optional(String4),optionalDependencies:optional(dependencyRecordSchema),packageManager:optional(String4),peerDependencies:optional(dependencyRecordSchema),workspaces:optional(Unknown2)}));var packageManagerFor=(rootDirectory,packageJson,inheritedDeclaration)=>{const declared=(packageJson.packageManager??inheritedDeclaration)?.split("@",1)[0];const candidates=[["bun","bun.lock"],["bun","bun.lockb"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"],["npm","package-lock.json"]];const match8=candidates.find(([manager,lockfile])=>(declared===manager||declared===undefined)&&existsSync8(path13.join(rootDirectory,lockfile)));if(match8===undefined){const supported=candidates.find(([manager])=>manager===declared);return supported===undefined?null:{packageManager:supported[0]}}return{lockfile:match8[1],packageManager:match8[0]}};var parsePackageJsonRecord=decodeUnknownSync(packageJsonSchema);var decodeWorkspacePackages=decodeUnknownSync(ArraySchema(String4));var collectPackageNames=(pkg)=>{const names=new Set;const addEntries=(record2)=>{if(!record2){return}for(const name2 of Object.keys(record2)){names.add(name2)}};addEntries(pkg.dependencies);addEntries(pkg.devDependencies);addEntries(pkg.peerDependencies);addEntries(pkg.optionalDependencies);return[...names].toSorted()};var normalizeRelativePath=(relativePath)=>relativePath.split(path13.sep).join("/");var isWikiRelativePath=(relativePath)=>{const normalized=normalizeRelativePath(relativePath);return[...wikiRootPaths].some((wikiRoot)=>normalized===wikiRoot||normalized.startsWith(`${wikiRoot}/`))};var nothingIgnored=()=>false;var processLayer2=layer3.pipe(provide2(mergeAll2(layer7,layer9)));var gitIgnoredPaths=(cwd)=>gen2(function*listGitIgnoredPaths(){const git2=yield*exports_ChildProcess.make("git",["ls-files","-z","--others","--ignored","--exclude-standard","--directory"],{cwd,stderr:"ignore",stdin:"ignore"});const[stdout,exitCode]=yield*all2([mkString(decodeText(git2.stdout)),git2.exitCode],{concurrency:"unbounded"});if(exitCode!==0){return nothingIgnored}const entries=stdout.split("\x00").filter((entry)=>entry.length>0);const files=new Set(entries.filter((entry)=>!entry.endsWith("/")));const directories=new Set(entries.filter((entry)=>entry.endsWith("/")).map((entry)=>entry.slice(0,-1)));const isIgnored=(relativePath)=>{const segments=normalizeRelativePath(relativePath).split("/");return files.has(segments.join("/"))||segments.some((_,index)=>directories.has(segments.slice(0,index+1).join("/")))};return isIgnored}).pipe(scoped2,provide4(processLayer2),orElseSucceed2(()=>nothingIgnored));var isWikiManifest=(manifest)=>isWikiRelativePath(manifest.relativePath);var packDetectionManifests=(manifests)=>manifests.filter((manifest)=>!isWikiManifest(manifest));var recursiveFindFiles=(cwd,filename,isIgnored)=>{const results=[];const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path13.join(directory3,entry.name);if(ignoredDirectoryNames.has(entry.name)||isIgnored(path13.relative(cwd,absolutePath))){continue}if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&entry.name===filename){results.push(absolutePath)}}};if(existsSync8(cwd)){visit2(cwd)}return results.toSorted()};var detectPythonPackages=(cwd,isIgnored)=>{const detected=new Set;for(const filename of pythonDependencyFiles){for(const dependencyFile of recursiveFindFiles(cwd,filename,isIgnored)){if(isWikiRelativePath(path13.relative(cwd,dependencyFile))){continue}const content=readFileSync7(dependencyFile,"utf-8");for(const packageName of detectedPythonPackages){const pattern=new RegExp(`(?:^|[\\s"'[,])${packageName}(?=$|[\\s"'\\[\\],=<>~!;])`,"imu");if(pattern.test(content)){detected.add(packageName)}}}}return[...detected].toSorted()};var discoverConventionalWorkspacePackageJsonPaths=(cwd)=>conventionalWorkspaceRoots.flatMap((rootDirectoryName)=>{const rootDirectory=path13.join(cwd,rootDirectoryName);if(!existsSync8(rootDirectory)){return[]}return readdirSync(rootDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path13.join(rootDirectory,entry.name,"package.json")).filter((manifestPath)=>existsSync8(manifestPath))});var discoverTopLevelPackageJsonPaths=(cwd)=>readdirSync(cwd,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path13.join(cwd,entry.name,"package.json")).filter((manifestPath)=>existsSync8(manifestPath));var readPackageJsonWorkspacePatterns=(pkg)=>{const{workspaces}=pkg;if(isArray(workspaces)){return decodeWorkspacePackages(workspaces)}if(isRecord4(workspaces)&&isArray(workspaces.packages)){return decodeWorkspacePackages(workspaces.packages)}return[]};var parsePnpmWorkspacePatterns=(content)=>{const patterns=[];let inPackagesSection=false;for(const rawLine of content.split(/\r?\n/u)){const line=rawLine.trim();if(line==="packages:"){inPackagesSection=true;continue}if(!inPackagesSection){continue}if(line.startsWith("- ")){const pattern=line.slice(2).trim().replaceAll(/^['"]|['"]$/gu,"");if(pattern.length>0){patterns.push(pattern)}continue}if(line.length>0&&!line.startsWith("#")){break}}return patterns};var readPnpmWorkspacePatterns=(cwd)=>{const workspacePath=path13.join(cwd,"pnpm-workspace.yaml");return existsSync8(workspacePath)?parsePnpmWorkspacePatterns(readFileSync7(workspacePath,"utf-8")):[]};var expandWorkspacePattern=(cwd,pattern)=>{if(pattern.endsWith("/*")){const baseDirectory=path13.join(cwd,pattern.slice(0,-2));if(!existsSync8(baseDirectory)){return[]}return readdirSync(baseDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path13.join(baseDirectory,entry.name,"package.json")).filter((manifestPath2)=>existsSync8(manifestPath2)).toSorted()}if(pattern.includes("*")){return[]}const manifestPath=path13.join(cwd,pattern,"package.json");return existsSync8(manifestPath)?[manifestPath]:[]};var discoverPackageJsonInputs=(cwd,isIgnored)=>{const rootPackageJsonPath=path13.join(cwd,"package.json");const recursivePackageJsonPaths=recursiveFindFiles(cwd,"package.json",isIgnored);if(!existsSync8(rootPackageJsonPath)){return{declaredWorkspacePaths:new Set,manifestPaths:recursivePackageJsonPaths,rootPackageJson:null}}const rootPackageJson=parsePackageJsonRecord(readFileSync7(rootPackageJsonPath,"utf-8"));const workspacePatterns=new Set([...readPackageJsonWorkspacePatterns(rootPackageJson),...readPnpmWorkspacePatterns(cwd)]);const workspacePackageJsonPaths=[...workspacePatterns].flatMap((pattern)=>expandWorkspacePattern(cwd,pattern));const conventionalWorkspacePackageJsonPaths=discoverConventionalWorkspacePackageJsonPaths(cwd);const topLevelPackageJsonPaths=discoverTopLevelPackageJsonPaths(cwd);return{declaredWorkspacePaths:new Set(recursivePackageJsonPaths.filter((manifestPath)=>{const relative=path13.relative(cwd,path13.dirname(manifestPath)).split(path13.sep).join("/");return relative!==""&&[...workspacePatterns].some((pattern)=>!pattern.startsWith("!")&&path13.matchesGlob(relative,pattern))&&![...workspacePatterns].some((pattern)=>pattern.startsWith("!")&&path13.matchesGlob(relative,pattern.slice(1)))})),manifestPaths:[...recursivePackageJsonPaths,...workspacePackageJsonPaths,...conventionalWorkspacePackageJsonPaths,...topLevelPackageJsonPaths].filter((value3,index,values)=>values.indexOf(value3)===index&&!isIgnored(path13.relative(cwd,value3))).toSorted(),rootPackageJson}};var detectTechnologies=(manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set;const hasPackage=(packageName)=>packageNames.has(packageName);const hasPackagePrefix=(prefix3)=>[...packageNames].some((packageName)=>packageName.startsWith(prefix3));if(hasPackage("next")){detected.add("nextjs");detected.add("react")}if(hasPackage("react")||hasPackage("react-dom")){detected.add("react")}if(hasPackage("@tanstack/react-query")||hasPackage("@tanstack/query-core")||hasPackage("@tanstack/react-query-devtools")||hasPackage("@tanstack/react-query-persist-client")||hasPackage("@tanstack/query-persist-client-core")){detected.add("tanstack-query")}if(hasPackage("elysia")){detected.add("elysia")}if(hasPackagePrefix("@trpc/")){detected.add("trpc")}if(hasPackage("drizzle-orm")||hasPackage("drizzle-kit")){detected.add("drizzle")}if(hasPackage("better-auth")){detected.add("better-auth")}if(hasPackage("effect")||hasPackagePrefix("@effect/")){detected.add("effect")}if(hasPackage("turbo")){detected.add("turborepo")}return detectionOrder.filter((technology)=>detected.has(technology))};var hasPackageTrigger=(packageNames,trigger)=>trigger.endsWith("/")?[...packageNames].some((packageName)=>packageName.startsWith(trigger)):packageNames.has(trigger);var isSourceDirectoryPath=(cwd,directory3)=>path13.relative(cwd,directory3)!=="";var detectSourceLanguages=(cwd,isIgnored)=>{const detected=new Set;const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path13.join(directory3,entry.name);const relativePath=path13.relative(cwd,absolutePath);if(ignoredDirectoryNames.has(entry.name)||isIgnored(relativePath)){continue}if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&isSourceDirectoryPath(cwd,directory3)&&!isWikiRelativePath(relativePath)){for(const{language,pattern}of sourceLanguageExtensions){if(pattern.test(entry.name)&&!entry.name.endsWith(".d.ts")&&!installerTypeScriptFiles.has(entry.name)){detected.add(language)}}}}};if(existsSync8(cwd)){visit2(cwd)}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectLanguages=(cwd,manifests,isIgnored)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set(detectSourceLanguages(cwd,isIgnored));if(hasPackageTrigger(packageNames,"typescript")){detected.add("typescript")}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectMonorepoSignals=(cwd,manifests,isIgnored)=>{const signals=[];for(const workspacePath of recursiveFindFiles(cwd,"pnpm-workspace.yaml",isIgnored)){signals.push({path:workspacePath,type:"pnpm-workspace"})}for(const turboConfigPath of recursiveFindFiles(cwd,"turbo.json",isIgnored)){signals.push({path:turboConfigPath,type:"turbo-config"})}for(const manifest of manifests){const pkg=parsePackageJsonRecord(readFileSync7(manifest.path,"utf-8"));const{workspaces}=pkg;const hasWorkspaces=isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages);if(hasWorkspaces){signals.push({path:manifest.path,type:"package-json-workspaces"})}}const workspaceManifests=manifests.filter((manifest)=>{const pkg=parsePackageJsonRecord(readFileSync7(manifest.path,"utf-8"));const{workspaces}=pkg;return!(isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages))});if(workspaceManifests.length>1){signals.push({path:cwd,type:"workspace-packages"})}return signals.filter((signal,index,allSignals)=>allSignals.findIndex((candidate)=>candidate.type===signal.type&&candidate.path===signal.path)===index)};var detectRepository=(cwd)=>flatMap3(gitIgnoredPaths(cwd),(isIgnored)=>try_3({catch:(cause)=>new CliDetectionError({cause,message:"Failed to detect repository shape."}),try:()=>{const root=statSync2(cwd,{throwIfNoEntry:false});if(root===undefined||!root.isDirectory()){throw new TypeError("Repository input must be an existing directory.")}const{declaredWorkspacePaths,manifestPaths,rootPackageJson}=discoverPackageJsonInputs(cwd,isIgnored);const rootDeclaration=rootPackageJson?.packageManager===undefined?undefined:packageManagerFor(cwd,rootPackageJson)?.packageManager;const manifests=manifestPaths.map((manifestPath)=>{const pkg=parsePackageJsonRecord(readFileSync7(manifestPath,"utf-8"));const packageManager=packageManagerFor(cwd,pkg,declaredWorkspacePaths.has(manifestPath)?rootDeclaration:undefined);return{dependencies:collectPackageNames(pkg),...packageManager,packageName:pkg.name??null,path:manifestPath,relativePath:path13.relative(cwd,manifestPath)||"package.json"}});const detectedLanguages=detectLanguages(cwd,manifests,isIgnored);const detectedPackages=detectPythonPackages(cwd,isIgnored);const detectedTechnologies=detectTechnologies(manifests);const monorepoSignals=detectMonorepoSignals(cwd,manifests,isIgnored);return{cwd,detectedLanguages,detectedPackages,detectedTechnologies,manifests,monorepo:monorepoSignals.length>0,monorepoSignals}}}));var wikiRoots=["apps/wiki","app/wiki","wiki"];var isDirectory=(absolute)=>{try{return statSync3(absolute).isDirectory()}catch{return false}};var isWikiPath=(relative)=>wikiRoots.some((wiki)=>relative===wiki||relative.startsWith(`${wiki}/`));var detectWikiRoot=(root)=>wikiRoots.find((wiki)=>isDirectory(path14.join(root,wiki)));var docsRoot="docs";var workspacePath=(manifest)=>{const directory3=path14.posix.dirname(manifest.relativePath.split(path14.sep).join("/"));return directory3===""?".":directory3};var sorted=(values)=>[...new Set(values)].toSorted();var typeScriptSourcePattern=/\.(?:ts|tsx|mts|cts)$/u;var declarationPattern=/\.d\.(?:ts|mts|cts)$/u;var tsconfigPattern2=/^tsconfig.*\.json$/u;var skippedScanDirectories=new Set(["build","dist","node_modules","opensrc"]);var maxScanDepth=8;var hasTypeScriptEvidence=(root,workspace,isIgnored)=>{const visit2=(directory3,depth)=>{let entries;try{entries=readdirSync2(directory3,{withFileTypes:true})}catch{return false}return entries.some((entry)=>{if(isIgnored(path14.relative(root,path14.join(directory3,entry.name)))){return false}if(entry.isDirectory()){return depth<maxScanDepth&&!entry.name.startsWith(".")&&!skippedScanDirectories.has(entry.name)&&visit2(path14.join(directory3,entry.name),depth+1)}return entry.isFile()&&(depth===0&&tsconfigPattern2.test(entry.name)||typeScriptSourcePattern.test(entry.name)&&!declarationPattern.test(entry.name)&&!installerTypeScriptFiles.has(entry.name))})};return visit2(path14.join(root,workspace),0)};var workspaceLanguages=(root,workspace,detected,isIgnored)=>sorted(detected.includes("typescript")||!hasTypeScriptEvidence(root,workspace,isIgnored)?detected:[...detected,"typescript"]);var detectionError=(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:"."});var repositoryDetection=(root)=>detectRepository(root).pipe(mapError3(detectionError));var detectShape=(root,packs)=>gen2(function*detectRecordedShape(){const detection=yield*detectRepository(root);const isIgnored=yield*gitIgnoredPaths(root);const wikiRoot=detectWikiRoot(root);const workspaces=[];for(const manifest of detection.manifests){const relative=workspacePath(manifest);if(wikiRoot!==undefined&&(relative===wikiRoot||relative.startsWith(`${wikiRoot}/`))){continue}const scoped4=relative==="."?detection:yield*detectRepository(path14.join(root,relative));workspaces.push({languages:workspaceLanguages(root,relative,scoped4.detectedLanguages,isIgnored),...manifest.packageName===null?{}:{name:manifest.packageName},path:relative,technologies:sorted(scoped4.detectedTechnologies)})}return{...isDirectory(path14.join(root,docsRoot))&&!isIgnored(docsRoot)?{docsRoot}:{},languages:sorted(detection.detectedLanguages),monorepo:detection.monorepo,packs:sorted(packs),technologies:sorted(detection.detectedTechnologies),...wikiRoot===undefined?{}:{wikiRoot},workspaces:workspaces.filter((workspace,index)=>workspaces.findIndex((other)=>other.path===workspace.path)===index).toSorted((left,right)=>left.path.localeCompare(right.path))}}).pipe(mapError3(detectionError));var backendWorkspaceSegments=new Set(["api","backend","server","services"]);var backendPackageSegments=new Set(["api","backend","server","service"]);var backendTechnologies=new Set(["better-auth","drizzle","elysia","trpc"]);var frontendTechnologies=new Set(["nextjs","react"]);var hasBackendWorkspaceName=(workspace)=>workspace.path.split("/").some((segment)=>backendWorkspaceSegments.has(segment))||(workspace.name??"").replace(/^@[^/]+\//u,"").split(/[^a-zA-Z0-9]+/u).some((segment)=>backendPackageSegments.has(segment.toLowerCase()));var surfaceSignals=(id,evidence)=>{if(id==="backend"){return[...evidence.technologies.filter((technology)=>backendTechnologies.has(technology)),...evidence.workspaces.filter(hasBackendWorkspaceName).map((workspace)=>workspace.path)]}return id==="frontend"?evidence.technologies.filter((technology)=>frontendTechnologies.has(technology)):[]};var surfaceApplies=(id,evidence)=>surfaceSignals(id,evidence).length>0;var packEvidence=(id,pack,detection)=>{const dependencies=detection.manifests.filter((manifest)=>!isWikiPath(manifest.relativePath.split(path14.sep).join("/"))).flatMap((manifest)=>manifest.dependencies);const packages=new Set(pack.category==="detected"?[...dependencies,...detection.detectedPackages??[]]:dependencies);const hasTrigger=(trigger)=>trigger.endsWith("/")?[...packages].some((name2)=>name2.startsWith(trigger)):packages.has(trigger);const technologies=detection.detectedTechnologies;const languages=detection.detectedLanguages;return sorted([...(pack.triggerPackages??[]).filter(hasTrigger).map((trigger)=>trigger.endsWith("/")?`${trigger}*`:trigger),...[id,...pack.technologies??[]].filter((technology)=>technologies.includes(technology)),...[id,...pack.languages??[]].filter((language)=>languages.includes(language)),...pack.category==="surface"?surfaceSignals(id,{technologies,workspaces:detection.manifests.map((manifest)=>({path:workspacePath(manifest),...manifest.packageName===null?{}:{name:manifest.packageName}}))}):[]])};var catalogPacks=(catalog)=>catalog.items.flatMap((entry)=>{const{kind,pack}=entry.meta.hi;return kind==="pack"&&pack!==undefined&&entry.name!==corePackName?[{id:entry.name.replace(/^pack-/u,""),pack}]:[]});var detectedPacks=(detection,catalog)=>catalogPacks(catalog).flatMap(({id,pack})=>{const evidence=pack.category==="default"?[]:packEvidence(id,pack,detection);return evidence.length===0?[]:[{evidence,id}]}).toSorted((left,right)=>left.id.localeCompare(right.id));var proposePacks=(detection,catalog)=>sorted([...catalogPacks(catalog).filter(({pack})=>pack.category==="default").map(({id})=>id),...detectedPacks(detection,catalog).map(({id})=>id)]);var proposeSoftwareScopes=(shape)=>shape.workspaces.filter((workspace)=>workspace.languages.includes("typescript")&&!isWikiPath(workspace.path)&&workspace.path!==shape.wikiRoot&&!(shape.monorepo&&workspace.path===".")).map((workspace)=>workspace.path);var promptSpecRoot=".devpunks/specs/prompts";var workflowEntrypoints=["business-finder","functional-finder","requirements-phase","design-phase","delivery-phase","debugging-phase","review-phase","docs-ingest-phase","parallel-research"];var isPhaseSkill=(skill)=>skill.endsWith("-phase")||skill==="business-finder"||skill==="functional-finder";var packPrefix="pack-";var skillPrefix="skill-";var installedPacks=(context3)=>context3.items.filter((item)=>item.meta.hi.kind==="pack"&&item.name.startsWith(packPrefix)).map((item)=>({id:item.name.slice(packPrefix.length),category:item.meta.hi.pack?.category,languages:item.meta.hi.pack?.languages??[],promptSurfaces:item.meta.hi.pack?.promptSurfaces,skills:(item.registryDependencies??[]).filter((name2)=>name2.startsWith(skillPrefix)).map((name2)=>name2.slice(skillPrefix.length)).toSorted(),technologies:item.meta.hi.pack?.technologies??[]})).toSorted((left,right)=>left.id.localeCompare(right.id));var intersects2=(left,right)=>left.some((value3)=>right.includes(value3));var hasPromptSurface=(pack,surface)=>pack.promptSurfaces?.includes(surface)??false;var workspaceFit=(pack,workspace)=>{if(pack.category==="default"){return hasPromptSurface(pack,"workspace-prompt-spec")?"definite":"none"}if(pack.category==="surface"){if(!surfaceApplies(pack.id,{technologies:workspace.technologies,workspaces:[workspace]})){return"none"}return pack.id==="backend"&&!hasBackendWorkspaceName(workspace)?"candidate":"definite"}return intersects2(pack.technologies,workspace.technologies)||intersects2(pack.languages,workspace.languages)?"definite":"none"};var sharedSpec={directory:".agents",spec:`${promptSpecRoot}/shared-agents.md`,target:".agents/AGENTS.md"};var rootSpec={directory:".",spec:`${promptSpecRoot}/root.md`,target:"AGENTS.md"};var docsSpec={directory:"docs",spec:`${promptSpecRoot}/docs.md`,target:"docs/AGENTS.md"};var docsPackId="docs";var workspaceSpec=(workspacePath2)=>({directory:workspacePath2,spec:`${promptSpecRoot}/${workspacePath2}/prompt.md`,target:`${workspacePath2}/AGENTS.md`});var nonRootWorkspaces=(context3)=>context3.shape.workspaces.filter((workspace)=>workspace.path!==".").toSorted((left,right)=>left.path.localeCompare(right.path));var authoredPromptSpecs=(context3)=>[rootSpec,...context3.settings.packs.includes(docsPackId)&&context3.shape.docsRoot!==undefined?[docsSpec]:[],...nonRootWorkspaces(context3).map((workspace)=>workspaceSpec(workspace.path))];var repositoryPath=(directory3,repositoryRelative)=>path15.posix.relative(directory3,repositoryRelative);var skillRows=(packs,directory3)=>[...new Set(packs.flatMap((pack)=>pack.skills))].filter((skill)=>!isPhaseSkill(skill)).toSorted().map((id)=>({id,path:repositoryPath(directory3,`.agents/skills/${id}/SKILL.md`)}));var promptSpecContext=(spec,packs)=>({packs:packs.map((pack)=>pack.id),skills:skillRows(packs,spec.directory),spec:spec.spec,target:spec.target,workspace:spec.directory});var scopedPromptSpecContext=(spec,packs)=>({...promptSpecContext(spec,packs),sourceGuide:repositoryPath(spec.directory,"opensrc/README.md")});var defaultPacks=(context3)=>installedPacks(context3).filter((pack)=>pack.category==="default");var pure=(build2)=>async(input)=>await Promise.resolve(build2(input));var rootBuilder=({context:context3})=>{const packs=installedPacks(context3);const skills=new Set(packs.flatMap((pack)=>pack.skills));return{...promptSpecContext(rootSpec,packs),entrypoints:workflowEntrypoints.filter((skill)=>skills.has(skill))}};var sharedBuilder=({context:context3})=>promptSpecContext(sharedSpec,defaultPacks(context3));var docsBuilder=({context:context3})=>scopedPromptSpecContext(docsSpec,installedPacks(context3).filter((pack)=>hasPromptSurface(pack,"docs-prompt-spec")));var workspaceBuilder=({context:context3,scope:scope3})=>{if(scope3===undefined){throw new Error("prompt-spec-workspace requires a workspace expansion scope")}const spec=workspaceSpec(scope3.path);const packs=installedPacks(context3);const definite=scopedPromptSpecContext(spec,packs.filter((pack)=>workspaceFit(pack,scope3)==="definite"));const candidates=packs.filter((pack)=>workspaceFit(pack,scope3)==="candidate");if(candidates.length===0){return definite}const definiteSkills=new Set(definite.skills.map((skill)=>skill.id));return{...definite,optional:{packs:candidates.map((pack)=>pack.id),skills:skillRows(candidates,spec.directory).filter((skill)=>!definiteSkills.has(skill.id))}}};var inlineCodeList=(values)=>values.length===0?"(none)":values.map((value3)=>`\`${value3}\``).join(", ");var handoffBuilder=({context:context3})=>({monorepo:context3.shape.monorepo?"yes":"no",packs:installedPacks(context3).map((pack)=>({id:pack.id,skills:inlineCodeList(pack.skills)})),promptSpecs:authoredPromptSpecs(context3).map(({spec,target})=>({spec,target})),requiredTools:inlineCodeList(context3.settings.requiredTools.toSorted()),semanticReads:context3.settings.packs.includes("typescript"),softwareScopes:context3.settings.softwareScopes.toSorted(),workspaces:nonRootWorkspaces(context3).map((workspace)=>({path:workspace.path,technologies:inlineCodeList(workspace.technologies)}))});var promptsBuilders={"agent-handoff":pure(handoffBuilder),"prompt-spec-docs":pure(docsBuilder),"prompt-spec-root":pure(rootBuilder),"prompt-spec-shared":pure(sharedBuilder),"prompt-spec-workspace":pure(workspaceBuilder)};var sourceGuidesReadmeBuilder="source-guides-readme";var guidePrefix=itemNames.sourceGuide("");var readme=async({context:context3})=>await Promise.resolve({guides:context3.items.filter((item)=>item.meta.hi.kind==="source-guide"&&item.name.startsWith(guidePrefix)).map((item)=>{const id=item.name.slice(guidePrefix.length);return{id,title:item.title??id}}).toSorted((left,right)=>left.id<right.id?-1:1)});var sourceGuidesBuilders={[sourceGuidesReadmeBuilder]:readme};var builders={...commitGateBuilders,...lintBuilders,...promptsBuilders,...sourceGuidesBuilders};var tagPattern=/\{\{\s*(?<sigil>[#^/!]?)\s*(?<body>[^}]*?)\s*\}\}/gu;class TemplateError extends TaggedError2("TemplateError"){}var stripStandaloneLines=(source)=>source.replaceAll(/^[ \t]*(?<tag>\{\{\s*[#^/!][^}]*\}\})[ \t]*\r?\n/gmu,"$<tag>");var parse3=(source)=>{const root=[];const stack=[];let current=root;let cursor2=0;for(const match8 of stripStandaloneLines(source).matchAll(tagPattern)){const[whole,sigil="",body=""]=match8;const index=match8.index??0;const text3=stripStandaloneLines(source).slice(cursor2,index);if(text3.length>0){current.push({_tag:"Text",text:text3})}cursor2=index+whole.length;if(sigil==="!"){continue}if(sigil==="#"||sigil==="^"){const frame={children:[],inverted:sigil==="^",path:body};current.push({_tag:"Section",children:frame.children,inverted:frame.inverted,path:frame.path});stack.push(frame);current=frame.children;continue}if(sigil==="/"){const frame=stack.pop();if(frame===undefined||frame.path!==body){throw new TemplateError({message:`Unexpected closing tag {{/${body}}}`})}current=stack.at(-1)?.children??root;continue}const json2=body.startsWith("json ");current.push({_tag:"Value",json:json2,path:json2?body.slice(5).trim():body})}if(stack.length>0){throw new TemplateError({message:`Unclosed section {{#${stack.at(-1)?.path}}}`})}const rest=stripStandaloneLines(source).slice(cursor2);if(rest.length>0){root.push({_tag:"Text",text:rest})}return root};var isRecord5=(value3)=>value3!==null&&typeof value3==="object";var formatValue=(value3,json2)=>{if(json2){return JSON.stringify(value3??null,null,2)}if(value3===undefined||value3===null){return""}if(typeof value3==="string"){return value3}return typeof value3==="number"||typeof value3==="boolean"?`${value3}`:JSON.stringify(value3)};var lookup=(stack,path16)=>{if(path16==="."){return stack.at(-1)}const[head3="",...rest]=path16.split(".");for(let index=stack.length-1;index>=0;index-=1){const frame=stack[index];if(isRecord5(frame)&&head3 in frame){let value3=frame[head3];for(const key of rest){value3=isRecord5(value3)?value3[key]:undefined}return value3}}return};var isTruthy=(value3)=>Array.isArray(value3)?value3.length>0:Boolean(value3);var renderTokens=(tokens,stack)=>{let output="";for(const token of tokens){if(token._tag==="Text"){output+=token.text}else if(token._tag==="Value"){const value3=lookup(stack,token.path);output+=formatValue(value3,token.json)}else{const value3=lookup(stack,token.path);if(token.inverted){output+=isTruthy(value3)?"":renderTokens(token.children,stack)}else if(Array.isArray(value3)){for(const element of value3){output+=renderTokens(token.children,[...stack,element])}}else if(isTruthy(value3)){output+=renderTokens(token.children,[...stack,value3])}}}return output};var renderTemplate=(source,context3)=>renderTokens(parse3(source),[context3]);var encoder3=new TextEncoder;var toScope=(workspace)=>({...workspace,relRoot:path16.posix.relative(workspace.path,".")||".",slug:workspace.path==="."?"root":workspace.path.replaceAll("/","-")});var instances=(expansion,context3)=>{const{settings,shape}=context3;if(expansion==="softwareScopes"){return settings.softwareScopes.map((scope3)=>toScope(shape.workspaces.find((workspace)=>workspace.path===scope3)??{languages:[],path:scope3,technologies:[]}))}if(expansion==="workspaces"){return shape.workspaces.filter((workspace)=>workspace.path!==".").map(toScope)}return[undefined]};var templateContext=(context3,scope3)=>({items:context3.items,scope:scope3,settings:context3.settings,shape:context3.shape,workspace:scope3});var renderLocation=(template,values)=>{const rendered=renderTemplate(template,values).replace(/^~\//u,"");if(rendered.length===0||rendered.split("/").includes("")){return}const normalized=path16.posix.normalize(rendered);if(path16.posix.isAbsolute(normalized)||normalized===".."||normalized.startsWith("../")){throw new Error(`Registry location ${template} renders outside the repository: ${rendered}`)}return normalized};var renderLeaves=(value3,values)=>{if(typeof value3==="string"){return renderTemplate(value3,values)}if(Array.isArray(value3)){return value3.map((element)=>renderLeaves(element,values))}if(value3!==null&&typeof value3==="object"){return Object.fromEntries(Object.entries(value3).map(([key,element])=>[key,renderLeaves(element,values)]))}return value3};var matchesWhen=(when2,context3,scope3)=>{if(when2===undefined){return true}const packs=new Set(["core",...context3.settings.packs]);const technologies=new Set(scope3?.technologies??context3.shape.technologies);const languages=new Set(scope3?.languages??context3.shape.languages);return(when2.packs??[]).every((pack)=>packs.has(pack))&&(when2.technologies??[]).every((technology)=>technologies.has(technology))&&(when2.languages??[]).every((language)=>languages.has(language))};var fileEffects=async({builders:builders2,context:context3,file:file5,item})=>{const meta=item.meta.hi.files?.[file5.path]??{artifact:"copied"};const rendered=meta.artifact==="built"||meta.artifact==="authored"&&meta.template===true;const builder=meta.builder===undefined?undefined:builders2[meta.builder];if(rendered&&meta.builder!==undefined&&builder===undefined){throw new Error(`Registry Item ${item.name} names unknown builder ${meta.builder}`)}const targets=instances(meta.expand,context3).flatMap((scope3)=>{const values=templateContext(context3,scope3);const location2=renderLocation(file5.target,values);return location2===undefined||!matchesWhen(meta.when,context3,scope3)?[]:[{location:location2,scope:scope3,values}]});return await Promise.all(targets.map(async({location:location2,scope:scope3,values})=>{let content;if(rendered){const build2=await builder?.({context:context3,file:file5,item,scope:scope3});content=encoder3.encode(renderTemplate(file5.content,{...values,build:build2}))}else{content=meta.encoding==="base64"?new Uint8Array(Buffer.from(file5.content,"base64")):encoder3.encode(file5.content)}return{_tag:"File",artifact:meta.artifact,content,executable:meta.executable??false,item:item.name,path:location2}}))};var itemLinkMergeDependencyEffects=(item,context3)=>{const effects=[];const{merges=[],symlinks=[],workspaceDependencies=[]}=item.meta.hi;for(const link4 of symlinks){for(const scope3 of instances(link4.expand,context3)){const values=templateContext(context3,scope3);const location2=renderLocation(link4.path,values);const target=renderTemplate(link4.target,values);if(location2!==undefined&&target.length>0){effects.push({_tag:"Symlink",item:item.name,path:location2,target})}}}for(const merge6 of merges){for(const scope3 of instances(merge6.expand,context3)){const values=templateContext(context3,scope3);const target=renderLocation(merge6.target,values);if(target!==undefined){const value3=renderLeaves(merge6.value,values);effects.push({_tag:"Merge",format:merge6.format,item:item.name,target,value:value3})}}}for(const dependencies of workspaceDependencies){for(const scope3 of instances(dependencies.expand,context3)){if(!matchesWhen(dependencies.when,context3,scope3)){continue}const values=templateContext(context3,scope3);for(const[name2,version3]of Object.entries(dependencies.packages)){effects.push({_tag:"Dependency",item:item.name,name:name2,version:renderTemplate(version3,values),workspace:scope3?.path??"."})}}}return effects};var sortKey=(effect2)=>{if(effect2._tag==="Dependency"){return`${effect2.workspace}\x00dependency\x00${effect2.name}\x00${effect2.item}`}return effect2._tag==="Merge"?`${effect2.target}\x00merge\x00${effect2.item}`:`${effect2.path}\x00${effect2._tag}`};var materialize=async(items,context3,options3)=>{const builders2=options3?.builders??builders;const buildAgentFiles=options3?.buildHarnessAgentFiles??buildHarnessAgentFiles;const itemEffects=async(item)=>{const files=await Promise.all((item.files??[]).map(async(file5)=>await fileEffects({builders:builders2,context:context3,file:file5,item})));const manifest=item.meta.hi.harnessAdapters===true?await context3.loadSubagentManifest():undefined;const agentFiles=manifest===undefined?[]:buildAgentFiles({manifest,readRepositoryFile:context3.readRepositoryFile});return[...files.flat(),...itemLinkMergeDependencyEffects(item,context3),...agentFiles.map((agentFile)=>({_tag:"File",artifact:"built",content:encoder3.encode(agentFile.content),executable:false,item:item.name,path:agentFile.path}))]};const perItem=await Promise.all(items.map(itemEffects));const effects=perItem.flat();const locations=new Map;for(const effect2 of effects){if(effect2._tag==="File"||effect2._tag==="Symlink"){const owner=locations.get(effect2.path);if(owner!==undefined){throw new Error(`Registry Items ${owner} and ${effect2.item} both install ${effect2.path}`)}locations.set(effect2.path,effect2.item)}}const requiredTools=[...new Set(items.flatMap((item)=>item.meta.hi.requiredTools??[]))].toSorted();return{effects:effects.toSorted((left,right)=>sortKey(left).localeCompare(sortKey(right))),requiredTools}};var utf8=new TextDecoder("utf-8",{fatal:true});var decodeText2=(bytes)=>{if(bytes.includes(0)){return}try{return utf8.decode(bytes)}catch{return}};var normalizedKey=(bytes)=>{const text3=decodeText2(bytes);return text3===undefined?`binary:${Buffer.from(bytes).toString("base64")}`:`text:${text3.replaceAll(/\r\n?/gu,`
339
339
  `).split(`
340
340
  `).map((line)=>line.trimEnd()).join(`
341
341
  `).trimEnd()}`};var sameNormalized=(left,right)=>normalizedKey(left)===normalizedKey(right);var resolveItemNames=(catalog,packs)=>gen2(function*resolveItems(){const entries=new Map(catalog.items.map((entry)=>[entry.name,entry]));const roots=[corePackName,...packs.map((pack)=>itemNames.pack(pack))];const unknown2=packs.filter((pack)=>!entries.has(itemNames.pack(pack)));if(unknown2.length>0){return yield*new ProjectIntentError({detail:`Settings select Packs the ${catalog.version} Baseline does not provide: ${unknown2.join(", ")}`})}const resolved=new Set;const pending=[...roots];while(pending.length>0){const name2=pending.pop()??"";if(resolved.has(name2)){continue}const entry=entries.get(name2);if(entry===undefined){return yield*new RegistryIntegrityError({detail:`Registry Item ${name2} is referenced but not in the ${catalog.version} catalog`,url:catalog.name})}resolved.add(name2);pending.push(...entry.registryDependencies??[])}return[...resolved].toSorted()});import{existsSync as existsSync9,readFileSync as readFileSync8}from"node:fs";import path17 from"node:path";var Strings2=ArraySchema(String4);var SettingsDocument=Struct({assetProviderSlug:optional(String4),backlogProjectUrl:optional(String4),backlogProvider:optional(String4),commitGate:optional(Literals(["enabled","disabled"])),commitGateChecks:optional(Struct({repository:optional(Struct({formatCheck:optional(String4),lint:optional(String4)}))})),lint:optional(Struct({exclude:optional(Strings2),scopes:optional(Strings2)})),packs:optional(Strings2),registry:optional(String4),repositoryManager:optional(String4),requiredTools:optional(Strings2),typescript:optional(Struct({compilerProjects:optional(Strings2)}))});var decodeSettings=decodeUnknownEffect2(fromJsonString2(SettingsDocument));var repositoryChecks=(document)=>{const repository=document.commitGateChecks?.repository;const lint=repository?.lint?.trim();const formatCheck2=repository?.formatCheck?.trim();if((lint===undefined||lint==="")&&(formatCheck2===undefined||formatCheck2==="")){return}return{...formatCheck2===undefined||formatCheck2===""?{}:{formatCheck:formatCheck2},...lint===undefined||lint===""?{}:{lint}}};var sorted2=(values)=>[...new Set(values)].toSorted();var containedPath=(value3)=>{const normalized=path17.posix.normalize(value3.trim()).replace(/\/$/u,"")||".";const escapes=normalized.includes("\\")||path17.posix.isAbsolute(normalized)||/^[A-Za-z]:/u.test(normalized)||normalized.split("/").includes("..");return escapes?undefined:normalized};var containedPaths=(label,values)=>{const escaping=values.filter((value3)=>containedPath(value3)===undefined);return escaping.length>0?fail6(new ProjectIntentError({detail:`${label} must stay inside the repository: ${escaping.join(", ")}`})):succeed6(sorted2(values.flatMap((value3)=>containedPath(value3)??[])))};var readSettingsDocument=(root)=>gen2(function*readDocument(){const absolute=path17.join(root,settingsPath);if(!existsSync9(absolute)){return yield*undefined_2}const text3=yield*try_3({catch:(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:settingsPath}),try:()=>readFileSync8(absolute,"utf-8")});return yield*decodeSettings(text3).pipe(mapError3((cause)=>new ProjectIntentError({detail:`Invalid ${settingsPath}: ${cause.message}`})))});var readProjectIntent=(root)=>gen2(function*readIntent(){const document=yield*readSettingsDocument(root);if(document===undefined){return yield*new ProjectIntentError({detail:`${settingsPath} is missing. Run hi init to select Packs and Software Scopes.`})}if(document.packs===undefined){return yield*new ProjectIntentError({detail:`${settingsPath} selects no Packs. Run hi init to select Packs.`})}const repository=repositoryChecks(document);const softwareScopes=yield*containedPaths("Software Scopes",document.lint?.scopes??[]);const compilerProjects=document.typescript?.compilerProjects;const typescript=compilerProjects===undefined?undefined:{compilerProjects:yield*containedPaths("Compiler Projects",compilerProjects)};return{lintExclude:sorted2(document.lint?.exclude??[]),packs:sorted2(document.packs),requiredTools:sorted2(document.requiredTools??[]),softwareScopes,...document.assetProviderSlug===undefined?{}:{assetProviderSlug:document.assetProviderSlug},...document.backlogProjectUrl===undefined?{}:{backlogProjectUrl:document.backlogProjectUrl},...document.backlogProvider===undefined?{}:{backlogProvider:document.backlogProvider},...document.commitGate===undefined?{}:{commitGate:document.commitGate},...repository===undefined?{}:{commitGateChecks:{repository}},...document.registry===undefined?{}:{registry:document.registry},...document.repositoryManager===undefined?{}:{repositoryManager:document.repositoryManager},...typescript===undefined?{}:{typescript}}});var isRecord6=(value3)=>typeof value3==="object"&&value3!==null&&!Array.isArray(value3);var writeInitSettings=(root,intent)=>try_3({catch:(cause)=>new InstallerFilesystemError({detail:cause instanceof Error?cause.message:String(cause),path:settingsPath}),try:()=>{const absolute=path17.join(root,settingsPath);const existing=existsSync9(absolute)?JSON.parse(readFileSync8(absolute,"utf-8")):{};const{backlogProjectUrl:_backlogProjectUrl,baselineVersion:_baseline,cliVersion:_cli,...kept}=isRecord6(existing)?existing:{};const lint=isRecord6(kept.lint)?kept.lint:{};const document={...kept,lint:{...lint,exclude:sorted2(intent.lintExclude),scopes:sorted2(intent.softwareScopes)},packs:sorted2(intent.packs),requiredTools:sorted2(intent.requiredTools),...intent.assetProviderSlug===undefined?{}:{assetProviderSlug:intent.assetProviderSlug},...intent.backlogProjectUrl===undefined?{}:{backlogProjectUrl:intent.backlogProjectUrl},...intent.backlogProvider===undefined?{}:{backlogProvider:intent.backlogProvider},...intent.commitGate===undefined?{}:{commitGate:intent.commitGate},...intent.registry===undefined?{}:{registry:intent.registry},...intent.repositoryManager===undefined?{}:{repositoryManager:intent.repositoryManager}};writeFileAtomic(absolute,canonicalJson(document))}});var effectForEach=forEach2;var absentCodes=new Set(["ENOENT","ENOTDIR","ELOOP"]);var isAbsent=(error2)=>error2 instanceof Error&&("code"in error2)&&absentCodes.has(String(error2.code));var readAbsentAsUndefined=(read2)=>{try{return read2()}catch(error2){if(isAbsent(error2)){return}throw error2}};var isConfined=(relative)=>{const normalized=path18.posix.normalize(relative);return!path18.isAbsolute(relative)&&normalized!==".."&&!normalized.startsWith("../")};var localRepository=(root)=>{const realRoot=realpathSync2(root);const insideRoot=(real)=>{const relative=path18.relative(realRoot,real);return relative!==".."&&!relative.startsWith(`..${path18.sep}`)&&!path18.isAbsolute(relative)};return{file:(relative)=>readAbsentAsUndefined(()=>{const real=realpathSync2(path18.join(root,relative));return insideRoot(real)&&!lstatSync(real).isDirectory()?readFileSync9(real):undefined}),link:(relative)=>readAbsentAsUndefined(()=>{const absolute=path18.join(root,relative);return lstatSync(absolute).isSymbolicLink()?readlinkSync(absolute):undefined})}};var decoder=new TextDecoder;var byPath2=(materialized)=>new Map(materialized.effects.flatMap((effect2)=>effect2._tag==="File"||effect2._tag==="Symlink"?[[effect2.path,effect2]]:[]));var fileKey=(effect2)=>effect2?._tag==="File"?normalizedKey(effect2.content):undefined;var linkTarget=(effect2)=>effect2?._tag==="Symlink"?effect2.target:undefined;var current={action:"current"};var classifySymlink=(facts,local)=>{const expected=linkTarget(facts.latest)??linkTarget(facts.installed)??facts.failedLink?.target;const actual=local.link(facts.path);if(actual!==undefined&&actual===expected){return current}const installedTarget=linkTarget(facts.installed);if(actual!==undefined&&actual===installedTarget){return{action:"update-available",detail:`Link target changes to ${expected??""}`}}if(actual===undefined&&installedTarget===undefined&&facts.recorded===undefined){return{action:"update-available",detail:"New link in the latest Baseline"}}const found=actual===undefined?"missing":`points to ${actual}`;return{action:"link-failed",detail:`${found}; expected ${expected??""}${facts.failedLink===undefined?"":` (${facts.failedLink.reason})`}`}};var classifyHarness=(facts,localKey)=>{if(localKey===undefined){return facts.recorded===undefined?{action:"stale",detail:`Not yet built from ${subagentManifestPath}; run hi update`}:{action:"missing"}}if(localKey!==fileKey(facts.installed)){return{action:"stale",detail:`Out of date with ${subagentManifestPath}; run hi update`}}return fileKey(facts.installed)===fileKey(facts.latest)?current:{action:"update-available"}};var classifyFile=(facts,artifact,localKey)=>{const installedKey=fileKey(facts.installed);const latestKey=fileKey(facts.latest);if(artifact==="authored"){if(localKey!==undefined){return current}return facts.installed===undefined?{action:"update-available"}:{action:"missing"}}if(artifact==="built"&&facts.installed!==undefined&&installedKey!==fileKey(facts.currentShape)){return{action:"shape-drift",detail:"Re-rendering with the current repository shape differs"}}if(localKey===undefined){return facts.installed===undefined?{action:"update-available"}:{action:"missing"}}if(localKey===latestKey){return current}if(localKey===installedKey){return{action:"update-available"}}return artifact==="built"||installedKey===latestKey?{action:"local-edit"}:{action:"conflict"}};var classify=(facts,local)=>{if(facts.recorded!==undefined&&facts.latest===undefined){return{action:"stale",detail:"Recorded in the Installed Record; not in the compared Baseline"}}const effect2=facts.latest??facts.installed??facts.currentShape;if(effect2?._tag==="Symlink"||effect2===undefined&&facts.failedLink!==undefined){return classifySymlink(facts,local)}if(effect2===undefined){return current}const bytes=local.file(facts.path);const localKey=bytes===undefined?undefined:normalizedKey(bytes);if(facts.harness&&facts.installed!==undefined){return classifyHarness(facts,localKey)}const shapeChangesPath=facts.installed===undefined!==(facts.currentShape===undefined);if(shapeChangesPath&&!(effect2.artifact==="authored"&&localKey!==undefined)){return{action:"shape-drift",detail:"The current repository shape adds or removes this path"}}return classifyFile(facts,effect2.artifact,localKey)};var authoredTemplateChanges=(installed,latest,latestVersion)=>[...latest.values()].flatMap((effect2)=>{const before=installed.get(effect2.path);return effect2._tag==="File"&&effect2.artifact==="authored"&&before!==undefined&&fileKey(before)!==fileKey(effect2)?[{detail:`Authored template changed in Baseline ${latestVersion}; the file is repository-owned and never compared.`,path:effect2.path}]:[]});var unselectedDetectedPacks=(catalog,detection,selected)=>detectedPacks(detection,catalog).flatMap(({evidence,id})=>selected.has(id)?[]:[{detail:`Pack ${id} is detected (${evidence.join(", ")}) but not selected in .devpunks/settings.json packs.`}]);var fetchItems=(client,catalog,names)=>effectForEach(names,(name2)=>client.fetchItem(catalog,name2),{concurrency:8});var fetchLatestBaseline=(client,packs,reusable)=>client.fetchLatestCatalog.pipe(flatMap3((catalog)=>{const provided=new Set(catalog.items.map((entry)=>entry.name));const unknownPacks=packs.filter((pack)=>!provided.has(itemNames.pack(pack)));const items=catalog.version===reusable?.catalog.version?succeed6(reusable.items):resolveItemNames(catalog,packs.filter((pack)=>provided.has(itemNames.pack(pack)))).pipe(flatMap3((names)=>fetchItems(client,catalog,names)));return items.pipe(map6((resolved)=>some2({catalog,items:resolved,unknownPacks})))}),catchTag2("RegistryUnavailable",()=>succeedNone2));var requireInstalledRecord=(record2)=>record2===undefined?fail6(new InstallerFilesystemError({detail:"No Installed Record. Run hi update to install the Baseline (hi init for a new repository).",path:installedRecordPath})):succeed6(record2);var rowArtifact=(effect2,recorded)=>{if(effect2===undefined){return recorded?.artifact??"symlink"}return effect2._tag==="Symlink"?"symlink":effect2.artifact};var runDiff=fn2("Registry.runDiff")(function*runDiff2(input){const{client,root}=input;const materialize2=input.materialize??materialize;const record2=yield*readInstalledRecord(root).pipe(flatMap3(requireInstalledRecord));const settings=yield*readProjectIntent(root);const manifest=yield*tryPromise2({catch:(cause)=>new InstallerFilesystemError({detail:String(cause),path:subagentManifestPath}),try:async()=>await(input.loadSubagentManifest??loadSubagentManifest)(root)});const currentShape=yield*(input.detectShape??detectShape)(root,record2.shape.packs);const detection=yield*(input.detectRepository??repositoryDetection)(root);const installedCatalog=yield*client.fetchCatalog(record2.baseline);const installedItems=yield*fetchItems(client,installedCatalog,record2.items);const latestShape={...record2.shape,packs:[...new Set(settings.packs)].toSorted()};const samePacks=latestShape.packs.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@punks/cli",
3
- "version": "6.2.0",
3
+ "version": "6.2.1",
4
4
  "description": "Harness Intelligence scaffolding CLI",
5
5
  "homepage": "https://github.com/wearedevpunks/harness-intelligence/tree/main/apps/cli#readme",
6
6
  "bugs": {